1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution analysis 10 // engine, which is used primarily to analyze expressions involving induction 11 // variables in loops. 12 // 13 // There are several aspects to this library. First is the representation of 14 // scalar expressions, which are represented as subclasses of the SCEV class. 15 // These classes are used to represent certain types of subexpressions that we 16 // can handle. We only create one SCEV of a particular shape, so 17 // pointer-comparisons for equality are legal. 18 // 19 // One important aspect of the SCEV objects is that they are never cyclic, even 20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 22 // recurrence) then we represent it directly as a recurrence node, otherwise we 23 // represent it as a SCEVUnknown node. 24 // 25 // In addition to being able to represent expressions of various types, we also 26 // have folders that are used to build the *canonical* representation for a 27 // particular expression. These folders are capable of using a variety of 28 // rewrite rules to simplify the expressions. 29 // 30 // Once the folders are defined, we can implement the more interesting 31 // higher-level code, such as the code that recognizes PHI nodes of various 32 // types, computes the execution count of a loop, etc. 33 // 34 // TODO: We should use these routines and value representations to implement 35 // dependence analysis! 36 // 37 //===----------------------------------------------------------------------===// 38 // 39 // There are several good references for the techniques used in this analysis. 40 // 41 // Chains of recurrences -- a method to expedite the evaluation 42 // of closed-form functions 43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 44 // 45 // On computational properties of chains of recurrences 46 // Eugene V. Zima 47 // 48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 49 // Robert A. van Engelen 50 // 51 // Efficient Symbolic Analysis for Optimizing Compilers 52 // Robert A. van Engelen 53 // 54 // Using the chains of recurrences algebra for data dependence testing and 55 // induction variable substitution 56 // MS Thesis, Johnie Birch 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 83 #include "llvm/Analysis/TargetLibraryInfo.h" 84 #include "llvm/Analysis/ValueTracking.h" 85 #include "llvm/Config/llvm-config.h" 86 #include "llvm/IR/Argument.h" 87 #include "llvm/IR/BasicBlock.h" 88 #include "llvm/IR/CFG.h" 89 #include "llvm/IR/CallSite.h" 90 #include "llvm/IR/Constant.h" 91 #include "llvm/IR/ConstantRange.h" 92 #include "llvm/IR/Constants.h" 93 #include "llvm/IR/DataLayout.h" 94 #include "llvm/IR/DerivedTypes.h" 95 #include "llvm/IR/Dominators.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/GlobalAlias.h" 98 #include "llvm/IR/GlobalValue.h" 99 #include "llvm/IR/GlobalVariable.h" 100 #include "llvm/IR/InstIterator.h" 101 #include "llvm/IR/InstrTypes.h" 102 #include "llvm/IR/Instruction.h" 103 #include "llvm/IR/Instructions.h" 104 #include "llvm/IR/IntrinsicInst.h" 105 #include "llvm/IR/Intrinsics.h" 106 #include "llvm/IR/LLVMContext.h" 107 #include "llvm/IR/Metadata.h" 108 #include "llvm/IR/Operator.h" 109 #include "llvm/IR/PatternMatch.h" 110 #include "llvm/IR/Type.h" 111 #include "llvm/IR/Use.h" 112 #include "llvm/IR/User.h" 113 #include "llvm/IR/Value.h" 114 #include "llvm/IR/Verifier.h" 115 #include "llvm/Pass.h" 116 #include "llvm/Support/Casting.h" 117 #include "llvm/Support/CommandLine.h" 118 #include "llvm/Support/Compiler.h" 119 #include "llvm/Support/Debug.h" 120 #include "llvm/Support/ErrorHandling.h" 121 #include "llvm/Support/KnownBits.h" 122 #include "llvm/Support/SaveAndRestore.h" 123 #include "llvm/Support/raw_ostream.h" 124 #include <algorithm> 125 #include <cassert> 126 #include <climits> 127 #include <cstddef> 128 #include <cstdint> 129 #include <cstdlib> 130 #include <map> 131 #include <memory> 132 #include <tuple> 133 #include <utility> 134 #include <vector> 135 136 using namespace llvm; 137 138 #define DEBUG_TYPE "scalar-evolution" 139 140 STATISTIC(NumArrayLenItCounts, 141 "Number of trip counts computed with array length"); 142 STATISTIC(NumTripCountsComputed, 143 "Number of loops with predictable loop counts"); 144 STATISTIC(NumTripCountsNotComputed, 145 "Number of loops without predictable loop counts"); 146 STATISTIC(NumBruteForceTripCountsComputed, 147 "Number of loops with trip counts computed by force"); 148 149 static cl::opt<unsigned> 150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 151 cl::desc("Maximum number of iterations SCEV will " 152 "symbolically execute a constant " 153 "derived loop"), 154 cl::init(100)); 155 156 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 157 static cl::opt<bool> VerifySCEV( 158 "verify-scev", cl::Hidden, 159 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 160 static cl::opt<bool> 161 VerifySCEVMap("verify-scev-maps", cl::Hidden, 162 cl::desc("Verify no dangling value in ScalarEvolution's " 163 "ExprValueMap (slow)")); 164 165 static cl::opt<bool> VerifyIR( 166 "scev-verify-ir", cl::Hidden, 167 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 168 cl::init(false)); 169 170 static cl::opt<unsigned> MulOpsInlineThreshold( 171 "scev-mulops-inline-threshold", cl::Hidden, 172 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 173 cl::init(32)); 174 175 static cl::opt<unsigned> AddOpsInlineThreshold( 176 "scev-addops-inline-threshold", cl::Hidden, 177 cl::desc("Threshold for inlining addition operands into a SCEV"), 178 cl::init(500)); 179 180 static cl::opt<unsigned> MaxSCEVCompareDepth( 181 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 182 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 183 cl::init(32)); 184 185 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 186 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 187 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 188 cl::init(2)); 189 190 static cl::opt<unsigned> MaxValueCompareDepth( 191 "scalar-evolution-max-value-compare-depth", cl::Hidden, 192 cl::desc("Maximum depth of recursive value complexity comparisons"), 193 cl::init(2)); 194 195 static cl::opt<unsigned> 196 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 197 cl::desc("Maximum depth of recursive arithmetics"), 198 cl::init(32)); 199 200 static cl::opt<unsigned> MaxConstantEvolvingDepth( 201 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 202 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 203 204 static cl::opt<unsigned> 205 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 206 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 207 cl::init(8)); 208 209 static cl::opt<unsigned> 210 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 211 cl::desc("Max coefficients in AddRec during evolving"), 212 cl::init(8)); 213 214 static cl::opt<unsigned> 215 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 216 cl::desc("Size of the expression which is considered huge"), 217 cl::init(4096)); 218 219 //===----------------------------------------------------------------------===// 220 // SCEV class definitions 221 //===----------------------------------------------------------------------===// 222 223 //===----------------------------------------------------------------------===// 224 // Implementation of the SCEV class. 225 // 226 227 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 228 LLVM_DUMP_METHOD void SCEV::dump() const { 229 print(dbgs()); 230 dbgs() << '\n'; 231 } 232 #endif 233 234 void SCEV::print(raw_ostream &OS) const { 235 switch (static_cast<SCEVTypes>(getSCEVType())) { 236 case scConstant: 237 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 238 return; 239 case scTruncate: { 240 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 241 const SCEV *Op = Trunc->getOperand(); 242 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 243 << *Trunc->getType() << ")"; 244 return; 245 } 246 case scZeroExtend: { 247 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 248 const SCEV *Op = ZExt->getOperand(); 249 OS << "(zext " << *Op->getType() << " " << *Op << " to " 250 << *ZExt->getType() << ")"; 251 return; 252 } 253 case scSignExtend: { 254 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 255 const SCEV *Op = SExt->getOperand(); 256 OS << "(sext " << *Op->getType() << " " << *Op << " to " 257 << *SExt->getType() << ")"; 258 return; 259 } 260 case scAddRecExpr: { 261 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 262 OS << "{" << *AR->getOperand(0); 263 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 264 OS << ",+," << *AR->getOperand(i); 265 OS << "}<"; 266 if (AR->hasNoUnsignedWrap()) 267 OS << "nuw><"; 268 if (AR->hasNoSignedWrap()) 269 OS << "nsw><"; 270 if (AR->hasNoSelfWrap() && 271 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 272 OS << "nw><"; 273 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 274 OS << ">"; 275 return; 276 } 277 case scAddExpr: 278 case scMulExpr: 279 case scUMaxExpr: 280 case scSMaxExpr: { 281 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 282 const char *OpStr = nullptr; 283 switch (NAry->getSCEVType()) { 284 case scAddExpr: OpStr = " + "; break; 285 case scMulExpr: OpStr = " * "; break; 286 case scUMaxExpr: OpStr = " umax "; break; 287 case scSMaxExpr: OpStr = " smax "; break; 288 } 289 OS << "("; 290 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 291 I != E; ++I) { 292 OS << **I; 293 if (std::next(I) != E) 294 OS << OpStr; 295 } 296 OS << ")"; 297 switch (NAry->getSCEVType()) { 298 case scAddExpr: 299 case scMulExpr: 300 if (NAry->hasNoUnsignedWrap()) 301 OS << "<nuw>"; 302 if (NAry->hasNoSignedWrap()) 303 OS << "<nsw>"; 304 } 305 return; 306 } 307 case scUDivExpr: { 308 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 309 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 310 return; 311 } 312 case scUnknown: { 313 const SCEVUnknown *U = cast<SCEVUnknown>(this); 314 Type *AllocTy; 315 if (U->isSizeOf(AllocTy)) { 316 OS << "sizeof(" << *AllocTy << ")"; 317 return; 318 } 319 if (U->isAlignOf(AllocTy)) { 320 OS << "alignof(" << *AllocTy << ")"; 321 return; 322 } 323 324 Type *CTy; 325 Constant *FieldNo; 326 if (U->isOffsetOf(CTy, FieldNo)) { 327 OS << "offsetof(" << *CTy << ", "; 328 FieldNo->printAsOperand(OS, false); 329 OS << ")"; 330 return; 331 } 332 333 // Otherwise just print it normally. 334 U->getValue()->printAsOperand(OS, false); 335 return; 336 } 337 case scCouldNotCompute: 338 OS << "***COULDNOTCOMPUTE***"; 339 return; 340 } 341 llvm_unreachable("Unknown SCEV kind!"); 342 } 343 344 Type *SCEV::getType() const { 345 switch (static_cast<SCEVTypes>(getSCEVType())) { 346 case scConstant: 347 return cast<SCEVConstant>(this)->getType(); 348 case scTruncate: 349 case scZeroExtend: 350 case scSignExtend: 351 return cast<SCEVCastExpr>(this)->getType(); 352 case scAddRecExpr: 353 case scMulExpr: 354 case scUMaxExpr: 355 case scSMaxExpr: 356 return cast<SCEVNAryExpr>(this)->getType(); 357 case scAddExpr: 358 return cast<SCEVAddExpr>(this)->getType(); 359 case scUDivExpr: 360 return cast<SCEVUDivExpr>(this)->getType(); 361 case scUnknown: 362 return cast<SCEVUnknown>(this)->getType(); 363 case scCouldNotCompute: 364 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 365 } 366 llvm_unreachable("Unknown SCEV kind!"); 367 } 368 369 bool SCEV::isZero() const { 370 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 371 return SC->getValue()->isZero(); 372 return false; 373 } 374 375 bool SCEV::isOne() const { 376 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 377 return SC->getValue()->isOne(); 378 return false; 379 } 380 381 bool SCEV::isAllOnesValue() const { 382 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 383 return SC->getValue()->isMinusOne(); 384 return false; 385 } 386 387 bool SCEV::isNonConstantNegative() const { 388 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 389 if (!Mul) return false; 390 391 // If there is a constant factor, it will be first. 392 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 393 if (!SC) return false; 394 395 // Return true if the value is negative, this matches things like (-42 * V). 396 return SC->getAPInt().isNegative(); 397 } 398 399 SCEVCouldNotCompute::SCEVCouldNotCompute() : 400 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 401 402 bool SCEVCouldNotCompute::classof(const SCEV *S) { 403 return S->getSCEVType() == scCouldNotCompute; 404 } 405 406 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 407 FoldingSetNodeID ID; 408 ID.AddInteger(scConstant); 409 ID.AddPointer(V); 410 void *IP = nullptr; 411 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 412 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 413 UniqueSCEVs.InsertNode(S, IP); 414 return S; 415 } 416 417 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 418 return getConstant(ConstantInt::get(getContext(), Val)); 419 } 420 421 const SCEV * 422 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 423 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 424 return getConstant(ConstantInt::get(ITy, V, isSigned)); 425 } 426 427 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 428 unsigned SCEVTy, const SCEV *op, Type *ty) 429 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {} 430 431 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 432 const SCEV *op, Type *ty) 433 : SCEVCastExpr(ID, scTruncate, op, ty) { 434 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 435 "Cannot truncate non-integer value!"); 436 } 437 438 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 439 const SCEV *op, Type *ty) 440 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 441 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 442 "Cannot zero extend non-integer value!"); 443 } 444 445 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 446 const SCEV *op, Type *ty) 447 : SCEVCastExpr(ID, scSignExtend, op, ty) { 448 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 449 "Cannot sign extend non-integer value!"); 450 } 451 452 void SCEVUnknown::deleted() { 453 // Clear this SCEVUnknown from various maps. 454 SE->forgetMemoizedResults(this); 455 456 // Remove this SCEVUnknown from the uniquing map. 457 SE->UniqueSCEVs.RemoveNode(this); 458 459 // Release the value. 460 setValPtr(nullptr); 461 } 462 463 void SCEVUnknown::allUsesReplacedWith(Value *New) { 464 // Remove this SCEVUnknown from the uniquing map. 465 SE->UniqueSCEVs.RemoveNode(this); 466 467 // Update this SCEVUnknown to point to the new value. This is needed 468 // because there may still be outstanding SCEVs which still point to 469 // this SCEVUnknown. 470 setValPtr(New); 471 } 472 473 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 474 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 475 if (VCE->getOpcode() == Instruction::PtrToInt) 476 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 477 if (CE->getOpcode() == Instruction::GetElementPtr && 478 CE->getOperand(0)->isNullValue() && 479 CE->getNumOperands() == 2) 480 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 481 if (CI->isOne()) { 482 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 483 ->getElementType(); 484 return true; 485 } 486 487 return false; 488 } 489 490 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 491 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 492 if (VCE->getOpcode() == Instruction::PtrToInt) 493 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 494 if (CE->getOpcode() == Instruction::GetElementPtr && 495 CE->getOperand(0)->isNullValue()) { 496 Type *Ty = 497 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 498 if (StructType *STy = dyn_cast<StructType>(Ty)) 499 if (!STy->isPacked() && 500 CE->getNumOperands() == 3 && 501 CE->getOperand(1)->isNullValue()) { 502 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 503 if (CI->isOne() && 504 STy->getNumElements() == 2 && 505 STy->getElementType(0)->isIntegerTy(1)) { 506 AllocTy = STy->getElementType(1); 507 return true; 508 } 509 } 510 } 511 512 return false; 513 } 514 515 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 516 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 517 if (VCE->getOpcode() == Instruction::PtrToInt) 518 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 519 if (CE->getOpcode() == Instruction::GetElementPtr && 520 CE->getNumOperands() == 3 && 521 CE->getOperand(0)->isNullValue() && 522 CE->getOperand(1)->isNullValue()) { 523 Type *Ty = 524 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 525 // Ignore vector types here so that ScalarEvolutionExpander doesn't 526 // emit getelementptrs that index into vectors. 527 if (Ty->isStructTy() || Ty->isArrayTy()) { 528 CTy = Ty; 529 FieldNo = CE->getOperand(2); 530 return true; 531 } 532 } 533 534 return false; 535 } 536 537 //===----------------------------------------------------------------------===// 538 // SCEV Utilities 539 //===----------------------------------------------------------------------===// 540 541 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 542 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 543 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 544 /// have been previously deemed to be "equally complex" by this routine. It is 545 /// intended to avoid exponential time complexity in cases like: 546 /// 547 /// %a = f(%x, %y) 548 /// %b = f(%a, %a) 549 /// %c = f(%b, %b) 550 /// 551 /// %d = f(%x, %y) 552 /// %e = f(%d, %d) 553 /// %f = f(%e, %e) 554 /// 555 /// CompareValueComplexity(%f, %c) 556 /// 557 /// Since we do not continue running this routine on expression trees once we 558 /// have seen unequal values, there is no need to track them in the cache. 559 static int 560 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 561 const LoopInfo *const LI, Value *LV, Value *RV, 562 unsigned Depth) { 563 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 564 return 0; 565 566 // Order pointer values after integer values. This helps SCEVExpander form 567 // GEPs. 568 bool LIsPointer = LV->getType()->isPointerTy(), 569 RIsPointer = RV->getType()->isPointerTy(); 570 if (LIsPointer != RIsPointer) 571 return (int)LIsPointer - (int)RIsPointer; 572 573 // Compare getValueID values. 574 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 575 if (LID != RID) 576 return (int)LID - (int)RID; 577 578 // Sort arguments by their position. 579 if (const auto *LA = dyn_cast<Argument>(LV)) { 580 const auto *RA = cast<Argument>(RV); 581 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 582 return (int)LArgNo - (int)RArgNo; 583 } 584 585 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 586 const auto *RGV = cast<GlobalValue>(RV); 587 588 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 589 auto LT = GV->getLinkage(); 590 return !(GlobalValue::isPrivateLinkage(LT) || 591 GlobalValue::isInternalLinkage(LT)); 592 }; 593 594 // Use the names to distinguish the two values, but only if the 595 // names are semantically important. 596 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 597 return LGV->getName().compare(RGV->getName()); 598 } 599 600 // For instructions, compare their loop depth, and their operand count. This 601 // is pretty loose. 602 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 603 const auto *RInst = cast<Instruction>(RV); 604 605 // Compare loop depths. 606 const BasicBlock *LParent = LInst->getParent(), 607 *RParent = RInst->getParent(); 608 if (LParent != RParent) { 609 unsigned LDepth = LI->getLoopDepth(LParent), 610 RDepth = LI->getLoopDepth(RParent); 611 if (LDepth != RDepth) 612 return (int)LDepth - (int)RDepth; 613 } 614 615 // Compare the number of operands. 616 unsigned LNumOps = LInst->getNumOperands(), 617 RNumOps = RInst->getNumOperands(); 618 if (LNumOps != RNumOps) 619 return (int)LNumOps - (int)RNumOps; 620 621 for (unsigned Idx : seq(0u, LNumOps)) { 622 int Result = 623 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 624 RInst->getOperand(Idx), Depth + 1); 625 if (Result != 0) 626 return Result; 627 } 628 } 629 630 EqCacheValue.unionSets(LV, RV); 631 return 0; 632 } 633 634 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 635 // than RHS, respectively. A three-way result allows recursive comparisons to be 636 // more efficient. 637 static int CompareSCEVComplexity( 638 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 639 EquivalenceClasses<const Value *> &EqCacheValue, 640 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 641 DominatorTree &DT, unsigned Depth = 0) { 642 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 643 if (LHS == RHS) 644 return 0; 645 646 // Primarily, sort the SCEVs by their getSCEVType(). 647 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 648 if (LType != RType) 649 return (int)LType - (int)RType; 650 651 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 652 return 0; 653 // Aside from the getSCEVType() ordering, the particular ordering 654 // isn't very important except that it's beneficial to be consistent, 655 // so that (a + b) and (b + a) don't end up as different expressions. 656 switch (static_cast<SCEVTypes>(LType)) { 657 case scUnknown: { 658 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 659 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 660 661 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 662 RU->getValue(), Depth + 1); 663 if (X == 0) 664 EqCacheSCEV.unionSets(LHS, RHS); 665 return X; 666 } 667 668 case scConstant: { 669 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 670 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 671 672 // Compare constant values. 673 const APInt &LA = LC->getAPInt(); 674 const APInt &RA = RC->getAPInt(); 675 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 676 if (LBitWidth != RBitWidth) 677 return (int)LBitWidth - (int)RBitWidth; 678 return LA.ult(RA) ? -1 : 1; 679 } 680 681 case scAddRecExpr: { 682 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 683 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 684 685 // There is always a dominance between two recs that are used by one SCEV, 686 // so we can safely sort recs by loop header dominance. We require such 687 // order in getAddExpr. 688 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 689 if (LLoop != RLoop) { 690 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 691 assert(LHead != RHead && "Two loops share the same header?"); 692 if (DT.dominates(LHead, RHead)) 693 return 1; 694 else 695 assert(DT.dominates(RHead, LHead) && 696 "No dominance between recurrences used by one SCEV?"); 697 return -1; 698 } 699 700 // Addrec complexity grows with operand count. 701 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 702 if (LNumOps != RNumOps) 703 return (int)LNumOps - (int)RNumOps; 704 705 // Lexicographically compare. 706 for (unsigned i = 0; i != LNumOps; ++i) { 707 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 708 LA->getOperand(i), RA->getOperand(i), DT, 709 Depth + 1); 710 if (X != 0) 711 return X; 712 } 713 EqCacheSCEV.unionSets(LHS, RHS); 714 return 0; 715 } 716 717 case scAddExpr: 718 case scMulExpr: 719 case scSMaxExpr: 720 case scUMaxExpr: { 721 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 722 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 723 724 // Lexicographically compare n-ary expressions. 725 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 726 if (LNumOps != RNumOps) 727 return (int)LNumOps - (int)RNumOps; 728 729 for (unsigned i = 0; i != LNumOps; ++i) { 730 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 731 LC->getOperand(i), RC->getOperand(i), DT, 732 Depth + 1); 733 if (X != 0) 734 return X; 735 } 736 EqCacheSCEV.unionSets(LHS, RHS); 737 return 0; 738 } 739 740 case scUDivExpr: { 741 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 742 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 743 744 // Lexicographically compare udiv expressions. 745 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 746 RC->getLHS(), DT, Depth + 1); 747 if (X != 0) 748 return X; 749 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 750 RC->getRHS(), DT, Depth + 1); 751 if (X == 0) 752 EqCacheSCEV.unionSets(LHS, RHS); 753 return X; 754 } 755 756 case scTruncate: 757 case scZeroExtend: 758 case scSignExtend: { 759 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 760 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 761 762 // Compare cast expressions by operand. 763 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 764 LC->getOperand(), RC->getOperand(), DT, 765 Depth + 1); 766 if (X == 0) 767 EqCacheSCEV.unionSets(LHS, RHS); 768 return X; 769 } 770 771 case scCouldNotCompute: 772 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 773 } 774 llvm_unreachable("Unknown SCEV kind!"); 775 } 776 777 /// Given a list of SCEV objects, order them by their complexity, and group 778 /// objects of the same complexity together by value. When this routine is 779 /// finished, we know that any duplicates in the vector are consecutive and that 780 /// complexity is monotonically increasing. 781 /// 782 /// Note that we go take special precautions to ensure that we get deterministic 783 /// results from this routine. In other words, we don't want the results of 784 /// this to depend on where the addresses of various SCEV objects happened to 785 /// land in memory. 786 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 787 LoopInfo *LI, DominatorTree &DT) { 788 if (Ops.size() < 2) return; // Noop 789 790 EquivalenceClasses<const SCEV *> EqCacheSCEV; 791 EquivalenceClasses<const Value *> EqCacheValue; 792 if (Ops.size() == 2) { 793 // This is the common case, which also happens to be trivially simple. 794 // Special case it. 795 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 796 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 797 std::swap(LHS, RHS); 798 return; 799 } 800 801 // Do the rough sort by complexity. 802 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 803 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < 804 0; 805 }); 806 807 // Now that we are sorted by complexity, group elements of the same 808 // complexity. Note that this is, at worst, N^2, but the vector is likely to 809 // be extremely short in practice. Note that we take this approach because we 810 // do not want to depend on the addresses of the objects we are grouping. 811 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 812 const SCEV *S = Ops[i]; 813 unsigned Complexity = S->getSCEVType(); 814 815 // If there are any objects of the same complexity and same value as this 816 // one, group them. 817 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 818 if (Ops[j] == S) { // Found a duplicate. 819 // Move it to immediately after i'th element. 820 std::swap(Ops[i+1], Ops[j]); 821 ++i; // no need to rescan it. 822 if (i == e-2) return; // Done! 823 } 824 } 825 } 826 } 827 828 // Returns the size of the SCEV S. 829 static inline int sizeOfSCEV(const SCEV *S) { 830 struct FindSCEVSize { 831 int Size = 0; 832 833 FindSCEVSize() = default; 834 835 bool follow(const SCEV *S) { 836 ++Size; 837 // Keep looking at all operands of S. 838 return true; 839 } 840 841 bool isDone() const { 842 return false; 843 } 844 }; 845 846 FindSCEVSize F; 847 SCEVTraversal<FindSCEVSize> ST(F); 848 ST.visitAll(S); 849 return F.Size; 850 } 851 852 /// Returns true if the subtree of \p S contains at least HugeExprThreshold 853 /// nodes. 854 static bool isHugeExpression(const SCEV *S) { 855 return S->getExpressionSize() >= HugeExprThreshold; 856 } 857 858 /// Returns true of \p Ops contains a huge SCEV (see definition above). 859 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 860 return any_of(Ops, isHugeExpression); 861 } 862 863 namespace { 864 865 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 866 public: 867 // Computes the Quotient and Remainder of the division of Numerator by 868 // Denominator. 869 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 870 const SCEV *Denominator, const SCEV **Quotient, 871 const SCEV **Remainder) { 872 assert(Numerator && Denominator && "Uninitialized SCEV"); 873 874 SCEVDivision D(SE, Numerator, Denominator); 875 876 // Check for the trivial case here to avoid having to check for it in the 877 // rest of the code. 878 if (Numerator == Denominator) { 879 *Quotient = D.One; 880 *Remainder = D.Zero; 881 return; 882 } 883 884 if (Numerator->isZero()) { 885 *Quotient = D.Zero; 886 *Remainder = D.Zero; 887 return; 888 } 889 890 // A simple case when N/1. The quotient is N. 891 if (Denominator->isOne()) { 892 *Quotient = Numerator; 893 *Remainder = D.Zero; 894 return; 895 } 896 897 // Split the Denominator when it is a product. 898 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 899 const SCEV *Q, *R; 900 *Quotient = Numerator; 901 for (const SCEV *Op : T->operands()) { 902 divide(SE, *Quotient, Op, &Q, &R); 903 *Quotient = Q; 904 905 // Bail out when the Numerator is not divisible by one of the terms of 906 // the Denominator. 907 if (!R->isZero()) { 908 *Quotient = D.Zero; 909 *Remainder = Numerator; 910 return; 911 } 912 } 913 *Remainder = D.Zero; 914 return; 915 } 916 917 D.visit(Numerator); 918 *Quotient = D.Quotient; 919 *Remainder = D.Remainder; 920 } 921 922 // Except in the trivial case described above, we do not know how to divide 923 // Expr by Denominator for the following functions with empty implementation. 924 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 925 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 926 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 927 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 928 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 929 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 930 void visitUnknown(const SCEVUnknown *Numerator) {} 931 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 932 933 void visitConstant(const SCEVConstant *Numerator) { 934 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 935 APInt NumeratorVal = Numerator->getAPInt(); 936 APInt DenominatorVal = D->getAPInt(); 937 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 938 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 939 940 if (NumeratorBW > DenominatorBW) 941 DenominatorVal = DenominatorVal.sext(NumeratorBW); 942 else if (NumeratorBW < DenominatorBW) 943 NumeratorVal = NumeratorVal.sext(DenominatorBW); 944 945 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 946 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 947 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 948 Quotient = SE.getConstant(QuotientVal); 949 Remainder = SE.getConstant(RemainderVal); 950 return; 951 } 952 } 953 954 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 955 const SCEV *StartQ, *StartR, *StepQ, *StepR; 956 if (!Numerator->isAffine()) 957 return cannotDivide(Numerator); 958 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 959 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 960 // Bail out if the types do not match. 961 Type *Ty = Denominator->getType(); 962 if (Ty != StartQ->getType() || Ty != StartR->getType() || 963 Ty != StepQ->getType() || Ty != StepR->getType()) 964 return cannotDivide(Numerator); 965 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 966 Numerator->getNoWrapFlags()); 967 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 968 Numerator->getNoWrapFlags()); 969 } 970 971 void visitAddExpr(const SCEVAddExpr *Numerator) { 972 SmallVector<const SCEV *, 2> Qs, Rs; 973 Type *Ty = Denominator->getType(); 974 975 for (const SCEV *Op : Numerator->operands()) { 976 const SCEV *Q, *R; 977 divide(SE, Op, Denominator, &Q, &R); 978 979 // Bail out if types do not match. 980 if (Ty != Q->getType() || Ty != R->getType()) 981 return cannotDivide(Numerator); 982 983 Qs.push_back(Q); 984 Rs.push_back(R); 985 } 986 987 if (Qs.size() == 1) { 988 Quotient = Qs[0]; 989 Remainder = Rs[0]; 990 return; 991 } 992 993 Quotient = SE.getAddExpr(Qs); 994 Remainder = SE.getAddExpr(Rs); 995 } 996 997 void visitMulExpr(const SCEVMulExpr *Numerator) { 998 SmallVector<const SCEV *, 2> Qs; 999 Type *Ty = Denominator->getType(); 1000 1001 bool FoundDenominatorTerm = false; 1002 for (const SCEV *Op : Numerator->operands()) { 1003 // Bail out if types do not match. 1004 if (Ty != Op->getType()) 1005 return cannotDivide(Numerator); 1006 1007 if (FoundDenominatorTerm) { 1008 Qs.push_back(Op); 1009 continue; 1010 } 1011 1012 // Check whether Denominator divides one of the product operands. 1013 const SCEV *Q, *R; 1014 divide(SE, Op, Denominator, &Q, &R); 1015 if (!R->isZero()) { 1016 Qs.push_back(Op); 1017 continue; 1018 } 1019 1020 // Bail out if types do not match. 1021 if (Ty != Q->getType()) 1022 return cannotDivide(Numerator); 1023 1024 FoundDenominatorTerm = true; 1025 Qs.push_back(Q); 1026 } 1027 1028 if (FoundDenominatorTerm) { 1029 Remainder = Zero; 1030 if (Qs.size() == 1) 1031 Quotient = Qs[0]; 1032 else 1033 Quotient = SE.getMulExpr(Qs); 1034 return; 1035 } 1036 1037 if (!isa<SCEVUnknown>(Denominator)) 1038 return cannotDivide(Numerator); 1039 1040 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1041 ValueToValueMap RewriteMap; 1042 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1043 cast<SCEVConstant>(Zero)->getValue(); 1044 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1045 1046 if (Remainder->isZero()) { 1047 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1048 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1049 cast<SCEVConstant>(One)->getValue(); 1050 Quotient = 1051 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1052 return; 1053 } 1054 1055 // Quotient is (Numerator - Remainder) divided by Denominator. 1056 const SCEV *Q, *R; 1057 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1058 // This SCEV does not seem to simplify: fail the division here. 1059 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1060 return cannotDivide(Numerator); 1061 divide(SE, Diff, Denominator, &Q, &R); 1062 if (R != Zero) 1063 return cannotDivide(Numerator); 1064 Quotient = Q; 1065 } 1066 1067 private: 1068 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1069 const SCEV *Denominator) 1070 : SE(S), Denominator(Denominator) { 1071 Zero = SE.getZero(Denominator->getType()); 1072 One = SE.getOne(Denominator->getType()); 1073 1074 // We generally do not know how to divide Expr by Denominator. We 1075 // initialize the division to a "cannot divide" state to simplify the rest 1076 // of the code. 1077 cannotDivide(Numerator); 1078 } 1079 1080 // Convenience function for giving up on the division. We set the quotient to 1081 // be equal to zero and the remainder to be equal to the numerator. 1082 void cannotDivide(const SCEV *Numerator) { 1083 Quotient = Zero; 1084 Remainder = Numerator; 1085 } 1086 1087 ScalarEvolution &SE; 1088 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1089 }; 1090 1091 } // end anonymous namespace 1092 1093 //===----------------------------------------------------------------------===// 1094 // Simple SCEV method implementations 1095 //===----------------------------------------------------------------------===// 1096 1097 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1098 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1099 ScalarEvolution &SE, 1100 Type *ResultTy) { 1101 // Handle the simplest case efficiently. 1102 if (K == 1) 1103 return SE.getTruncateOrZeroExtend(It, ResultTy); 1104 1105 // We are using the following formula for BC(It, K): 1106 // 1107 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1108 // 1109 // Suppose, W is the bitwidth of the return value. We must be prepared for 1110 // overflow. Hence, we must assure that the result of our computation is 1111 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1112 // safe in modular arithmetic. 1113 // 1114 // However, this code doesn't use exactly that formula; the formula it uses 1115 // is something like the following, where T is the number of factors of 2 in 1116 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1117 // exponentiation: 1118 // 1119 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1120 // 1121 // This formula is trivially equivalent to the previous formula. However, 1122 // this formula can be implemented much more efficiently. The trick is that 1123 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1124 // arithmetic. To do exact division in modular arithmetic, all we have 1125 // to do is multiply by the inverse. Therefore, this step can be done at 1126 // width W. 1127 // 1128 // The next issue is how to safely do the division by 2^T. The way this 1129 // is done is by doing the multiplication step at a width of at least W + T 1130 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1131 // when we perform the division by 2^T (which is equivalent to a right shift 1132 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1133 // truncated out after the division by 2^T. 1134 // 1135 // In comparison to just directly using the first formula, this technique 1136 // is much more efficient; using the first formula requires W * K bits, 1137 // but this formula less than W + K bits. Also, the first formula requires 1138 // a division step, whereas this formula only requires multiplies and shifts. 1139 // 1140 // It doesn't matter whether the subtraction step is done in the calculation 1141 // width or the input iteration count's width; if the subtraction overflows, 1142 // the result must be zero anyway. We prefer here to do it in the width of 1143 // the induction variable because it helps a lot for certain cases; CodeGen 1144 // isn't smart enough to ignore the overflow, which leads to much less 1145 // efficient code if the width of the subtraction is wider than the native 1146 // register width. 1147 // 1148 // (It's possible to not widen at all by pulling out factors of 2 before 1149 // the multiplication; for example, K=2 can be calculated as 1150 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1151 // extra arithmetic, so it's not an obvious win, and it gets 1152 // much more complicated for K > 3.) 1153 1154 // Protection from insane SCEVs; this bound is conservative, 1155 // but it probably doesn't matter. 1156 if (K > 1000) 1157 return SE.getCouldNotCompute(); 1158 1159 unsigned W = SE.getTypeSizeInBits(ResultTy); 1160 1161 // Calculate K! / 2^T and T; we divide out the factors of two before 1162 // multiplying for calculating K! / 2^T to avoid overflow. 1163 // Other overflow doesn't matter because we only care about the bottom 1164 // W bits of the result. 1165 APInt OddFactorial(W, 1); 1166 unsigned T = 1; 1167 for (unsigned i = 3; i <= K; ++i) { 1168 APInt Mult(W, i); 1169 unsigned TwoFactors = Mult.countTrailingZeros(); 1170 T += TwoFactors; 1171 Mult.lshrInPlace(TwoFactors); 1172 OddFactorial *= Mult; 1173 } 1174 1175 // We need at least W + T bits for the multiplication step 1176 unsigned CalculationBits = W + T; 1177 1178 // Calculate 2^T, at width T+W. 1179 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1180 1181 // Calculate the multiplicative inverse of K! / 2^T; 1182 // this multiplication factor will perform the exact division by 1183 // K! / 2^T. 1184 APInt Mod = APInt::getSignedMinValue(W+1); 1185 APInt MultiplyFactor = OddFactorial.zext(W+1); 1186 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1187 MultiplyFactor = MultiplyFactor.trunc(W); 1188 1189 // Calculate the product, at width T+W 1190 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1191 CalculationBits); 1192 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1193 for (unsigned i = 1; i != K; ++i) { 1194 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1195 Dividend = SE.getMulExpr(Dividend, 1196 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1197 } 1198 1199 // Divide by 2^T 1200 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1201 1202 // Truncate the result, and divide by K! / 2^T. 1203 1204 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1205 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1206 } 1207 1208 /// Return the value of this chain of recurrences at the specified iteration 1209 /// number. We can evaluate this recurrence by multiplying each element in the 1210 /// chain by the binomial coefficient corresponding to it. In other words, we 1211 /// can evaluate {A,+,B,+,C,+,D} as: 1212 /// 1213 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1214 /// 1215 /// where BC(It, k) stands for binomial coefficient. 1216 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1217 ScalarEvolution &SE) const { 1218 const SCEV *Result = getStart(); 1219 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1220 // The computation is correct in the face of overflow provided that the 1221 // multiplication is performed _after_ the evaluation of the binomial 1222 // coefficient. 1223 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1224 if (isa<SCEVCouldNotCompute>(Coeff)) 1225 return Coeff; 1226 1227 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1228 } 1229 return Result; 1230 } 1231 1232 //===----------------------------------------------------------------------===// 1233 // SCEV Expression folder implementations 1234 //===----------------------------------------------------------------------===// 1235 1236 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1237 unsigned Depth) { 1238 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1239 "This is not a truncating conversion!"); 1240 assert(isSCEVable(Ty) && 1241 "This is not a conversion to a SCEVable type!"); 1242 Ty = getEffectiveSCEVType(Ty); 1243 1244 FoldingSetNodeID ID; 1245 ID.AddInteger(scTruncate); 1246 ID.AddPointer(Op); 1247 ID.AddPointer(Ty); 1248 void *IP = nullptr; 1249 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1250 1251 // Fold if the operand is constant. 1252 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1253 return getConstant( 1254 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1255 1256 // trunc(trunc(x)) --> trunc(x) 1257 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1258 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1259 1260 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1261 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1262 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1263 1264 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1265 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1266 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1267 1268 if (Depth > MaxCastDepth) { 1269 SCEV *S = 1270 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1271 UniqueSCEVs.InsertNode(S, IP); 1272 addToLoopUseLists(S); 1273 return S; 1274 } 1275 1276 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1277 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1278 // if after transforming we have at most one truncate, not counting truncates 1279 // that replace other casts. 1280 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1281 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1282 SmallVector<const SCEV *, 4> Operands; 1283 unsigned numTruncs = 0; 1284 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1285 ++i) { 1286 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1287 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1288 numTruncs++; 1289 Operands.push_back(S); 1290 } 1291 if (numTruncs < 2) { 1292 if (isa<SCEVAddExpr>(Op)) 1293 return getAddExpr(Operands); 1294 else if (isa<SCEVMulExpr>(Op)) 1295 return getMulExpr(Operands); 1296 else 1297 llvm_unreachable("Unexpected SCEV type for Op."); 1298 } 1299 // Although we checked in the beginning that ID is not in the cache, it is 1300 // possible that during recursion and different modification ID was inserted 1301 // into the cache. So if we find it, just return it. 1302 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1303 return S; 1304 } 1305 1306 // If the input value is a chrec scev, truncate the chrec's operands. 1307 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1308 SmallVector<const SCEV *, 4> Operands; 1309 for (const SCEV *Op : AddRec->operands()) 1310 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1311 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1312 } 1313 1314 // The cast wasn't folded; create an explicit cast node. We can reuse 1315 // the existing insert position since if we get here, we won't have 1316 // made any changes which would invalidate it. 1317 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1318 Op, Ty); 1319 UniqueSCEVs.InsertNode(S, IP); 1320 addToLoopUseLists(S); 1321 return S; 1322 } 1323 1324 // Get the limit of a recurrence such that incrementing by Step cannot cause 1325 // signed overflow as long as the value of the recurrence within the 1326 // loop does not exceed this limit before incrementing. 1327 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1328 ICmpInst::Predicate *Pred, 1329 ScalarEvolution *SE) { 1330 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1331 if (SE->isKnownPositive(Step)) { 1332 *Pred = ICmpInst::ICMP_SLT; 1333 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1334 SE->getSignedRangeMax(Step)); 1335 } 1336 if (SE->isKnownNegative(Step)) { 1337 *Pred = ICmpInst::ICMP_SGT; 1338 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1339 SE->getSignedRangeMin(Step)); 1340 } 1341 return nullptr; 1342 } 1343 1344 // Get the limit of a recurrence such that incrementing by Step cannot cause 1345 // unsigned overflow as long as the value of the recurrence within the loop does 1346 // not exceed this limit before incrementing. 1347 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1348 ICmpInst::Predicate *Pred, 1349 ScalarEvolution *SE) { 1350 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1351 *Pred = ICmpInst::ICMP_ULT; 1352 1353 return SE->getConstant(APInt::getMinValue(BitWidth) - 1354 SE->getUnsignedRangeMax(Step)); 1355 } 1356 1357 namespace { 1358 1359 struct ExtendOpTraitsBase { 1360 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1361 unsigned); 1362 }; 1363 1364 // Used to make code generic over signed and unsigned overflow. 1365 template <typename ExtendOp> struct ExtendOpTraits { 1366 // Members present: 1367 // 1368 // static const SCEV::NoWrapFlags WrapType; 1369 // 1370 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1371 // 1372 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1373 // ICmpInst::Predicate *Pred, 1374 // ScalarEvolution *SE); 1375 }; 1376 1377 template <> 1378 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1379 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1380 1381 static const GetExtendExprTy GetExtendExpr; 1382 1383 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1384 ICmpInst::Predicate *Pred, 1385 ScalarEvolution *SE) { 1386 return getSignedOverflowLimitForStep(Step, Pred, SE); 1387 } 1388 }; 1389 1390 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1391 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1392 1393 template <> 1394 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1395 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1396 1397 static const GetExtendExprTy GetExtendExpr; 1398 1399 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1400 ICmpInst::Predicate *Pred, 1401 ScalarEvolution *SE) { 1402 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1403 } 1404 }; 1405 1406 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1407 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1408 1409 } // end anonymous namespace 1410 1411 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1412 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1413 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1414 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1415 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1416 // expression "Step + sext/zext(PreIncAR)" is congruent with 1417 // "sext/zext(PostIncAR)" 1418 template <typename ExtendOpTy> 1419 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1420 ScalarEvolution *SE, unsigned Depth) { 1421 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1422 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1423 1424 const Loop *L = AR->getLoop(); 1425 const SCEV *Start = AR->getStart(); 1426 const SCEV *Step = AR->getStepRecurrence(*SE); 1427 1428 // Check for a simple looking step prior to loop entry. 1429 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1430 if (!SA) 1431 return nullptr; 1432 1433 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1434 // subtraction is expensive. For this purpose, perform a quick and dirty 1435 // difference, by checking for Step in the operand list. 1436 SmallVector<const SCEV *, 4> DiffOps; 1437 for (const SCEV *Op : SA->operands()) 1438 if (Op != Step) 1439 DiffOps.push_back(Op); 1440 1441 if (DiffOps.size() == SA->getNumOperands()) 1442 return nullptr; 1443 1444 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1445 // `Step`: 1446 1447 // 1. NSW/NUW flags on the step increment. 1448 auto PreStartFlags = 1449 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1450 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1451 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1452 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1453 1454 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1455 // "S+X does not sign/unsign-overflow". 1456 // 1457 1458 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1459 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1460 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1461 return PreStart; 1462 1463 // 2. Direct overflow check on the step operation's expression. 1464 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1465 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1466 const SCEV *OperandExtendedStart = 1467 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1468 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1469 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1470 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1471 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1472 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1473 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1474 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1475 } 1476 return PreStart; 1477 } 1478 1479 // 3. Loop precondition. 1480 ICmpInst::Predicate Pred; 1481 const SCEV *OverflowLimit = 1482 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1483 1484 if (OverflowLimit && 1485 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1486 return PreStart; 1487 1488 return nullptr; 1489 } 1490 1491 // Get the normalized zero or sign extended expression for this AddRec's Start. 1492 template <typename ExtendOpTy> 1493 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1494 ScalarEvolution *SE, 1495 unsigned Depth) { 1496 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1497 1498 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1499 if (!PreStart) 1500 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1501 1502 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1503 Depth), 1504 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1505 } 1506 1507 // Try to prove away overflow by looking at "nearby" add recurrences. A 1508 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1509 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1510 // 1511 // Formally: 1512 // 1513 // {S,+,X} == {S-T,+,X} + T 1514 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1515 // 1516 // If ({S-T,+,X} + T) does not overflow ... (1) 1517 // 1518 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1519 // 1520 // If {S-T,+,X} does not overflow ... (2) 1521 // 1522 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1523 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1524 // 1525 // If (S-T)+T does not overflow ... (3) 1526 // 1527 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1528 // == {Ext(S),+,Ext(X)} == LHS 1529 // 1530 // Thus, if (1), (2) and (3) are true for some T, then 1531 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1532 // 1533 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1534 // does not overflow" restricted to the 0th iteration. Therefore we only need 1535 // to check for (1) and (2). 1536 // 1537 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1538 // is `Delta` (defined below). 1539 template <typename ExtendOpTy> 1540 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1541 const SCEV *Step, 1542 const Loop *L) { 1543 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1544 1545 // We restrict `Start` to a constant to prevent SCEV from spending too much 1546 // time here. It is correct (but more expensive) to continue with a 1547 // non-constant `Start` and do a general SCEV subtraction to compute 1548 // `PreStart` below. 1549 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1550 if (!StartC) 1551 return false; 1552 1553 APInt StartAI = StartC->getAPInt(); 1554 1555 for (unsigned Delta : {-2, -1, 1, 2}) { 1556 const SCEV *PreStart = getConstant(StartAI - Delta); 1557 1558 FoldingSetNodeID ID; 1559 ID.AddInteger(scAddRecExpr); 1560 ID.AddPointer(PreStart); 1561 ID.AddPointer(Step); 1562 ID.AddPointer(L); 1563 void *IP = nullptr; 1564 const auto *PreAR = 1565 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1566 1567 // Give up if we don't already have the add recurrence we need because 1568 // actually constructing an add recurrence is relatively expensive. 1569 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1570 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1571 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1572 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1573 DeltaS, &Pred, this); 1574 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1575 return true; 1576 } 1577 } 1578 1579 return false; 1580 } 1581 1582 // Finds an integer D for an expression (C + x + y + ...) such that the top 1583 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1584 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1585 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1586 // the (C + x + y + ...) expression is \p WholeAddExpr. 1587 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1588 const SCEVConstant *ConstantTerm, 1589 const SCEVAddExpr *WholeAddExpr) { 1590 const APInt C = ConstantTerm->getAPInt(); 1591 const unsigned BitWidth = C.getBitWidth(); 1592 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1593 uint32_t TZ = BitWidth; 1594 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1595 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1596 if (TZ) { 1597 // Set D to be as many least significant bits of C as possible while still 1598 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1599 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1600 } 1601 return APInt(BitWidth, 0); 1602 } 1603 1604 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1605 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1606 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1607 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1608 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1609 const APInt &ConstantStart, 1610 const SCEV *Step) { 1611 const unsigned BitWidth = ConstantStart.getBitWidth(); 1612 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1613 if (TZ) 1614 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1615 : ConstantStart; 1616 return APInt(BitWidth, 0); 1617 } 1618 1619 const SCEV * 1620 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1621 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1622 "This is not an extending conversion!"); 1623 assert(isSCEVable(Ty) && 1624 "This is not a conversion to a SCEVable type!"); 1625 Ty = getEffectiveSCEVType(Ty); 1626 1627 // Fold if the operand is constant. 1628 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1629 return getConstant( 1630 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1631 1632 // zext(zext(x)) --> zext(x) 1633 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1634 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1635 1636 // Before doing any expensive analysis, check to see if we've already 1637 // computed a SCEV for this Op and Ty. 1638 FoldingSetNodeID ID; 1639 ID.AddInteger(scZeroExtend); 1640 ID.AddPointer(Op); 1641 ID.AddPointer(Ty); 1642 void *IP = nullptr; 1643 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1644 if (Depth > MaxCastDepth) { 1645 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1646 Op, Ty); 1647 UniqueSCEVs.InsertNode(S, IP); 1648 addToLoopUseLists(S); 1649 return S; 1650 } 1651 1652 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1653 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1654 // It's possible the bits taken off by the truncate were all zero bits. If 1655 // so, we should be able to simplify this further. 1656 const SCEV *X = ST->getOperand(); 1657 ConstantRange CR = getUnsignedRange(X); 1658 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1659 unsigned NewBits = getTypeSizeInBits(Ty); 1660 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1661 CR.zextOrTrunc(NewBits))) 1662 return getTruncateOrZeroExtend(X, Ty, Depth); 1663 } 1664 1665 // If the input value is a chrec scev, and we can prove that the value 1666 // did not overflow the old, smaller, value, we can zero extend all of the 1667 // operands (often constants). This allows analysis of something like 1668 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1669 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1670 if (AR->isAffine()) { 1671 const SCEV *Start = AR->getStart(); 1672 const SCEV *Step = AR->getStepRecurrence(*this); 1673 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1674 const Loop *L = AR->getLoop(); 1675 1676 if (!AR->hasNoUnsignedWrap()) { 1677 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1678 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1679 } 1680 1681 // If we have special knowledge that this addrec won't overflow, 1682 // we don't need to do any further analysis. 1683 if (AR->hasNoUnsignedWrap()) 1684 return getAddRecExpr( 1685 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1686 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1687 1688 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1689 // Note that this serves two purposes: It filters out loops that are 1690 // simply not analyzable, and it covers the case where this code is 1691 // being called from within backedge-taken count analysis, such that 1692 // attempting to ask for the backedge-taken count would likely result 1693 // in infinite recursion. In the later case, the analysis code will 1694 // cope with a conservative value, and it will take care to purge 1695 // that value once it has finished. 1696 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1697 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1698 // Manually compute the final value for AR, checking for 1699 // overflow. 1700 1701 // Check whether the backedge-taken count can be losslessly casted to 1702 // the addrec's type. The count is always unsigned. 1703 const SCEV *CastedMaxBECount = 1704 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1705 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1706 CastedMaxBECount, MaxBECount->getType(), Depth); 1707 if (MaxBECount == RecastedMaxBECount) { 1708 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1709 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1710 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1711 SCEV::FlagAnyWrap, Depth + 1); 1712 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1713 SCEV::FlagAnyWrap, 1714 Depth + 1), 1715 WideTy, Depth + 1); 1716 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1717 const SCEV *WideMaxBECount = 1718 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1719 const SCEV *OperandExtendedAdd = 1720 getAddExpr(WideStart, 1721 getMulExpr(WideMaxBECount, 1722 getZeroExtendExpr(Step, WideTy, Depth + 1), 1723 SCEV::FlagAnyWrap, Depth + 1), 1724 SCEV::FlagAnyWrap, Depth + 1); 1725 if (ZAdd == OperandExtendedAdd) { 1726 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1727 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1728 // Return the expression with the addrec on the outside. 1729 return getAddRecExpr( 1730 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1731 Depth + 1), 1732 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1733 AR->getNoWrapFlags()); 1734 } 1735 // Similar to above, only this time treat the step value as signed. 1736 // This covers loops that count down. 1737 OperandExtendedAdd = 1738 getAddExpr(WideStart, 1739 getMulExpr(WideMaxBECount, 1740 getSignExtendExpr(Step, WideTy, Depth + 1), 1741 SCEV::FlagAnyWrap, Depth + 1), 1742 SCEV::FlagAnyWrap, Depth + 1); 1743 if (ZAdd == OperandExtendedAdd) { 1744 // Cache knowledge of AR NW, which is propagated to this AddRec. 1745 // Negative step causes unsigned wrap, but it still can't self-wrap. 1746 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1747 // Return the expression with the addrec on the outside. 1748 return getAddRecExpr( 1749 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1750 Depth + 1), 1751 getSignExtendExpr(Step, Ty, Depth + 1), L, 1752 AR->getNoWrapFlags()); 1753 } 1754 } 1755 } 1756 1757 // Normally, in the cases we can prove no-overflow via a 1758 // backedge guarding condition, we can also compute a backedge 1759 // taken count for the loop. The exceptions are assumptions and 1760 // guards present in the loop -- SCEV is not great at exploiting 1761 // these to compute max backedge taken counts, but can still use 1762 // these to prove lack of overflow. Use this fact to avoid 1763 // doing extra work that may not pay off. 1764 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1765 !AC.assumptions().empty()) { 1766 // If the backedge is guarded by a comparison with the pre-inc 1767 // value the addrec is safe. Also, if the entry is guarded by 1768 // a comparison with the start value and the backedge is 1769 // guarded by a comparison with the post-inc value, the addrec 1770 // is safe. 1771 if (isKnownPositive(Step)) { 1772 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1773 getUnsignedRangeMax(Step)); 1774 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1775 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1776 // Cache knowledge of AR NUW, which is propagated to this 1777 // AddRec. 1778 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1779 // Return the expression with the addrec on the outside. 1780 return getAddRecExpr( 1781 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1782 Depth + 1), 1783 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1784 AR->getNoWrapFlags()); 1785 } 1786 } else if (isKnownNegative(Step)) { 1787 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1788 getSignedRangeMin(Step)); 1789 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1790 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1791 // Cache knowledge of AR NW, which is propagated to this 1792 // AddRec. Negative step causes unsigned wrap, but it 1793 // still can't self-wrap. 1794 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1795 // Return the expression with the addrec on the outside. 1796 return getAddRecExpr( 1797 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1798 Depth + 1), 1799 getSignExtendExpr(Step, Ty, Depth + 1), L, 1800 AR->getNoWrapFlags()); 1801 } 1802 } 1803 } 1804 1805 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1806 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1807 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1808 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1809 const APInt &C = SC->getAPInt(); 1810 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1811 if (D != 0) { 1812 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1813 const SCEV *SResidual = 1814 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1815 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1816 return getAddExpr(SZExtD, SZExtR, 1817 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1818 Depth + 1); 1819 } 1820 } 1821 1822 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1823 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1824 return getAddRecExpr( 1825 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1826 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1827 } 1828 } 1829 1830 // zext(A % B) --> zext(A) % zext(B) 1831 { 1832 const SCEV *LHS; 1833 const SCEV *RHS; 1834 if (matchURem(Op, LHS, RHS)) 1835 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1836 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1837 } 1838 1839 // zext(A / B) --> zext(A) / zext(B). 1840 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1841 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1842 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1843 1844 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1845 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1846 if (SA->hasNoUnsignedWrap()) { 1847 // If the addition does not unsign overflow then we can, by definition, 1848 // commute the zero extension with the addition operation. 1849 SmallVector<const SCEV *, 4> Ops; 1850 for (const auto *Op : SA->operands()) 1851 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1852 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1853 } 1854 1855 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1856 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1857 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1858 // 1859 // Often address arithmetics contain expressions like 1860 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1861 // This transformation is useful while proving that such expressions are 1862 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1863 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1864 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1865 if (D != 0) { 1866 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1867 const SCEV *SResidual = 1868 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1869 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1870 return getAddExpr(SZExtD, SZExtR, 1871 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1872 Depth + 1); 1873 } 1874 } 1875 } 1876 1877 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1878 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1879 if (SM->hasNoUnsignedWrap()) { 1880 // If the multiply does not unsign overflow then we can, by definition, 1881 // commute the zero extension with the multiply operation. 1882 SmallVector<const SCEV *, 4> Ops; 1883 for (const auto *Op : SM->operands()) 1884 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1885 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1886 } 1887 1888 // zext(2^K * (trunc X to iN)) to iM -> 1889 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1890 // 1891 // Proof: 1892 // 1893 // zext(2^K * (trunc X to iN)) to iM 1894 // = zext((trunc X to iN) << K) to iM 1895 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1896 // (because shl removes the top K bits) 1897 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1898 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1899 // 1900 if (SM->getNumOperands() == 2) 1901 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1902 if (MulLHS->getAPInt().isPowerOf2()) 1903 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1904 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1905 MulLHS->getAPInt().logBase2(); 1906 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1907 return getMulExpr( 1908 getZeroExtendExpr(MulLHS, Ty), 1909 getZeroExtendExpr( 1910 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1911 SCEV::FlagNUW, Depth + 1); 1912 } 1913 } 1914 1915 // The cast wasn't folded; create an explicit cast node. 1916 // Recompute the insert position, as it may have been invalidated. 1917 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1918 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1919 Op, Ty); 1920 UniqueSCEVs.InsertNode(S, IP); 1921 addToLoopUseLists(S); 1922 return S; 1923 } 1924 1925 const SCEV * 1926 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1927 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1928 "This is not an extending conversion!"); 1929 assert(isSCEVable(Ty) && 1930 "This is not a conversion to a SCEVable type!"); 1931 Ty = getEffectiveSCEVType(Ty); 1932 1933 // Fold if the operand is constant. 1934 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1935 return getConstant( 1936 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1937 1938 // sext(sext(x)) --> sext(x) 1939 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1940 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1941 1942 // sext(zext(x)) --> zext(x) 1943 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1944 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1945 1946 // Before doing any expensive analysis, check to see if we've already 1947 // computed a SCEV for this Op and Ty. 1948 FoldingSetNodeID ID; 1949 ID.AddInteger(scSignExtend); 1950 ID.AddPointer(Op); 1951 ID.AddPointer(Ty); 1952 void *IP = nullptr; 1953 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1954 // Limit recursion depth. 1955 if (Depth > MaxCastDepth) { 1956 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1957 Op, Ty); 1958 UniqueSCEVs.InsertNode(S, IP); 1959 addToLoopUseLists(S); 1960 return S; 1961 } 1962 1963 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1964 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1965 // It's possible the bits taken off by the truncate were all sign bits. If 1966 // so, we should be able to simplify this further. 1967 const SCEV *X = ST->getOperand(); 1968 ConstantRange CR = getSignedRange(X); 1969 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1970 unsigned NewBits = getTypeSizeInBits(Ty); 1971 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1972 CR.sextOrTrunc(NewBits))) 1973 return getTruncateOrSignExtend(X, Ty, Depth); 1974 } 1975 1976 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1977 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1978 if (SA->hasNoSignedWrap()) { 1979 // If the addition does not sign overflow then we can, by definition, 1980 // commute the sign extension with the addition operation. 1981 SmallVector<const SCEV *, 4> Ops; 1982 for (const auto *Op : SA->operands()) 1983 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1984 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1985 } 1986 1987 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1988 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1989 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1990 // 1991 // For instance, this will bring two seemingly different expressions: 1992 // 1 + sext(5 + 20 * %x + 24 * %y) and 1993 // sext(6 + 20 * %x + 24 * %y) 1994 // to the same form: 1995 // 2 + sext(4 + 20 * %x + 24 * %y) 1996 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1997 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1998 if (D != 0) { 1999 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2000 const SCEV *SResidual = 2001 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 2002 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2003 return getAddExpr(SSExtD, SSExtR, 2004 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2005 Depth + 1); 2006 } 2007 } 2008 } 2009 // If the input value is a chrec scev, and we can prove that the value 2010 // did not overflow the old, smaller, value, we can sign extend all of the 2011 // operands (often constants). This allows analysis of something like 2012 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 2013 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 2014 if (AR->isAffine()) { 2015 const SCEV *Start = AR->getStart(); 2016 const SCEV *Step = AR->getStepRecurrence(*this); 2017 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 2018 const Loop *L = AR->getLoop(); 2019 2020 if (!AR->hasNoSignedWrap()) { 2021 auto NewFlags = proveNoWrapViaConstantRanges(AR); 2022 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 2023 } 2024 2025 // If we have special knowledge that this addrec won't overflow, 2026 // we don't need to do any further analysis. 2027 if (AR->hasNoSignedWrap()) 2028 return getAddRecExpr( 2029 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2030 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 2031 2032 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2033 // Note that this serves two purposes: It filters out loops that are 2034 // simply not analyzable, and it covers the case where this code is 2035 // being called from within backedge-taken count analysis, such that 2036 // attempting to ask for the backedge-taken count would likely result 2037 // in infinite recursion. In the later case, the analysis code will 2038 // cope with a conservative value, and it will take care to purge 2039 // that value once it has finished. 2040 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 2041 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2042 // Manually compute the final value for AR, checking for 2043 // overflow. 2044 2045 // Check whether the backedge-taken count can be losslessly casted to 2046 // the addrec's type. The count is always unsigned. 2047 const SCEV *CastedMaxBECount = 2048 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2049 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2050 CastedMaxBECount, MaxBECount->getType(), Depth); 2051 if (MaxBECount == RecastedMaxBECount) { 2052 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2053 // Check whether Start+Step*MaxBECount has no signed overflow. 2054 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2055 SCEV::FlagAnyWrap, Depth + 1); 2056 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2057 SCEV::FlagAnyWrap, 2058 Depth + 1), 2059 WideTy, Depth + 1); 2060 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2061 const SCEV *WideMaxBECount = 2062 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2063 const SCEV *OperandExtendedAdd = 2064 getAddExpr(WideStart, 2065 getMulExpr(WideMaxBECount, 2066 getSignExtendExpr(Step, WideTy, Depth + 1), 2067 SCEV::FlagAnyWrap, Depth + 1), 2068 SCEV::FlagAnyWrap, Depth + 1); 2069 if (SAdd == OperandExtendedAdd) { 2070 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2071 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2072 // Return the expression with the addrec on the outside. 2073 return getAddRecExpr( 2074 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2075 Depth + 1), 2076 getSignExtendExpr(Step, Ty, Depth + 1), L, 2077 AR->getNoWrapFlags()); 2078 } 2079 // Similar to above, only this time treat the step value as unsigned. 2080 // This covers loops that count up with an unsigned step. 2081 OperandExtendedAdd = 2082 getAddExpr(WideStart, 2083 getMulExpr(WideMaxBECount, 2084 getZeroExtendExpr(Step, WideTy, Depth + 1), 2085 SCEV::FlagAnyWrap, Depth + 1), 2086 SCEV::FlagAnyWrap, Depth + 1); 2087 if (SAdd == OperandExtendedAdd) { 2088 // If AR wraps around then 2089 // 2090 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2091 // => SAdd != OperandExtendedAdd 2092 // 2093 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2094 // (SAdd == OperandExtendedAdd => AR is NW) 2095 2096 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2097 2098 // Return the expression with the addrec on the outside. 2099 return getAddRecExpr( 2100 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2101 Depth + 1), 2102 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2103 AR->getNoWrapFlags()); 2104 } 2105 } 2106 } 2107 2108 // Normally, in the cases we can prove no-overflow via a 2109 // backedge guarding condition, we can also compute a backedge 2110 // taken count for the loop. The exceptions are assumptions and 2111 // guards present in the loop -- SCEV is not great at exploiting 2112 // these to compute max backedge taken counts, but can still use 2113 // these to prove lack of overflow. Use this fact to avoid 2114 // doing extra work that may not pay off. 2115 2116 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2117 !AC.assumptions().empty()) { 2118 // If the backedge is guarded by a comparison with the pre-inc 2119 // value the addrec is safe. Also, if the entry is guarded by 2120 // a comparison with the start value and the backedge is 2121 // guarded by a comparison with the post-inc value, the addrec 2122 // is safe. 2123 ICmpInst::Predicate Pred; 2124 const SCEV *OverflowLimit = 2125 getSignedOverflowLimitForStep(Step, &Pred, this); 2126 if (OverflowLimit && 2127 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2128 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2129 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2130 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2131 return getAddRecExpr( 2132 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2133 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2134 } 2135 } 2136 2137 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2138 // if D + (C - D + Step * n) could be proven to not signed wrap 2139 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2140 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2141 const APInt &C = SC->getAPInt(); 2142 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2143 if (D != 0) { 2144 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2145 const SCEV *SResidual = 2146 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2147 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2148 return getAddExpr(SSExtD, SSExtR, 2149 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2150 Depth + 1); 2151 } 2152 } 2153 2154 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2155 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2156 return getAddRecExpr( 2157 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2158 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2159 } 2160 } 2161 2162 // If the input value is provably positive and we could not simplify 2163 // away the sext build a zext instead. 2164 if (isKnownNonNegative(Op)) 2165 return getZeroExtendExpr(Op, Ty, Depth + 1); 2166 2167 // The cast wasn't folded; create an explicit cast node. 2168 // Recompute the insert position, as it may have been invalidated. 2169 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2170 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2171 Op, Ty); 2172 UniqueSCEVs.InsertNode(S, IP); 2173 addToLoopUseLists(S); 2174 return S; 2175 } 2176 2177 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2178 /// unspecified bits out to the given type. 2179 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2180 Type *Ty) { 2181 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2182 "This is not an extending conversion!"); 2183 assert(isSCEVable(Ty) && 2184 "This is not a conversion to a SCEVable type!"); 2185 Ty = getEffectiveSCEVType(Ty); 2186 2187 // Sign-extend negative constants. 2188 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2189 if (SC->getAPInt().isNegative()) 2190 return getSignExtendExpr(Op, Ty); 2191 2192 // Peel off a truncate cast. 2193 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2194 const SCEV *NewOp = T->getOperand(); 2195 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2196 return getAnyExtendExpr(NewOp, Ty); 2197 return getTruncateOrNoop(NewOp, Ty); 2198 } 2199 2200 // Next try a zext cast. If the cast is folded, use it. 2201 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2202 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2203 return ZExt; 2204 2205 // Next try a sext cast. If the cast is folded, use it. 2206 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2207 if (!isa<SCEVSignExtendExpr>(SExt)) 2208 return SExt; 2209 2210 // Force the cast to be folded into the operands of an addrec. 2211 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2212 SmallVector<const SCEV *, 4> Ops; 2213 for (const SCEV *Op : AR->operands()) 2214 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2215 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2216 } 2217 2218 // If the expression is obviously signed, use the sext cast value. 2219 if (isa<SCEVSMaxExpr>(Op)) 2220 return SExt; 2221 2222 // Absent any other information, use the zext cast value. 2223 return ZExt; 2224 } 2225 2226 /// Process the given Ops list, which is a list of operands to be added under 2227 /// the given scale, update the given map. This is a helper function for 2228 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2229 /// that would form an add expression like this: 2230 /// 2231 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2232 /// 2233 /// where A and B are constants, update the map with these values: 2234 /// 2235 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2236 /// 2237 /// and add 13 + A*B*29 to AccumulatedConstant. 2238 /// This will allow getAddRecExpr to produce this: 2239 /// 2240 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2241 /// 2242 /// This form often exposes folding opportunities that are hidden in 2243 /// the original operand list. 2244 /// 2245 /// Return true iff it appears that any interesting folding opportunities 2246 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2247 /// the common case where no interesting opportunities are present, and 2248 /// is also used as a check to avoid infinite recursion. 2249 static bool 2250 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2251 SmallVectorImpl<const SCEV *> &NewOps, 2252 APInt &AccumulatedConstant, 2253 const SCEV *const *Ops, size_t NumOperands, 2254 const APInt &Scale, 2255 ScalarEvolution &SE) { 2256 bool Interesting = false; 2257 2258 // Iterate over the add operands. They are sorted, with constants first. 2259 unsigned i = 0; 2260 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2261 ++i; 2262 // Pull a buried constant out to the outside. 2263 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2264 Interesting = true; 2265 AccumulatedConstant += Scale * C->getAPInt(); 2266 } 2267 2268 // Next comes everything else. We're especially interested in multiplies 2269 // here, but they're in the middle, so just visit the rest with one loop. 2270 for (; i != NumOperands; ++i) { 2271 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2272 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2273 APInt NewScale = 2274 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2275 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2276 // A multiplication of a constant with another add; recurse. 2277 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2278 Interesting |= 2279 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2280 Add->op_begin(), Add->getNumOperands(), 2281 NewScale, SE); 2282 } else { 2283 // A multiplication of a constant with some other value. Update 2284 // the map. 2285 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2286 const SCEV *Key = SE.getMulExpr(MulOps); 2287 auto Pair = M.insert({Key, NewScale}); 2288 if (Pair.second) { 2289 NewOps.push_back(Pair.first->first); 2290 } else { 2291 Pair.first->second += NewScale; 2292 // The map already had an entry for this value, which may indicate 2293 // a folding opportunity. 2294 Interesting = true; 2295 } 2296 } 2297 } else { 2298 // An ordinary operand. Update the map. 2299 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2300 M.insert({Ops[i], Scale}); 2301 if (Pair.second) { 2302 NewOps.push_back(Pair.first->first); 2303 } else { 2304 Pair.first->second += Scale; 2305 // The map already had an entry for this value, which may indicate 2306 // a folding opportunity. 2307 Interesting = true; 2308 } 2309 } 2310 } 2311 2312 return Interesting; 2313 } 2314 2315 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2316 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2317 // can't-overflow flags for the operation if possible. 2318 static SCEV::NoWrapFlags 2319 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2320 const ArrayRef<const SCEV *> Ops, 2321 SCEV::NoWrapFlags Flags) { 2322 using namespace std::placeholders; 2323 2324 using OBO = OverflowingBinaryOperator; 2325 2326 bool CanAnalyze = 2327 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2328 (void)CanAnalyze; 2329 assert(CanAnalyze && "don't call from other places!"); 2330 2331 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2332 SCEV::NoWrapFlags SignOrUnsignWrap = 2333 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2334 2335 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2336 auto IsKnownNonNegative = [&](const SCEV *S) { 2337 return SE->isKnownNonNegative(S); 2338 }; 2339 2340 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2341 Flags = 2342 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2343 2344 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2345 2346 if (SignOrUnsignWrap != SignOrUnsignMask && 2347 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2348 isa<SCEVConstant>(Ops[0])) { 2349 2350 auto Opcode = [&] { 2351 switch (Type) { 2352 case scAddExpr: 2353 return Instruction::Add; 2354 case scMulExpr: 2355 return Instruction::Mul; 2356 default: 2357 llvm_unreachable("Unexpected SCEV op."); 2358 } 2359 }(); 2360 2361 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2362 2363 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2364 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2365 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2366 Opcode, C, OBO::NoSignedWrap); 2367 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2368 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2369 } 2370 2371 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2372 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2373 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2374 Opcode, C, OBO::NoUnsignedWrap); 2375 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2376 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2377 } 2378 } 2379 2380 return Flags; 2381 } 2382 2383 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2384 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2385 } 2386 2387 /// Get a canonical add expression, or something simpler if possible. 2388 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2389 SCEV::NoWrapFlags Flags, 2390 unsigned Depth) { 2391 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2392 "only nuw or nsw allowed"); 2393 assert(!Ops.empty() && "Cannot get empty add!"); 2394 if (Ops.size() == 1) return Ops[0]; 2395 #ifndef NDEBUG 2396 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2397 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2398 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2399 "SCEVAddExpr operand types don't match!"); 2400 #endif 2401 2402 // Sort by complexity, this groups all similar expression types together. 2403 GroupByComplexity(Ops, &LI, DT); 2404 2405 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2406 2407 // If there are any constants, fold them together. 2408 unsigned Idx = 0; 2409 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2410 ++Idx; 2411 assert(Idx < Ops.size()); 2412 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2413 // We found two constants, fold them together! 2414 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2415 if (Ops.size() == 2) return Ops[0]; 2416 Ops.erase(Ops.begin()+1); // Erase the folded element 2417 LHSC = cast<SCEVConstant>(Ops[0]); 2418 } 2419 2420 // If we are left with a constant zero being added, strip it off. 2421 if (LHSC->getValue()->isZero()) { 2422 Ops.erase(Ops.begin()); 2423 --Idx; 2424 } 2425 2426 if (Ops.size() == 1) return Ops[0]; 2427 } 2428 2429 // Limit recursion calls depth. 2430 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2431 return getOrCreateAddExpr(Ops, Flags); 2432 2433 // Okay, check to see if the same value occurs in the operand list more than 2434 // once. If so, merge them together into an multiply expression. Since we 2435 // sorted the list, these values are required to be adjacent. 2436 Type *Ty = Ops[0]->getType(); 2437 bool FoundMatch = false; 2438 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2439 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2440 // Scan ahead to count how many equal operands there are. 2441 unsigned Count = 2; 2442 while (i+Count != e && Ops[i+Count] == Ops[i]) 2443 ++Count; 2444 // Merge the values into a multiply. 2445 const SCEV *Scale = getConstant(Ty, Count); 2446 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2447 if (Ops.size() == Count) 2448 return Mul; 2449 Ops[i] = Mul; 2450 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2451 --i; e -= Count - 1; 2452 FoundMatch = true; 2453 } 2454 if (FoundMatch) 2455 return getAddExpr(Ops, Flags, Depth + 1); 2456 2457 // Check for truncates. If all the operands are truncated from the same 2458 // type, see if factoring out the truncate would permit the result to be 2459 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2460 // if the contents of the resulting outer trunc fold to something simple. 2461 auto FindTruncSrcType = [&]() -> Type * { 2462 // We're ultimately looking to fold an addrec of truncs and muls of only 2463 // constants and truncs, so if we find any other types of SCEV 2464 // as operands of the addrec then we bail and return nullptr here. 2465 // Otherwise, we return the type of the operand of a trunc that we find. 2466 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2467 return T->getOperand()->getType(); 2468 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2469 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2470 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2471 return T->getOperand()->getType(); 2472 } 2473 return nullptr; 2474 }; 2475 if (auto *SrcType = FindTruncSrcType()) { 2476 SmallVector<const SCEV *, 8> LargeOps; 2477 bool Ok = true; 2478 // Check all the operands to see if they can be represented in the 2479 // source type of the truncate. 2480 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2481 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2482 if (T->getOperand()->getType() != SrcType) { 2483 Ok = false; 2484 break; 2485 } 2486 LargeOps.push_back(T->getOperand()); 2487 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2488 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2489 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2490 SmallVector<const SCEV *, 8> LargeMulOps; 2491 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2492 if (const SCEVTruncateExpr *T = 2493 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2494 if (T->getOperand()->getType() != SrcType) { 2495 Ok = false; 2496 break; 2497 } 2498 LargeMulOps.push_back(T->getOperand()); 2499 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2500 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2501 } else { 2502 Ok = false; 2503 break; 2504 } 2505 } 2506 if (Ok) 2507 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2508 } else { 2509 Ok = false; 2510 break; 2511 } 2512 } 2513 if (Ok) { 2514 // Evaluate the expression in the larger type. 2515 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2516 // If it folds to something simple, use it. Otherwise, don't. 2517 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2518 return getTruncateExpr(Fold, Ty); 2519 } 2520 } 2521 2522 // Skip past any other cast SCEVs. 2523 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2524 ++Idx; 2525 2526 // If there are add operands they would be next. 2527 if (Idx < Ops.size()) { 2528 bool DeletedAdd = false; 2529 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2530 if (Ops.size() > AddOpsInlineThreshold || 2531 Add->getNumOperands() > AddOpsInlineThreshold) 2532 break; 2533 // If we have an add, expand the add operands onto the end of the operands 2534 // list. 2535 Ops.erase(Ops.begin()+Idx); 2536 Ops.append(Add->op_begin(), Add->op_end()); 2537 DeletedAdd = true; 2538 } 2539 2540 // If we deleted at least one add, we added operands to the end of the list, 2541 // and they are not necessarily sorted. Recurse to resort and resimplify 2542 // any operands we just acquired. 2543 if (DeletedAdd) 2544 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2545 } 2546 2547 // Skip over the add expression until we get to a multiply. 2548 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2549 ++Idx; 2550 2551 // Check to see if there are any folding opportunities present with 2552 // operands multiplied by constant values. 2553 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2554 uint64_t BitWidth = getTypeSizeInBits(Ty); 2555 DenseMap<const SCEV *, APInt> M; 2556 SmallVector<const SCEV *, 8> NewOps; 2557 APInt AccumulatedConstant(BitWidth, 0); 2558 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2559 Ops.data(), Ops.size(), 2560 APInt(BitWidth, 1), *this)) { 2561 struct APIntCompare { 2562 bool operator()(const APInt &LHS, const APInt &RHS) const { 2563 return LHS.ult(RHS); 2564 } 2565 }; 2566 2567 // Some interesting folding opportunity is present, so its worthwhile to 2568 // re-generate the operands list. Group the operands by constant scale, 2569 // to avoid multiplying by the same constant scale multiple times. 2570 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2571 for (const SCEV *NewOp : NewOps) 2572 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2573 // Re-generate the operands list. 2574 Ops.clear(); 2575 if (AccumulatedConstant != 0) 2576 Ops.push_back(getConstant(AccumulatedConstant)); 2577 for (auto &MulOp : MulOpLists) 2578 if (MulOp.first != 0) 2579 Ops.push_back(getMulExpr( 2580 getConstant(MulOp.first), 2581 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2582 SCEV::FlagAnyWrap, Depth + 1)); 2583 if (Ops.empty()) 2584 return getZero(Ty); 2585 if (Ops.size() == 1) 2586 return Ops[0]; 2587 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2588 } 2589 } 2590 2591 // If we are adding something to a multiply expression, make sure the 2592 // something is not already an operand of the multiply. If so, merge it into 2593 // the multiply. 2594 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2595 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2596 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2597 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2598 if (isa<SCEVConstant>(MulOpSCEV)) 2599 continue; 2600 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2601 if (MulOpSCEV == Ops[AddOp]) { 2602 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2603 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2604 if (Mul->getNumOperands() != 2) { 2605 // If the multiply has more than two operands, we must get the 2606 // Y*Z term. 2607 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2608 Mul->op_begin()+MulOp); 2609 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2610 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2611 } 2612 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2613 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2614 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2615 SCEV::FlagAnyWrap, Depth + 1); 2616 if (Ops.size() == 2) return OuterMul; 2617 if (AddOp < Idx) { 2618 Ops.erase(Ops.begin()+AddOp); 2619 Ops.erase(Ops.begin()+Idx-1); 2620 } else { 2621 Ops.erase(Ops.begin()+Idx); 2622 Ops.erase(Ops.begin()+AddOp-1); 2623 } 2624 Ops.push_back(OuterMul); 2625 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2626 } 2627 2628 // Check this multiply against other multiplies being added together. 2629 for (unsigned OtherMulIdx = Idx+1; 2630 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2631 ++OtherMulIdx) { 2632 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2633 // If MulOp occurs in OtherMul, we can fold the two multiplies 2634 // together. 2635 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2636 OMulOp != e; ++OMulOp) 2637 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2638 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2639 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2640 if (Mul->getNumOperands() != 2) { 2641 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2642 Mul->op_begin()+MulOp); 2643 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2644 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2645 } 2646 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2647 if (OtherMul->getNumOperands() != 2) { 2648 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2649 OtherMul->op_begin()+OMulOp); 2650 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2651 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2652 } 2653 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2654 const SCEV *InnerMulSum = 2655 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2656 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2657 SCEV::FlagAnyWrap, Depth + 1); 2658 if (Ops.size() == 2) return OuterMul; 2659 Ops.erase(Ops.begin()+Idx); 2660 Ops.erase(Ops.begin()+OtherMulIdx-1); 2661 Ops.push_back(OuterMul); 2662 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2663 } 2664 } 2665 } 2666 } 2667 2668 // If there are any add recurrences in the operands list, see if any other 2669 // added values are loop invariant. If so, we can fold them into the 2670 // recurrence. 2671 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2672 ++Idx; 2673 2674 // Scan over all recurrences, trying to fold loop invariants into them. 2675 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2676 // Scan all of the other operands to this add and add them to the vector if 2677 // they are loop invariant w.r.t. the recurrence. 2678 SmallVector<const SCEV *, 8> LIOps; 2679 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2680 const Loop *AddRecLoop = AddRec->getLoop(); 2681 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2682 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2683 LIOps.push_back(Ops[i]); 2684 Ops.erase(Ops.begin()+i); 2685 --i; --e; 2686 } 2687 2688 // If we found some loop invariants, fold them into the recurrence. 2689 if (!LIOps.empty()) { 2690 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2691 LIOps.push_back(AddRec->getStart()); 2692 2693 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2694 AddRec->op_end()); 2695 // This follows from the fact that the no-wrap flags on the outer add 2696 // expression are applicable on the 0th iteration, when the add recurrence 2697 // will be equal to its start value. 2698 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2699 2700 // Build the new addrec. Propagate the NUW and NSW flags if both the 2701 // outer add and the inner addrec are guaranteed to have no overflow. 2702 // Always propagate NW. 2703 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2704 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2705 2706 // If all of the other operands were loop invariant, we are done. 2707 if (Ops.size() == 1) return NewRec; 2708 2709 // Otherwise, add the folded AddRec by the non-invariant parts. 2710 for (unsigned i = 0;; ++i) 2711 if (Ops[i] == AddRec) { 2712 Ops[i] = NewRec; 2713 break; 2714 } 2715 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2716 } 2717 2718 // Okay, if there weren't any loop invariants to be folded, check to see if 2719 // there are multiple AddRec's with the same loop induction variable being 2720 // added together. If so, we can fold them. 2721 for (unsigned OtherIdx = Idx+1; 2722 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2723 ++OtherIdx) { 2724 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2725 // so that the 1st found AddRecExpr is dominated by all others. 2726 assert(DT.dominates( 2727 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2728 AddRec->getLoop()->getHeader()) && 2729 "AddRecExprs are not sorted in reverse dominance order?"); 2730 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2731 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2732 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2733 AddRec->op_end()); 2734 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2735 ++OtherIdx) { 2736 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2737 if (OtherAddRec->getLoop() == AddRecLoop) { 2738 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2739 i != e; ++i) { 2740 if (i >= AddRecOps.size()) { 2741 AddRecOps.append(OtherAddRec->op_begin()+i, 2742 OtherAddRec->op_end()); 2743 break; 2744 } 2745 SmallVector<const SCEV *, 2> TwoOps = { 2746 AddRecOps[i], OtherAddRec->getOperand(i)}; 2747 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2748 } 2749 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2750 } 2751 } 2752 // Step size has changed, so we cannot guarantee no self-wraparound. 2753 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2754 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2755 } 2756 } 2757 2758 // Otherwise couldn't fold anything into this recurrence. Move onto the 2759 // next one. 2760 } 2761 2762 // Okay, it looks like we really DO need an add expr. Check to see if we 2763 // already have one, otherwise create a new one. 2764 return getOrCreateAddExpr(Ops, Flags); 2765 } 2766 2767 const SCEV * 2768 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2769 SCEV::NoWrapFlags Flags) { 2770 FoldingSetNodeID ID; 2771 ID.AddInteger(scAddExpr); 2772 for (const SCEV *Op : Ops) 2773 ID.AddPointer(Op); 2774 void *IP = nullptr; 2775 SCEVAddExpr *S = 2776 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2777 if (!S) { 2778 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2779 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2780 S = new (SCEVAllocator) 2781 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2782 UniqueSCEVs.InsertNode(S, IP); 2783 addToLoopUseLists(S); 2784 } 2785 S->setNoWrapFlags(Flags); 2786 return S; 2787 } 2788 2789 const SCEV * 2790 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2791 const Loop *L, SCEV::NoWrapFlags Flags) { 2792 FoldingSetNodeID ID; 2793 ID.AddInteger(scAddRecExpr); 2794 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2795 ID.AddPointer(Ops[i]); 2796 ID.AddPointer(L); 2797 void *IP = nullptr; 2798 SCEVAddRecExpr *S = 2799 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2800 if (!S) { 2801 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2802 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2803 S = new (SCEVAllocator) 2804 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2805 UniqueSCEVs.InsertNode(S, IP); 2806 addToLoopUseLists(S); 2807 } 2808 S->setNoWrapFlags(Flags); 2809 return S; 2810 } 2811 2812 const SCEV * 2813 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2814 SCEV::NoWrapFlags Flags) { 2815 FoldingSetNodeID ID; 2816 ID.AddInteger(scMulExpr); 2817 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2818 ID.AddPointer(Ops[i]); 2819 void *IP = nullptr; 2820 SCEVMulExpr *S = 2821 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2822 if (!S) { 2823 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2824 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2825 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2826 O, Ops.size()); 2827 UniqueSCEVs.InsertNode(S, IP); 2828 addToLoopUseLists(S); 2829 } 2830 S->setNoWrapFlags(Flags); 2831 return S; 2832 } 2833 2834 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2835 uint64_t k = i*j; 2836 if (j > 1 && k / j != i) Overflow = true; 2837 return k; 2838 } 2839 2840 /// Compute the result of "n choose k", the binomial coefficient. If an 2841 /// intermediate computation overflows, Overflow will be set and the return will 2842 /// be garbage. Overflow is not cleared on absence of overflow. 2843 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2844 // We use the multiplicative formula: 2845 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2846 // At each iteration, we take the n-th term of the numeral and divide by the 2847 // (k-n)th term of the denominator. This division will always produce an 2848 // integral result, and helps reduce the chance of overflow in the 2849 // intermediate computations. However, we can still overflow even when the 2850 // final result would fit. 2851 2852 if (n == 0 || n == k) return 1; 2853 if (k > n) return 0; 2854 2855 if (k > n/2) 2856 k = n-k; 2857 2858 uint64_t r = 1; 2859 for (uint64_t i = 1; i <= k; ++i) { 2860 r = umul_ov(r, n-(i-1), Overflow); 2861 r /= i; 2862 } 2863 return r; 2864 } 2865 2866 /// Determine if any of the operands in this SCEV are a constant or if 2867 /// any of the add or multiply expressions in this SCEV contain a constant. 2868 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2869 struct FindConstantInAddMulChain { 2870 bool FoundConstant = false; 2871 2872 bool follow(const SCEV *S) { 2873 FoundConstant |= isa<SCEVConstant>(S); 2874 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2875 } 2876 2877 bool isDone() const { 2878 return FoundConstant; 2879 } 2880 }; 2881 2882 FindConstantInAddMulChain F; 2883 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2884 ST.visitAll(StartExpr); 2885 return F.FoundConstant; 2886 } 2887 2888 /// Get a canonical multiply expression, or something simpler if possible. 2889 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2890 SCEV::NoWrapFlags Flags, 2891 unsigned Depth) { 2892 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2893 "only nuw or nsw allowed"); 2894 assert(!Ops.empty() && "Cannot get empty mul!"); 2895 if (Ops.size() == 1) return Ops[0]; 2896 #ifndef NDEBUG 2897 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2898 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2899 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2900 "SCEVMulExpr operand types don't match!"); 2901 #endif 2902 2903 // Sort by complexity, this groups all similar expression types together. 2904 GroupByComplexity(Ops, &LI, DT); 2905 2906 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2907 2908 // Limit recursion calls depth. 2909 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2910 return getOrCreateMulExpr(Ops, Flags); 2911 2912 // If there are any constants, fold them together. 2913 unsigned Idx = 0; 2914 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2915 2916 if (Ops.size() == 2) 2917 // C1*(C2+V) -> C1*C2 + C1*V 2918 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2919 // If any of Add's ops are Adds or Muls with a constant, apply this 2920 // transformation as well. 2921 // 2922 // TODO: There are some cases where this transformation is not 2923 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2924 // this transformation should be narrowed down. 2925 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2926 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2927 SCEV::FlagAnyWrap, Depth + 1), 2928 getMulExpr(LHSC, Add->getOperand(1), 2929 SCEV::FlagAnyWrap, Depth + 1), 2930 SCEV::FlagAnyWrap, Depth + 1); 2931 2932 ++Idx; 2933 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2934 // We found two constants, fold them together! 2935 ConstantInt *Fold = 2936 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2937 Ops[0] = getConstant(Fold); 2938 Ops.erase(Ops.begin()+1); // Erase the folded element 2939 if (Ops.size() == 1) return Ops[0]; 2940 LHSC = cast<SCEVConstant>(Ops[0]); 2941 } 2942 2943 // If we are left with a constant one being multiplied, strip it off. 2944 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2945 Ops.erase(Ops.begin()); 2946 --Idx; 2947 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2948 // If we have a multiply of zero, it will always be zero. 2949 return Ops[0]; 2950 } else if (Ops[0]->isAllOnesValue()) { 2951 // If we have a mul by -1 of an add, try distributing the -1 among the 2952 // add operands. 2953 if (Ops.size() == 2) { 2954 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2955 SmallVector<const SCEV *, 4> NewOps; 2956 bool AnyFolded = false; 2957 for (const SCEV *AddOp : Add->operands()) { 2958 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2959 Depth + 1); 2960 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2961 NewOps.push_back(Mul); 2962 } 2963 if (AnyFolded) 2964 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2965 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2966 // Negation preserves a recurrence's no self-wrap property. 2967 SmallVector<const SCEV *, 4> Operands; 2968 for (const SCEV *AddRecOp : AddRec->operands()) 2969 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2970 Depth + 1)); 2971 2972 return getAddRecExpr(Operands, AddRec->getLoop(), 2973 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2974 } 2975 } 2976 } 2977 2978 if (Ops.size() == 1) 2979 return Ops[0]; 2980 } 2981 2982 // Skip over the add expression until we get to a multiply. 2983 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2984 ++Idx; 2985 2986 // If there are mul operands inline them all into this expression. 2987 if (Idx < Ops.size()) { 2988 bool DeletedMul = false; 2989 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2990 if (Ops.size() > MulOpsInlineThreshold) 2991 break; 2992 // If we have an mul, expand the mul operands onto the end of the 2993 // operands list. 2994 Ops.erase(Ops.begin()+Idx); 2995 Ops.append(Mul->op_begin(), Mul->op_end()); 2996 DeletedMul = true; 2997 } 2998 2999 // If we deleted at least one mul, we added operands to the end of the 3000 // list, and they are not necessarily sorted. Recurse to resort and 3001 // resimplify any operands we just acquired. 3002 if (DeletedMul) 3003 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3004 } 3005 3006 // If there are any add recurrences in the operands list, see if any other 3007 // added values are loop invariant. If so, we can fold them into the 3008 // recurrence. 3009 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3010 ++Idx; 3011 3012 // Scan over all recurrences, trying to fold loop invariants into them. 3013 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3014 // Scan all of the other operands to this mul and add them to the vector 3015 // if they are loop invariant w.r.t. the recurrence. 3016 SmallVector<const SCEV *, 8> LIOps; 3017 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3018 const Loop *AddRecLoop = AddRec->getLoop(); 3019 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3020 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3021 LIOps.push_back(Ops[i]); 3022 Ops.erase(Ops.begin()+i); 3023 --i; --e; 3024 } 3025 3026 // If we found some loop invariants, fold them into the recurrence. 3027 if (!LIOps.empty()) { 3028 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3029 SmallVector<const SCEV *, 4> NewOps; 3030 NewOps.reserve(AddRec->getNumOperands()); 3031 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3032 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3033 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3034 SCEV::FlagAnyWrap, Depth + 1)); 3035 3036 // Build the new addrec. Propagate the NUW and NSW flags if both the 3037 // outer mul and the inner addrec are guaranteed to have no overflow. 3038 // 3039 // No self-wrap cannot be guaranteed after changing the step size, but 3040 // will be inferred if either NUW or NSW is true. 3041 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 3042 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 3043 3044 // If all of the other operands were loop invariant, we are done. 3045 if (Ops.size() == 1) return NewRec; 3046 3047 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3048 for (unsigned i = 0;; ++i) 3049 if (Ops[i] == AddRec) { 3050 Ops[i] = NewRec; 3051 break; 3052 } 3053 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3054 } 3055 3056 // Okay, if there weren't any loop invariants to be folded, check to see 3057 // if there are multiple AddRec's with the same loop induction variable 3058 // being multiplied together. If so, we can fold them. 3059 3060 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3061 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3062 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3063 // ]]],+,...up to x=2n}. 3064 // Note that the arguments to choose() are always integers with values 3065 // known at compile time, never SCEV objects. 3066 // 3067 // The implementation avoids pointless extra computations when the two 3068 // addrec's are of different length (mathematically, it's equivalent to 3069 // an infinite stream of zeros on the right). 3070 bool OpsModified = false; 3071 for (unsigned OtherIdx = Idx+1; 3072 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3073 ++OtherIdx) { 3074 const SCEVAddRecExpr *OtherAddRec = 3075 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3076 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3077 continue; 3078 3079 // Limit max number of arguments to avoid creation of unreasonably big 3080 // SCEVAddRecs with very complex operands. 3081 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3082 MaxAddRecSize || isHugeExpression(AddRec) || 3083 isHugeExpression(OtherAddRec)) 3084 continue; 3085 3086 bool Overflow = false; 3087 Type *Ty = AddRec->getType(); 3088 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3089 SmallVector<const SCEV*, 7> AddRecOps; 3090 for (int x = 0, xe = AddRec->getNumOperands() + 3091 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3092 SmallVector <const SCEV *, 7> SumOps; 3093 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3094 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3095 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3096 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3097 z < ze && !Overflow; ++z) { 3098 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3099 uint64_t Coeff; 3100 if (LargerThan64Bits) 3101 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3102 else 3103 Coeff = Coeff1*Coeff2; 3104 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3105 const SCEV *Term1 = AddRec->getOperand(y-z); 3106 const SCEV *Term2 = OtherAddRec->getOperand(z); 3107 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3108 SCEV::FlagAnyWrap, Depth + 1)); 3109 } 3110 } 3111 if (SumOps.empty()) 3112 SumOps.push_back(getZero(Ty)); 3113 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3114 } 3115 if (!Overflow) { 3116 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3117 SCEV::FlagAnyWrap); 3118 if (Ops.size() == 2) return NewAddRec; 3119 Ops[Idx] = NewAddRec; 3120 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3121 OpsModified = true; 3122 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3123 if (!AddRec) 3124 break; 3125 } 3126 } 3127 if (OpsModified) 3128 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3129 3130 // Otherwise couldn't fold anything into this recurrence. Move onto the 3131 // next one. 3132 } 3133 3134 // Okay, it looks like we really DO need an mul expr. Check to see if we 3135 // already have one, otherwise create a new one. 3136 return getOrCreateMulExpr(Ops, Flags); 3137 } 3138 3139 /// Represents an unsigned remainder expression based on unsigned division. 3140 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3141 const SCEV *RHS) { 3142 assert(getEffectiveSCEVType(LHS->getType()) == 3143 getEffectiveSCEVType(RHS->getType()) && 3144 "SCEVURemExpr operand types don't match!"); 3145 3146 // Short-circuit easy cases 3147 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3148 // If constant is one, the result is trivial 3149 if (RHSC->getValue()->isOne()) 3150 return getZero(LHS->getType()); // X urem 1 --> 0 3151 3152 // If constant is a power of two, fold into a zext(trunc(LHS)). 3153 if (RHSC->getAPInt().isPowerOf2()) { 3154 Type *FullTy = LHS->getType(); 3155 Type *TruncTy = 3156 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3157 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3158 } 3159 } 3160 3161 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3162 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3163 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3164 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3165 } 3166 3167 /// Get a canonical unsigned division expression, or something simpler if 3168 /// possible. 3169 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3170 const SCEV *RHS) { 3171 assert(getEffectiveSCEVType(LHS->getType()) == 3172 getEffectiveSCEVType(RHS->getType()) && 3173 "SCEVUDivExpr operand types don't match!"); 3174 3175 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3176 if (RHSC->getValue()->isOne()) 3177 return LHS; // X udiv 1 --> x 3178 // If the denominator is zero, the result of the udiv is undefined. Don't 3179 // try to analyze it, because the resolution chosen here may differ from 3180 // the resolution chosen in other parts of the compiler. 3181 if (!RHSC->getValue()->isZero()) { 3182 // Determine if the division can be folded into the operands of 3183 // its operands. 3184 // TODO: Generalize this to non-constants by using known-bits information. 3185 Type *Ty = LHS->getType(); 3186 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3187 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3188 // For non-power-of-two values, effectively round the value up to the 3189 // nearest power of two. 3190 if (!RHSC->getAPInt().isPowerOf2()) 3191 ++MaxShiftAmt; 3192 IntegerType *ExtTy = 3193 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3194 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3195 if (const SCEVConstant *Step = 3196 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3197 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3198 const APInt &StepInt = Step->getAPInt(); 3199 const APInt &DivInt = RHSC->getAPInt(); 3200 if (!StepInt.urem(DivInt) && 3201 getZeroExtendExpr(AR, ExtTy) == 3202 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3203 getZeroExtendExpr(Step, ExtTy), 3204 AR->getLoop(), SCEV::FlagAnyWrap)) { 3205 SmallVector<const SCEV *, 4> Operands; 3206 for (const SCEV *Op : AR->operands()) 3207 Operands.push_back(getUDivExpr(Op, RHS)); 3208 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3209 } 3210 /// Get a canonical UDivExpr for a recurrence. 3211 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3212 // We can currently only fold X%N if X is constant. 3213 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3214 if (StartC && !DivInt.urem(StepInt) && 3215 getZeroExtendExpr(AR, ExtTy) == 3216 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3217 getZeroExtendExpr(Step, ExtTy), 3218 AR->getLoop(), SCEV::FlagAnyWrap)) { 3219 const APInt &StartInt = StartC->getAPInt(); 3220 const APInt &StartRem = StartInt.urem(StepInt); 3221 if (StartRem != 0) 3222 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3223 AR->getLoop(), SCEV::FlagNW); 3224 } 3225 } 3226 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3227 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3228 SmallVector<const SCEV *, 4> Operands; 3229 for (const SCEV *Op : M->operands()) 3230 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3231 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3232 // Find an operand that's safely divisible. 3233 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3234 const SCEV *Op = M->getOperand(i); 3235 const SCEV *Div = getUDivExpr(Op, RHSC); 3236 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3237 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3238 M->op_end()); 3239 Operands[i] = Div; 3240 return getMulExpr(Operands); 3241 } 3242 } 3243 } 3244 3245 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3246 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3247 if (auto *DivisorConstant = 3248 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3249 bool Overflow = false; 3250 APInt NewRHS = 3251 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3252 if (Overflow) { 3253 return getConstant(RHSC->getType(), 0, false); 3254 } 3255 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3256 } 3257 } 3258 3259 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3260 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3261 SmallVector<const SCEV *, 4> Operands; 3262 for (const SCEV *Op : A->operands()) 3263 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3264 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3265 Operands.clear(); 3266 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3267 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3268 if (isa<SCEVUDivExpr>(Op) || 3269 getMulExpr(Op, RHS) != A->getOperand(i)) 3270 break; 3271 Operands.push_back(Op); 3272 } 3273 if (Operands.size() == A->getNumOperands()) 3274 return getAddExpr(Operands); 3275 } 3276 } 3277 3278 // Fold if both operands are constant. 3279 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3280 Constant *LHSCV = LHSC->getValue(); 3281 Constant *RHSCV = RHSC->getValue(); 3282 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3283 RHSCV))); 3284 } 3285 } 3286 } 3287 3288 FoldingSetNodeID ID; 3289 ID.AddInteger(scUDivExpr); 3290 ID.AddPointer(LHS); 3291 ID.AddPointer(RHS); 3292 void *IP = nullptr; 3293 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3294 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3295 LHS, RHS); 3296 UniqueSCEVs.InsertNode(S, IP); 3297 addToLoopUseLists(S); 3298 return S; 3299 } 3300 3301 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3302 APInt A = C1->getAPInt().abs(); 3303 APInt B = C2->getAPInt().abs(); 3304 uint32_t ABW = A.getBitWidth(); 3305 uint32_t BBW = B.getBitWidth(); 3306 3307 if (ABW > BBW) 3308 B = B.zext(ABW); 3309 else if (ABW < BBW) 3310 A = A.zext(BBW); 3311 3312 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3313 } 3314 3315 /// Get a canonical unsigned division expression, or something simpler if 3316 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3317 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3318 /// it's not exact because the udiv may be clearing bits. 3319 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3320 const SCEV *RHS) { 3321 // TODO: we could try to find factors in all sorts of things, but for now we 3322 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3323 // end of this file for inspiration. 3324 3325 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3326 if (!Mul || !Mul->hasNoUnsignedWrap()) 3327 return getUDivExpr(LHS, RHS); 3328 3329 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3330 // If the mulexpr multiplies by a constant, then that constant must be the 3331 // first element of the mulexpr. 3332 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3333 if (LHSCst == RHSCst) { 3334 SmallVector<const SCEV *, 2> Operands; 3335 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3336 return getMulExpr(Operands); 3337 } 3338 3339 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3340 // that there's a factor provided by one of the other terms. We need to 3341 // check. 3342 APInt Factor = gcd(LHSCst, RHSCst); 3343 if (!Factor.isIntN(1)) { 3344 LHSCst = 3345 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3346 RHSCst = 3347 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3348 SmallVector<const SCEV *, 2> Operands; 3349 Operands.push_back(LHSCst); 3350 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3351 LHS = getMulExpr(Operands); 3352 RHS = RHSCst; 3353 Mul = dyn_cast<SCEVMulExpr>(LHS); 3354 if (!Mul) 3355 return getUDivExactExpr(LHS, RHS); 3356 } 3357 } 3358 } 3359 3360 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3361 if (Mul->getOperand(i) == RHS) { 3362 SmallVector<const SCEV *, 2> Operands; 3363 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3364 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3365 return getMulExpr(Operands); 3366 } 3367 } 3368 3369 return getUDivExpr(LHS, RHS); 3370 } 3371 3372 /// Get an add recurrence expression for the specified loop. Simplify the 3373 /// expression as much as possible. 3374 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3375 const Loop *L, 3376 SCEV::NoWrapFlags Flags) { 3377 SmallVector<const SCEV *, 4> Operands; 3378 Operands.push_back(Start); 3379 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3380 if (StepChrec->getLoop() == L) { 3381 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3382 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3383 } 3384 3385 Operands.push_back(Step); 3386 return getAddRecExpr(Operands, L, Flags); 3387 } 3388 3389 /// Get an add recurrence expression for the specified loop. Simplify the 3390 /// expression as much as possible. 3391 const SCEV * 3392 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3393 const Loop *L, SCEV::NoWrapFlags Flags) { 3394 if (Operands.size() == 1) return Operands[0]; 3395 #ifndef NDEBUG 3396 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3397 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3398 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3399 "SCEVAddRecExpr operand types don't match!"); 3400 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3401 assert(isLoopInvariant(Operands[i], L) && 3402 "SCEVAddRecExpr operand is not loop-invariant!"); 3403 #endif 3404 3405 if (Operands.back()->isZero()) { 3406 Operands.pop_back(); 3407 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3408 } 3409 3410 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3411 // use that information to infer NUW and NSW flags. However, computing a 3412 // BE count requires calling getAddRecExpr, so we may not yet have a 3413 // meaningful BE count at this point (and if we don't, we'd be stuck 3414 // with a SCEVCouldNotCompute as the cached BE count). 3415 3416 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3417 3418 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3419 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3420 const Loop *NestedLoop = NestedAR->getLoop(); 3421 if (L->contains(NestedLoop) 3422 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3423 : (!NestedLoop->contains(L) && 3424 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3425 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3426 NestedAR->op_end()); 3427 Operands[0] = NestedAR->getStart(); 3428 // AddRecs require their operands be loop-invariant with respect to their 3429 // loops. Don't perform this transformation if it would break this 3430 // requirement. 3431 bool AllInvariant = all_of( 3432 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3433 3434 if (AllInvariant) { 3435 // Create a recurrence for the outer loop with the same step size. 3436 // 3437 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3438 // inner recurrence has the same property. 3439 SCEV::NoWrapFlags OuterFlags = 3440 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3441 3442 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3443 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3444 return isLoopInvariant(Op, NestedLoop); 3445 }); 3446 3447 if (AllInvariant) { 3448 // Ok, both add recurrences are valid after the transformation. 3449 // 3450 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3451 // the outer recurrence has the same property. 3452 SCEV::NoWrapFlags InnerFlags = 3453 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3454 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3455 } 3456 } 3457 // Reset Operands to its original state. 3458 Operands[0] = NestedAR; 3459 } 3460 } 3461 3462 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3463 // already have one, otherwise create a new one. 3464 return getOrCreateAddRecExpr(Operands, L, Flags); 3465 } 3466 3467 const SCEV * 3468 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3469 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3470 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3471 // getSCEV(Base)->getType() has the same address space as Base->getType() 3472 // because SCEV::getType() preserves the address space. 3473 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3474 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3475 // instruction to its SCEV, because the Instruction may be guarded by control 3476 // flow and the no-overflow bits may not be valid for the expression in any 3477 // context. This can be fixed similarly to how these flags are handled for 3478 // adds. 3479 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3480 : SCEV::FlagAnyWrap; 3481 3482 const SCEV *TotalOffset = getZero(IntPtrTy); 3483 // The array size is unimportant. The first thing we do on CurTy is getting 3484 // its element type. 3485 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3486 for (const SCEV *IndexExpr : IndexExprs) { 3487 // Compute the (potentially symbolic) offset in bytes for this index. 3488 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3489 // For a struct, add the member offset. 3490 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3491 unsigned FieldNo = Index->getZExtValue(); 3492 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3493 3494 // Add the field offset to the running total offset. 3495 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3496 3497 // Update CurTy to the type of the field at Index. 3498 CurTy = STy->getTypeAtIndex(Index); 3499 } else { 3500 // Update CurTy to its element type. 3501 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3502 // For an array, add the element offset, explicitly scaled. 3503 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3504 // Getelementptr indices are signed. 3505 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3506 3507 // Multiply the index by the element size to compute the element offset. 3508 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3509 3510 // Add the element offset to the running total offset. 3511 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3512 } 3513 } 3514 3515 // Add the total offset from all the GEP indices to the base. 3516 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3517 } 3518 3519 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3520 const SCEV *RHS) { 3521 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3522 return getSMaxExpr(Ops); 3523 } 3524 3525 std::tuple<const SCEV *, FoldingSetNodeID, void *> 3526 ScalarEvolution::findExistingSCEVInCache(int SCEVType, 3527 ArrayRef<const SCEV *> Ops) { 3528 FoldingSetNodeID ID; 3529 void *IP = nullptr; 3530 ID.AddInteger(SCEVType); 3531 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3532 ID.AddPointer(Ops[i]); 3533 return std::tuple<const SCEV *, FoldingSetNodeID, void *>( 3534 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3535 } 3536 3537 const SCEV * 3538 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3539 assert(!Ops.empty() && "Cannot get empty smax!"); 3540 if (Ops.size() == 1) return Ops[0]; 3541 #ifndef NDEBUG 3542 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3543 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3544 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3545 "SCEVSMaxExpr operand types don't match!"); 3546 #endif 3547 3548 // Sort by complexity, this groups all similar expression types together. 3549 GroupByComplexity(Ops, &LI, DT); 3550 3551 // Check if we have created the same SMax expression before. 3552 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(scSMaxExpr, Ops))) { 3553 return S; 3554 } 3555 3556 // If there are any constants, fold them together. 3557 unsigned Idx = 0; 3558 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3559 ++Idx; 3560 assert(Idx < Ops.size()); 3561 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3562 // We found two constants, fold them together! 3563 ConstantInt *Fold = ConstantInt::get( 3564 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3565 Ops[0] = getConstant(Fold); 3566 Ops.erase(Ops.begin()+1); // Erase the folded element 3567 if (Ops.size() == 1) return Ops[0]; 3568 LHSC = cast<SCEVConstant>(Ops[0]); 3569 } 3570 3571 // If we are left with a constant minimum-int, strip it off. 3572 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3573 Ops.erase(Ops.begin()); 3574 --Idx; 3575 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3576 // If we have an smax with a constant maximum-int, it will always be 3577 // maximum-int. 3578 return Ops[0]; 3579 } 3580 3581 if (Ops.size() == 1) return Ops[0]; 3582 } 3583 3584 // Find the first SMax 3585 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3586 ++Idx; 3587 3588 // Check to see if one of the operands is an SMax. If so, expand its operands 3589 // onto our operand list, and recurse to simplify. 3590 if (Idx < Ops.size()) { 3591 bool DeletedSMax = false; 3592 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3593 Ops.erase(Ops.begin()+Idx); 3594 Ops.append(SMax->op_begin(), SMax->op_end()); 3595 DeletedSMax = true; 3596 } 3597 3598 if (DeletedSMax) 3599 return getSMaxExpr(Ops); 3600 } 3601 3602 // Okay, check to see if the same value occurs in the operand list twice. If 3603 // so, delete one. Since we sorted the list, these values are required to 3604 // be adjacent. 3605 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3606 // X smax Y smax Y --> X smax Y 3607 // X smax Y --> X, if X is always greater than Y 3608 if (Ops[i] == Ops[i+1] || 3609 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3610 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3611 --i; --e; 3612 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3613 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3614 --i; --e; 3615 } 3616 3617 if (Ops.size() == 1) return Ops[0]; 3618 3619 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3620 3621 // Okay, it looks like we really DO need an smax expr. Check to see if we 3622 // already have one, otherwise create a new one. 3623 const SCEV *ExistingSCEV; 3624 FoldingSetNodeID ID; 3625 void *IP; 3626 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(scSMaxExpr, Ops); 3627 if (ExistingSCEV) 3628 return ExistingSCEV; 3629 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3630 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3631 SCEV *S = 3632 new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 3633 UniqueSCEVs.InsertNode(S, IP); 3634 addToLoopUseLists(S); 3635 return S; 3636 } 3637 3638 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3639 const SCEV *RHS) { 3640 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3641 return getUMaxExpr(Ops); 3642 } 3643 3644 const SCEV * 3645 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3646 assert(!Ops.empty() && "Cannot get empty umax!"); 3647 if (Ops.size() == 1) return Ops[0]; 3648 #ifndef NDEBUG 3649 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3650 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3651 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3652 "SCEVUMaxExpr operand types don't match!"); 3653 #endif 3654 3655 // Sort by complexity, this groups all similar expression types together. 3656 GroupByComplexity(Ops, &LI, DT); 3657 3658 // Check if we have created the same UMax expression before. 3659 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(scUMaxExpr, Ops))) { 3660 return S; 3661 } 3662 3663 // If there are any constants, fold them together. 3664 unsigned Idx = 0; 3665 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3666 ++Idx; 3667 assert(Idx < Ops.size()); 3668 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3669 // We found two constants, fold them together! 3670 ConstantInt *Fold = ConstantInt::get( 3671 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3672 Ops[0] = getConstant(Fold); 3673 Ops.erase(Ops.begin()+1); // Erase the folded element 3674 if (Ops.size() == 1) return Ops[0]; 3675 LHSC = cast<SCEVConstant>(Ops[0]); 3676 } 3677 3678 // If we are left with a constant minimum-int, strip it off. 3679 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3680 Ops.erase(Ops.begin()); 3681 --Idx; 3682 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3683 // If we have an umax with a constant maximum-int, it will always be 3684 // maximum-int. 3685 return Ops[0]; 3686 } 3687 3688 if (Ops.size() == 1) return Ops[0]; 3689 } 3690 3691 // Find the first UMax 3692 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3693 ++Idx; 3694 3695 // Check to see if one of the operands is a UMax. If so, expand its operands 3696 // onto our operand list, and recurse to simplify. 3697 if (Idx < Ops.size()) { 3698 bool DeletedUMax = false; 3699 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3700 Ops.erase(Ops.begin()+Idx); 3701 Ops.append(UMax->op_begin(), UMax->op_end()); 3702 DeletedUMax = true; 3703 } 3704 3705 if (DeletedUMax) 3706 return getUMaxExpr(Ops); 3707 } 3708 3709 // Okay, check to see if the same value occurs in the operand list twice. If 3710 // so, delete one. Since we sorted the list, these values are required to 3711 // be adjacent. 3712 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3713 // X umax Y umax Y --> X umax Y 3714 // X umax Y --> X, if X is always greater than Y 3715 if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning( 3716 ICmpInst::ICMP_UGE, Ops[i], Ops[i + 1])) { 3717 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3718 --i; --e; 3719 } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, Ops[i], 3720 Ops[i + 1])) { 3721 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3722 --i; --e; 3723 } 3724 3725 if (Ops.size() == 1) return Ops[0]; 3726 3727 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3728 3729 // Okay, it looks like we really DO need a umax expr. Check to see if we 3730 // already have one, otherwise create a new one. 3731 const SCEV *ExistingSCEV; 3732 FoldingSetNodeID ID; 3733 void *IP; 3734 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(scUMaxExpr, Ops); 3735 if (ExistingSCEV) 3736 return ExistingSCEV; 3737 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3738 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3739 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3740 O, Ops.size()); 3741 UniqueSCEVs.InsertNode(S, IP); 3742 addToLoopUseLists(S); 3743 return S; 3744 } 3745 3746 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3747 const SCEV *RHS) { 3748 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3749 return getSMinExpr(Ops); 3750 } 3751 3752 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3753 // ~smax(~x, ~y, ~z) == smin(x, y, z). 3754 SmallVector<const SCEV *, 2> NotOps; 3755 for (auto *S : Ops) 3756 NotOps.push_back(getNotSCEV(S)); 3757 return getNotSCEV(getSMaxExpr(NotOps)); 3758 } 3759 3760 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3761 const SCEV *RHS) { 3762 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3763 return getUMinExpr(Ops); 3764 } 3765 3766 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3767 assert(!Ops.empty() && "At least one operand must be!"); 3768 // Trivial case. 3769 if (Ops.size() == 1) 3770 return Ops[0]; 3771 3772 // ~umax(~x, ~y, ~z) == umin(x, y, z). 3773 SmallVector<const SCEV *, 2> NotOps; 3774 for (auto *S : Ops) 3775 NotOps.push_back(getNotSCEV(S)); 3776 return getNotSCEV(getUMaxExpr(NotOps)); 3777 } 3778 3779 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3780 // We can bypass creating a target-independent 3781 // constant expression and then folding it back into a ConstantInt. 3782 // This is just a compile-time optimization. 3783 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3784 } 3785 3786 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3787 StructType *STy, 3788 unsigned FieldNo) { 3789 // We can bypass creating a target-independent 3790 // constant expression and then folding it back into a ConstantInt. 3791 // This is just a compile-time optimization. 3792 return getConstant( 3793 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3794 } 3795 3796 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3797 // Don't attempt to do anything other than create a SCEVUnknown object 3798 // here. createSCEV only calls getUnknown after checking for all other 3799 // interesting possibilities, and any other code that calls getUnknown 3800 // is doing so in order to hide a value from SCEV canonicalization. 3801 3802 FoldingSetNodeID ID; 3803 ID.AddInteger(scUnknown); 3804 ID.AddPointer(V); 3805 void *IP = nullptr; 3806 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3807 assert(cast<SCEVUnknown>(S)->getValue() == V && 3808 "Stale SCEVUnknown in uniquing map!"); 3809 return S; 3810 } 3811 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3812 FirstUnknown); 3813 FirstUnknown = cast<SCEVUnknown>(S); 3814 UniqueSCEVs.InsertNode(S, IP); 3815 return S; 3816 } 3817 3818 //===----------------------------------------------------------------------===// 3819 // Basic SCEV Analysis and PHI Idiom Recognition Code 3820 // 3821 3822 /// Test if values of the given type are analyzable within the SCEV 3823 /// framework. This primarily includes integer types, and it can optionally 3824 /// include pointer types if the ScalarEvolution class has access to 3825 /// target-specific information. 3826 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3827 // Integers and pointers are always SCEVable. 3828 return Ty->isIntOrPtrTy(); 3829 } 3830 3831 /// Return the size in bits of the specified type, for which isSCEVable must 3832 /// return true. 3833 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3834 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3835 if (Ty->isPointerTy()) 3836 return getDataLayout().getIndexTypeSizeInBits(Ty); 3837 return getDataLayout().getTypeSizeInBits(Ty); 3838 } 3839 3840 /// Return a type with the same bitwidth as the given type and which represents 3841 /// how SCEV will treat the given type, for which isSCEVable must return 3842 /// true. For pointer types, this is the pointer-sized integer type. 3843 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3844 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3845 3846 if (Ty->isIntegerTy()) 3847 return Ty; 3848 3849 // The only other support type is pointer. 3850 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3851 return getDataLayout().getIntPtrType(Ty); 3852 } 3853 3854 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3855 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3856 } 3857 3858 const SCEV *ScalarEvolution::getCouldNotCompute() { 3859 return CouldNotCompute.get(); 3860 } 3861 3862 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3863 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3864 auto *SU = dyn_cast<SCEVUnknown>(S); 3865 return SU && SU->getValue() == nullptr; 3866 }); 3867 3868 return !ContainsNulls; 3869 } 3870 3871 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3872 HasRecMapType::iterator I = HasRecMap.find(S); 3873 if (I != HasRecMap.end()) 3874 return I->second; 3875 3876 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3877 HasRecMap.insert({S, FoundAddRec}); 3878 return FoundAddRec; 3879 } 3880 3881 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3882 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3883 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3884 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3885 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3886 if (!Add) 3887 return {S, nullptr}; 3888 3889 if (Add->getNumOperands() != 2) 3890 return {S, nullptr}; 3891 3892 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3893 if (!ConstOp) 3894 return {S, nullptr}; 3895 3896 return {Add->getOperand(1), ConstOp->getValue()}; 3897 } 3898 3899 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3900 /// by the value and offset from any ValueOffsetPair in the set. 3901 SetVector<ScalarEvolution::ValueOffsetPair> * 3902 ScalarEvolution::getSCEVValues(const SCEV *S) { 3903 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3904 if (SI == ExprValueMap.end()) 3905 return nullptr; 3906 #ifndef NDEBUG 3907 if (VerifySCEVMap) { 3908 // Check there is no dangling Value in the set returned. 3909 for (const auto &VE : SI->second) 3910 assert(ValueExprMap.count(VE.first)); 3911 } 3912 #endif 3913 return &SI->second; 3914 } 3915 3916 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3917 /// cannot be used separately. eraseValueFromMap should be used to remove 3918 /// V from ValueExprMap and ExprValueMap at the same time. 3919 void ScalarEvolution::eraseValueFromMap(Value *V) { 3920 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3921 if (I != ValueExprMap.end()) { 3922 const SCEV *S = I->second; 3923 // Remove {V, 0} from the set of ExprValueMap[S] 3924 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3925 SV->remove({V, nullptr}); 3926 3927 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3928 const SCEV *Stripped; 3929 ConstantInt *Offset; 3930 std::tie(Stripped, Offset) = splitAddExpr(S); 3931 if (Offset != nullptr) { 3932 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3933 SV->remove({V, Offset}); 3934 } 3935 ValueExprMap.erase(V); 3936 } 3937 } 3938 3939 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3940 /// TODO: In reality it is better to check the poison recursively 3941 /// but this is better than nothing. 3942 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3943 if (auto *I = dyn_cast<Instruction>(V)) { 3944 if (isa<OverflowingBinaryOperator>(I)) { 3945 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3946 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3947 return true; 3948 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3949 return true; 3950 } 3951 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3952 return true; 3953 } 3954 return false; 3955 } 3956 3957 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3958 /// create a new one. 3959 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3960 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3961 3962 const SCEV *S = getExistingSCEV(V); 3963 if (S == nullptr) { 3964 S = createSCEV(V); 3965 // During PHI resolution, it is possible to create two SCEVs for the same 3966 // V, so it is needed to double check whether V->S is inserted into 3967 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3968 std::pair<ValueExprMapType::iterator, bool> Pair = 3969 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3970 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3971 ExprValueMap[S].insert({V, nullptr}); 3972 3973 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3974 // ExprValueMap. 3975 const SCEV *Stripped = S; 3976 ConstantInt *Offset = nullptr; 3977 std::tie(Stripped, Offset) = splitAddExpr(S); 3978 // If stripped is SCEVUnknown, don't bother to save 3979 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3980 // increase the complexity of the expansion code. 3981 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3982 // because it may generate add/sub instead of GEP in SCEV expansion. 3983 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3984 !isa<GetElementPtrInst>(V)) 3985 ExprValueMap[Stripped].insert({V, Offset}); 3986 } 3987 } 3988 return S; 3989 } 3990 3991 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3992 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3993 3994 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3995 if (I != ValueExprMap.end()) { 3996 const SCEV *S = I->second; 3997 if (checkValidity(S)) 3998 return S; 3999 eraseValueFromMap(V); 4000 forgetMemoizedResults(S); 4001 } 4002 return nullptr; 4003 } 4004 4005 /// Return a SCEV corresponding to -V = -1*V 4006 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4007 SCEV::NoWrapFlags Flags) { 4008 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4009 return getConstant( 4010 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4011 4012 Type *Ty = V->getType(); 4013 Ty = getEffectiveSCEVType(Ty); 4014 return getMulExpr( 4015 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 4016 } 4017 4018 /// Return a SCEV corresponding to ~V = -1-V 4019 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4020 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4021 return getConstant( 4022 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4023 4024 Type *Ty = V->getType(); 4025 Ty = getEffectiveSCEVType(Ty); 4026 const SCEV *AllOnes = 4027 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 4028 return getMinusSCEV(AllOnes, V); 4029 } 4030 4031 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4032 SCEV::NoWrapFlags Flags, 4033 unsigned Depth) { 4034 // Fast path: X - X --> 0. 4035 if (LHS == RHS) 4036 return getZero(LHS->getType()); 4037 4038 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4039 // makes it so that we cannot make much use of NUW. 4040 auto AddFlags = SCEV::FlagAnyWrap; 4041 const bool RHSIsNotMinSigned = 4042 !getSignedRangeMin(RHS).isMinSignedValue(); 4043 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4044 // Let M be the minimum representable signed value. Then (-1)*RHS 4045 // signed-wraps if and only if RHS is M. That can happen even for 4046 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4047 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4048 // (-1)*RHS, we need to prove that RHS != M. 4049 // 4050 // If LHS is non-negative and we know that LHS - RHS does not 4051 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4052 // either by proving that RHS > M or that LHS >= 0. 4053 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4054 AddFlags = SCEV::FlagNSW; 4055 } 4056 } 4057 4058 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4059 // RHS is NSW and LHS >= 0. 4060 // 4061 // The difficulty here is that the NSW flag may have been proven 4062 // relative to a loop that is to be found in a recurrence in LHS and 4063 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4064 // larger scope than intended. 4065 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4066 4067 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4068 } 4069 4070 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4071 unsigned Depth) { 4072 Type *SrcTy = V->getType(); 4073 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4074 "Cannot truncate or zero extend with non-integer arguments!"); 4075 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4076 return V; // No conversion 4077 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4078 return getTruncateExpr(V, Ty, Depth); 4079 return getZeroExtendExpr(V, Ty, Depth); 4080 } 4081 4082 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4083 unsigned Depth) { 4084 Type *SrcTy = V->getType(); 4085 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4086 "Cannot truncate or zero extend with non-integer arguments!"); 4087 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4088 return V; // No conversion 4089 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4090 return getTruncateExpr(V, Ty, Depth); 4091 return getSignExtendExpr(V, Ty, Depth); 4092 } 4093 4094 const SCEV * 4095 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4096 Type *SrcTy = V->getType(); 4097 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4098 "Cannot noop or zero extend with non-integer arguments!"); 4099 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4100 "getNoopOrZeroExtend cannot truncate!"); 4101 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4102 return V; // No conversion 4103 return getZeroExtendExpr(V, Ty); 4104 } 4105 4106 const SCEV * 4107 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4108 Type *SrcTy = V->getType(); 4109 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4110 "Cannot noop or sign extend with non-integer arguments!"); 4111 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4112 "getNoopOrSignExtend cannot truncate!"); 4113 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4114 return V; // No conversion 4115 return getSignExtendExpr(V, Ty); 4116 } 4117 4118 const SCEV * 4119 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4120 Type *SrcTy = V->getType(); 4121 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4122 "Cannot noop or any extend with non-integer arguments!"); 4123 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4124 "getNoopOrAnyExtend cannot truncate!"); 4125 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4126 return V; // No conversion 4127 return getAnyExtendExpr(V, Ty); 4128 } 4129 4130 const SCEV * 4131 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4132 Type *SrcTy = V->getType(); 4133 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4134 "Cannot truncate or noop with non-integer arguments!"); 4135 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4136 "getTruncateOrNoop cannot extend!"); 4137 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4138 return V; // No conversion 4139 return getTruncateExpr(V, Ty); 4140 } 4141 4142 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4143 const SCEV *RHS) { 4144 const SCEV *PromotedLHS = LHS; 4145 const SCEV *PromotedRHS = RHS; 4146 4147 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4148 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4149 else 4150 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4151 4152 return getUMaxExpr(PromotedLHS, PromotedRHS); 4153 } 4154 4155 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4156 const SCEV *RHS) { 4157 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4158 return getUMinFromMismatchedTypes(Ops); 4159 } 4160 4161 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4162 SmallVectorImpl<const SCEV *> &Ops) { 4163 assert(!Ops.empty() && "At least one operand must be!"); 4164 // Trivial case. 4165 if (Ops.size() == 1) 4166 return Ops[0]; 4167 4168 // Find the max type first. 4169 Type *MaxType = nullptr; 4170 for (auto *S : Ops) 4171 if (MaxType) 4172 MaxType = getWiderType(MaxType, S->getType()); 4173 else 4174 MaxType = S->getType(); 4175 4176 // Extend all ops to max type. 4177 SmallVector<const SCEV *, 2> PromotedOps; 4178 for (auto *S : Ops) 4179 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4180 4181 // Generate umin. 4182 return getUMinExpr(PromotedOps); 4183 } 4184 4185 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4186 // A pointer operand may evaluate to a nonpointer expression, such as null. 4187 if (!V->getType()->isPointerTy()) 4188 return V; 4189 4190 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4191 return getPointerBase(Cast->getOperand()); 4192 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4193 const SCEV *PtrOp = nullptr; 4194 for (const SCEV *NAryOp : NAry->operands()) { 4195 if (NAryOp->getType()->isPointerTy()) { 4196 // Cannot find the base of an expression with multiple pointer operands. 4197 if (PtrOp) 4198 return V; 4199 PtrOp = NAryOp; 4200 } 4201 } 4202 if (!PtrOp) 4203 return V; 4204 return getPointerBase(PtrOp); 4205 } 4206 return V; 4207 } 4208 4209 /// Push users of the given Instruction onto the given Worklist. 4210 static void 4211 PushDefUseChildren(Instruction *I, 4212 SmallVectorImpl<Instruction *> &Worklist) { 4213 // Push the def-use children onto the Worklist stack. 4214 for (User *U : I->users()) 4215 Worklist.push_back(cast<Instruction>(U)); 4216 } 4217 4218 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4219 SmallVector<Instruction *, 16> Worklist; 4220 PushDefUseChildren(PN, Worklist); 4221 4222 SmallPtrSet<Instruction *, 8> Visited; 4223 Visited.insert(PN); 4224 while (!Worklist.empty()) { 4225 Instruction *I = Worklist.pop_back_val(); 4226 if (!Visited.insert(I).second) 4227 continue; 4228 4229 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4230 if (It != ValueExprMap.end()) { 4231 const SCEV *Old = It->second; 4232 4233 // Short-circuit the def-use traversal if the symbolic name 4234 // ceases to appear in expressions. 4235 if (Old != SymName && !hasOperand(Old, SymName)) 4236 continue; 4237 4238 // SCEVUnknown for a PHI either means that it has an unrecognized 4239 // structure, it's a PHI that's in the progress of being computed 4240 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4241 // additional loop trip count information isn't going to change anything. 4242 // In the second case, createNodeForPHI will perform the necessary 4243 // updates on its own when it gets to that point. In the third, we do 4244 // want to forget the SCEVUnknown. 4245 if (!isa<PHINode>(I) || 4246 !isa<SCEVUnknown>(Old) || 4247 (I != PN && Old == SymName)) { 4248 eraseValueFromMap(It->first); 4249 forgetMemoizedResults(Old); 4250 } 4251 } 4252 4253 PushDefUseChildren(I, Worklist); 4254 } 4255 } 4256 4257 namespace { 4258 4259 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4260 /// expression in case its Loop is L. If it is not L then 4261 /// if IgnoreOtherLoops is true then use AddRec itself 4262 /// otherwise rewrite cannot be done. 4263 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4264 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4265 public: 4266 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4267 bool IgnoreOtherLoops = true) { 4268 SCEVInitRewriter Rewriter(L, SE); 4269 const SCEV *Result = Rewriter.visit(S); 4270 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4271 return SE.getCouldNotCompute(); 4272 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4273 ? SE.getCouldNotCompute() 4274 : Result; 4275 } 4276 4277 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4278 if (!SE.isLoopInvariant(Expr, L)) 4279 SeenLoopVariantSCEVUnknown = true; 4280 return Expr; 4281 } 4282 4283 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4284 // Only re-write AddRecExprs for this loop. 4285 if (Expr->getLoop() == L) 4286 return Expr->getStart(); 4287 SeenOtherLoops = true; 4288 return Expr; 4289 } 4290 4291 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4292 4293 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4294 4295 private: 4296 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4297 : SCEVRewriteVisitor(SE), L(L) {} 4298 4299 const Loop *L; 4300 bool SeenLoopVariantSCEVUnknown = false; 4301 bool SeenOtherLoops = false; 4302 }; 4303 4304 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4305 /// increment expression in case its Loop is L. If it is not L then 4306 /// use AddRec itself. 4307 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4308 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4309 public: 4310 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4311 SCEVPostIncRewriter Rewriter(L, SE); 4312 const SCEV *Result = Rewriter.visit(S); 4313 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4314 ? SE.getCouldNotCompute() 4315 : Result; 4316 } 4317 4318 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4319 if (!SE.isLoopInvariant(Expr, L)) 4320 SeenLoopVariantSCEVUnknown = true; 4321 return Expr; 4322 } 4323 4324 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4325 // Only re-write AddRecExprs for this loop. 4326 if (Expr->getLoop() == L) 4327 return Expr->getPostIncExpr(SE); 4328 SeenOtherLoops = true; 4329 return Expr; 4330 } 4331 4332 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4333 4334 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4335 4336 private: 4337 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4338 : SCEVRewriteVisitor(SE), L(L) {} 4339 4340 const Loop *L; 4341 bool SeenLoopVariantSCEVUnknown = false; 4342 bool SeenOtherLoops = false; 4343 }; 4344 4345 /// This class evaluates the compare condition by matching it against the 4346 /// condition of loop latch. If there is a match we assume a true value 4347 /// for the condition while building SCEV nodes. 4348 class SCEVBackedgeConditionFolder 4349 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4350 public: 4351 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4352 ScalarEvolution &SE) { 4353 bool IsPosBECond = false; 4354 Value *BECond = nullptr; 4355 if (BasicBlock *Latch = L->getLoopLatch()) { 4356 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4357 if (BI && BI->isConditional()) { 4358 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4359 "Both outgoing branches should not target same header!"); 4360 BECond = BI->getCondition(); 4361 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4362 } else { 4363 return S; 4364 } 4365 } 4366 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4367 return Rewriter.visit(S); 4368 } 4369 4370 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4371 const SCEV *Result = Expr; 4372 bool InvariantF = SE.isLoopInvariant(Expr, L); 4373 4374 if (!InvariantF) { 4375 Instruction *I = cast<Instruction>(Expr->getValue()); 4376 switch (I->getOpcode()) { 4377 case Instruction::Select: { 4378 SelectInst *SI = cast<SelectInst>(I); 4379 Optional<const SCEV *> Res = 4380 compareWithBackedgeCondition(SI->getCondition()); 4381 if (Res.hasValue()) { 4382 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4383 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4384 } 4385 break; 4386 } 4387 default: { 4388 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4389 if (Res.hasValue()) 4390 Result = Res.getValue(); 4391 break; 4392 } 4393 } 4394 } 4395 return Result; 4396 } 4397 4398 private: 4399 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4400 bool IsPosBECond, ScalarEvolution &SE) 4401 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4402 IsPositiveBECond(IsPosBECond) {} 4403 4404 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4405 4406 const Loop *L; 4407 /// Loop back condition. 4408 Value *BackedgeCond = nullptr; 4409 /// Set to true if loop back is on positive branch condition. 4410 bool IsPositiveBECond; 4411 }; 4412 4413 Optional<const SCEV *> 4414 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4415 4416 // If value matches the backedge condition for loop latch, 4417 // then return a constant evolution node based on loopback 4418 // branch taken. 4419 if (BackedgeCond == IC) 4420 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4421 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4422 return None; 4423 } 4424 4425 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4426 public: 4427 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4428 ScalarEvolution &SE) { 4429 SCEVShiftRewriter Rewriter(L, SE); 4430 const SCEV *Result = Rewriter.visit(S); 4431 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4432 } 4433 4434 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4435 // Only allow AddRecExprs for this loop. 4436 if (!SE.isLoopInvariant(Expr, L)) 4437 Valid = false; 4438 return Expr; 4439 } 4440 4441 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4442 if (Expr->getLoop() == L && Expr->isAffine()) 4443 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4444 Valid = false; 4445 return Expr; 4446 } 4447 4448 bool isValid() { return Valid; } 4449 4450 private: 4451 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4452 : SCEVRewriteVisitor(SE), L(L) {} 4453 4454 const Loop *L; 4455 bool Valid = true; 4456 }; 4457 4458 } // end anonymous namespace 4459 4460 SCEV::NoWrapFlags 4461 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4462 if (!AR->isAffine()) 4463 return SCEV::FlagAnyWrap; 4464 4465 using OBO = OverflowingBinaryOperator; 4466 4467 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4468 4469 if (!AR->hasNoSignedWrap()) { 4470 ConstantRange AddRecRange = getSignedRange(AR); 4471 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4472 4473 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4474 Instruction::Add, IncRange, OBO::NoSignedWrap); 4475 if (NSWRegion.contains(AddRecRange)) 4476 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4477 } 4478 4479 if (!AR->hasNoUnsignedWrap()) { 4480 ConstantRange AddRecRange = getUnsignedRange(AR); 4481 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4482 4483 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4484 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4485 if (NUWRegion.contains(AddRecRange)) 4486 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4487 } 4488 4489 return Result; 4490 } 4491 4492 namespace { 4493 4494 /// Represents an abstract binary operation. This may exist as a 4495 /// normal instruction or constant expression, or may have been 4496 /// derived from an expression tree. 4497 struct BinaryOp { 4498 unsigned Opcode; 4499 Value *LHS; 4500 Value *RHS; 4501 bool IsNSW = false; 4502 bool IsNUW = false; 4503 4504 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4505 /// constant expression. 4506 Operator *Op = nullptr; 4507 4508 explicit BinaryOp(Operator *Op) 4509 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4510 Op(Op) { 4511 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4512 IsNSW = OBO->hasNoSignedWrap(); 4513 IsNUW = OBO->hasNoUnsignedWrap(); 4514 } 4515 } 4516 4517 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4518 bool IsNUW = false) 4519 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4520 }; 4521 4522 } // end anonymous namespace 4523 4524 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4525 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4526 auto *Op = dyn_cast<Operator>(V); 4527 if (!Op) 4528 return None; 4529 4530 // Implementation detail: all the cleverness here should happen without 4531 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4532 // SCEV expressions when possible, and we should not break that. 4533 4534 switch (Op->getOpcode()) { 4535 case Instruction::Add: 4536 case Instruction::Sub: 4537 case Instruction::Mul: 4538 case Instruction::UDiv: 4539 case Instruction::URem: 4540 case Instruction::And: 4541 case Instruction::Or: 4542 case Instruction::AShr: 4543 case Instruction::Shl: 4544 return BinaryOp(Op); 4545 4546 case Instruction::Xor: 4547 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4548 // If the RHS of the xor is a signmask, then this is just an add. 4549 // Instcombine turns add of signmask into xor as a strength reduction step. 4550 if (RHSC->getValue().isSignMask()) 4551 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4552 return BinaryOp(Op); 4553 4554 case Instruction::LShr: 4555 // Turn logical shift right of a constant into a unsigned divide. 4556 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4557 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4558 4559 // If the shift count is not less than the bitwidth, the result of 4560 // the shift is undefined. Don't try to analyze it, because the 4561 // resolution chosen here may differ from the resolution chosen in 4562 // other parts of the compiler. 4563 if (SA->getValue().ult(BitWidth)) { 4564 Constant *X = 4565 ConstantInt::get(SA->getContext(), 4566 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4567 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4568 } 4569 } 4570 return BinaryOp(Op); 4571 4572 case Instruction::ExtractValue: { 4573 auto *EVI = cast<ExtractValueInst>(Op); 4574 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4575 break; 4576 4577 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4578 if (!WO) 4579 break; 4580 4581 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4582 bool Signed = WO->isSigned(); 4583 // TODO: Should add nuw/nsw flags for mul as well. 4584 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4585 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4586 4587 // Now that we know that all uses of the arithmetic-result component of 4588 // CI are guarded by the overflow check, we can go ahead and pretend 4589 // that the arithmetic is non-overflowing. 4590 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4591 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4592 } 4593 4594 default: 4595 break; 4596 } 4597 4598 return None; 4599 } 4600 4601 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4602 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4603 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4604 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4605 /// follows one of the following patterns: 4606 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4607 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4608 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4609 /// we return the type of the truncation operation, and indicate whether the 4610 /// truncated type should be treated as signed/unsigned by setting 4611 /// \p Signed to true/false, respectively. 4612 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4613 bool &Signed, ScalarEvolution &SE) { 4614 // The case where Op == SymbolicPHI (that is, with no type conversions on 4615 // the way) is handled by the regular add recurrence creating logic and 4616 // would have already been triggered in createAddRecForPHI. Reaching it here 4617 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4618 // because one of the other operands of the SCEVAddExpr updating this PHI is 4619 // not invariant). 4620 // 4621 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4622 // this case predicates that allow us to prove that Op == SymbolicPHI will 4623 // be added. 4624 if (Op == SymbolicPHI) 4625 return nullptr; 4626 4627 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4628 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4629 if (SourceBits != NewBits) 4630 return nullptr; 4631 4632 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4633 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4634 if (!SExt && !ZExt) 4635 return nullptr; 4636 const SCEVTruncateExpr *Trunc = 4637 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4638 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4639 if (!Trunc) 4640 return nullptr; 4641 const SCEV *X = Trunc->getOperand(); 4642 if (X != SymbolicPHI) 4643 return nullptr; 4644 Signed = SExt != nullptr; 4645 return Trunc->getType(); 4646 } 4647 4648 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4649 if (!PN->getType()->isIntegerTy()) 4650 return nullptr; 4651 const Loop *L = LI.getLoopFor(PN->getParent()); 4652 if (!L || L->getHeader() != PN->getParent()) 4653 return nullptr; 4654 return L; 4655 } 4656 4657 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4658 // computation that updates the phi follows the following pattern: 4659 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4660 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4661 // If so, try to see if it can be rewritten as an AddRecExpr under some 4662 // Predicates. If successful, return them as a pair. Also cache the results 4663 // of the analysis. 4664 // 4665 // Example usage scenario: 4666 // Say the Rewriter is called for the following SCEV: 4667 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4668 // where: 4669 // %X = phi i64 (%Start, %BEValue) 4670 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4671 // and call this function with %SymbolicPHI = %X. 4672 // 4673 // The analysis will find that the value coming around the backedge has 4674 // the following SCEV: 4675 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4676 // Upon concluding that this matches the desired pattern, the function 4677 // will return the pair {NewAddRec, SmallPredsVec} where: 4678 // NewAddRec = {%Start,+,%Step} 4679 // SmallPredsVec = {P1, P2, P3} as follows: 4680 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4681 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4682 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4683 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4684 // under the predicates {P1,P2,P3}. 4685 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4686 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4687 // 4688 // TODO's: 4689 // 4690 // 1) Extend the Induction descriptor to also support inductions that involve 4691 // casts: When needed (namely, when we are called in the context of the 4692 // vectorizer induction analysis), a Set of cast instructions will be 4693 // populated by this method, and provided back to isInductionPHI. This is 4694 // needed to allow the vectorizer to properly record them to be ignored by 4695 // the cost model and to avoid vectorizing them (otherwise these casts, 4696 // which are redundant under the runtime overflow checks, will be 4697 // vectorized, which can be costly). 4698 // 4699 // 2) Support additional induction/PHISCEV patterns: We also want to support 4700 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4701 // after the induction update operation (the induction increment): 4702 // 4703 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4704 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4705 // 4706 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4707 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4708 // 4709 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4710 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4711 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4712 SmallVector<const SCEVPredicate *, 3> Predicates; 4713 4714 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4715 // return an AddRec expression under some predicate. 4716 4717 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4718 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4719 assert(L && "Expecting an integer loop header phi"); 4720 4721 // The loop may have multiple entrances or multiple exits; we can analyze 4722 // this phi as an addrec if it has a unique entry value and a unique 4723 // backedge value. 4724 Value *BEValueV = nullptr, *StartValueV = nullptr; 4725 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4726 Value *V = PN->getIncomingValue(i); 4727 if (L->contains(PN->getIncomingBlock(i))) { 4728 if (!BEValueV) { 4729 BEValueV = V; 4730 } else if (BEValueV != V) { 4731 BEValueV = nullptr; 4732 break; 4733 } 4734 } else if (!StartValueV) { 4735 StartValueV = V; 4736 } else if (StartValueV != V) { 4737 StartValueV = nullptr; 4738 break; 4739 } 4740 } 4741 if (!BEValueV || !StartValueV) 4742 return None; 4743 4744 const SCEV *BEValue = getSCEV(BEValueV); 4745 4746 // If the value coming around the backedge is an add with the symbolic 4747 // value we just inserted, possibly with casts that we can ignore under 4748 // an appropriate runtime guard, then we found a simple induction variable! 4749 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4750 if (!Add) 4751 return None; 4752 4753 // If there is a single occurrence of the symbolic value, possibly 4754 // casted, replace it with a recurrence. 4755 unsigned FoundIndex = Add->getNumOperands(); 4756 Type *TruncTy = nullptr; 4757 bool Signed; 4758 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4759 if ((TruncTy = 4760 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4761 if (FoundIndex == e) { 4762 FoundIndex = i; 4763 break; 4764 } 4765 4766 if (FoundIndex == Add->getNumOperands()) 4767 return None; 4768 4769 // Create an add with everything but the specified operand. 4770 SmallVector<const SCEV *, 8> Ops; 4771 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4772 if (i != FoundIndex) 4773 Ops.push_back(Add->getOperand(i)); 4774 const SCEV *Accum = getAddExpr(Ops); 4775 4776 // The runtime checks will not be valid if the step amount is 4777 // varying inside the loop. 4778 if (!isLoopInvariant(Accum, L)) 4779 return None; 4780 4781 // *** Part2: Create the predicates 4782 4783 // Analysis was successful: we have a phi-with-cast pattern for which we 4784 // can return an AddRec expression under the following predicates: 4785 // 4786 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4787 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4788 // P2: An Equal predicate that guarantees that 4789 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4790 // P3: An Equal predicate that guarantees that 4791 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4792 // 4793 // As we next prove, the above predicates guarantee that: 4794 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4795 // 4796 // 4797 // More formally, we want to prove that: 4798 // Expr(i+1) = Start + (i+1) * Accum 4799 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4800 // 4801 // Given that: 4802 // 1) Expr(0) = Start 4803 // 2) Expr(1) = Start + Accum 4804 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4805 // 3) Induction hypothesis (step i): 4806 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4807 // 4808 // Proof: 4809 // Expr(i+1) = 4810 // = Start + (i+1)*Accum 4811 // = (Start + i*Accum) + Accum 4812 // = Expr(i) + Accum 4813 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4814 // :: from step i 4815 // 4816 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4817 // 4818 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4819 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4820 // + Accum :: from P3 4821 // 4822 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4823 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4824 // 4825 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4826 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4827 // 4828 // By induction, the same applies to all iterations 1<=i<n: 4829 // 4830 4831 // Create a truncated addrec for which we will add a no overflow check (P1). 4832 const SCEV *StartVal = getSCEV(StartValueV); 4833 const SCEV *PHISCEV = 4834 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4835 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4836 4837 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4838 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4839 // will be constant. 4840 // 4841 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4842 // add P1. 4843 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4844 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4845 Signed ? SCEVWrapPredicate::IncrementNSSW 4846 : SCEVWrapPredicate::IncrementNUSW; 4847 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4848 Predicates.push_back(AddRecPred); 4849 } 4850 4851 // Create the Equal Predicates P2,P3: 4852 4853 // It is possible that the predicates P2 and/or P3 are computable at 4854 // compile time due to StartVal and/or Accum being constants. 4855 // If either one is, then we can check that now and escape if either P2 4856 // or P3 is false. 4857 4858 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4859 // for each of StartVal and Accum 4860 auto getExtendedExpr = [&](const SCEV *Expr, 4861 bool CreateSignExtend) -> const SCEV * { 4862 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4863 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4864 const SCEV *ExtendedExpr = 4865 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4866 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4867 return ExtendedExpr; 4868 }; 4869 4870 // Given: 4871 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4872 // = getExtendedExpr(Expr) 4873 // Determine whether the predicate P: Expr == ExtendedExpr 4874 // is known to be false at compile time 4875 auto PredIsKnownFalse = [&](const SCEV *Expr, 4876 const SCEV *ExtendedExpr) -> bool { 4877 return Expr != ExtendedExpr && 4878 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4879 }; 4880 4881 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4882 if (PredIsKnownFalse(StartVal, StartExtended)) { 4883 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4884 return None; 4885 } 4886 4887 // The Step is always Signed (because the overflow checks are either 4888 // NSSW or NUSW) 4889 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4890 if (PredIsKnownFalse(Accum, AccumExtended)) { 4891 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4892 return None; 4893 } 4894 4895 auto AppendPredicate = [&](const SCEV *Expr, 4896 const SCEV *ExtendedExpr) -> void { 4897 if (Expr != ExtendedExpr && 4898 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4899 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4900 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4901 Predicates.push_back(Pred); 4902 } 4903 }; 4904 4905 AppendPredicate(StartVal, StartExtended); 4906 AppendPredicate(Accum, AccumExtended); 4907 4908 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4909 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4910 // into NewAR if it will also add the runtime overflow checks specified in 4911 // Predicates. 4912 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4913 4914 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4915 std::make_pair(NewAR, Predicates); 4916 // Remember the result of the analysis for this SCEV at this locayyytion. 4917 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4918 return PredRewrite; 4919 } 4920 4921 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4922 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4923 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4924 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4925 if (!L) 4926 return None; 4927 4928 // Check to see if we already analyzed this PHI. 4929 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4930 if (I != PredicatedSCEVRewrites.end()) { 4931 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4932 I->second; 4933 // Analysis was done before and failed to create an AddRec: 4934 if (Rewrite.first == SymbolicPHI) 4935 return None; 4936 // Analysis was done before and succeeded to create an AddRec under 4937 // a predicate: 4938 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4939 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4940 return Rewrite; 4941 } 4942 4943 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4944 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4945 4946 // Record in the cache that the analysis failed 4947 if (!Rewrite) { 4948 SmallVector<const SCEVPredicate *, 3> Predicates; 4949 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4950 return None; 4951 } 4952 4953 return Rewrite; 4954 } 4955 4956 // FIXME: This utility is currently required because the Rewriter currently 4957 // does not rewrite this expression: 4958 // {0, +, (sext ix (trunc iy to ix) to iy)} 4959 // into {0, +, %step}, 4960 // even when the following Equal predicate exists: 4961 // "%step == (sext ix (trunc iy to ix) to iy)". 4962 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4963 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4964 if (AR1 == AR2) 4965 return true; 4966 4967 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4968 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4969 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4970 return false; 4971 return true; 4972 }; 4973 4974 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4975 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4976 return false; 4977 return true; 4978 } 4979 4980 /// A helper function for createAddRecFromPHI to handle simple cases. 4981 /// 4982 /// This function tries to find an AddRec expression for the simplest (yet most 4983 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4984 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4985 /// technique for finding the AddRec expression. 4986 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4987 Value *BEValueV, 4988 Value *StartValueV) { 4989 const Loop *L = LI.getLoopFor(PN->getParent()); 4990 assert(L && L->getHeader() == PN->getParent()); 4991 assert(BEValueV && StartValueV); 4992 4993 auto BO = MatchBinaryOp(BEValueV, DT); 4994 if (!BO) 4995 return nullptr; 4996 4997 if (BO->Opcode != Instruction::Add) 4998 return nullptr; 4999 5000 const SCEV *Accum = nullptr; 5001 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5002 Accum = getSCEV(BO->RHS); 5003 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5004 Accum = getSCEV(BO->LHS); 5005 5006 if (!Accum) 5007 return nullptr; 5008 5009 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5010 if (BO->IsNUW) 5011 Flags = setFlags(Flags, SCEV::FlagNUW); 5012 if (BO->IsNSW) 5013 Flags = setFlags(Flags, SCEV::FlagNSW); 5014 5015 const SCEV *StartVal = getSCEV(StartValueV); 5016 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5017 5018 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5019 5020 // We can add Flags to the post-inc expression only if we 5021 // know that it is *undefined behavior* for BEValueV to 5022 // overflow. 5023 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5024 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5025 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5026 5027 return PHISCEV; 5028 } 5029 5030 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5031 const Loop *L = LI.getLoopFor(PN->getParent()); 5032 if (!L || L->getHeader() != PN->getParent()) 5033 return nullptr; 5034 5035 // The loop may have multiple entrances or multiple exits; we can analyze 5036 // this phi as an addrec if it has a unique entry value and a unique 5037 // backedge value. 5038 Value *BEValueV = nullptr, *StartValueV = nullptr; 5039 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5040 Value *V = PN->getIncomingValue(i); 5041 if (L->contains(PN->getIncomingBlock(i))) { 5042 if (!BEValueV) { 5043 BEValueV = V; 5044 } else if (BEValueV != V) { 5045 BEValueV = nullptr; 5046 break; 5047 } 5048 } else if (!StartValueV) { 5049 StartValueV = V; 5050 } else if (StartValueV != V) { 5051 StartValueV = nullptr; 5052 break; 5053 } 5054 } 5055 if (!BEValueV || !StartValueV) 5056 return nullptr; 5057 5058 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5059 "PHI node already processed?"); 5060 5061 // First, try to find AddRec expression without creating a fictituos symbolic 5062 // value for PN. 5063 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5064 return S; 5065 5066 // Handle PHI node value symbolically. 5067 const SCEV *SymbolicName = getUnknown(PN); 5068 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5069 5070 // Using this symbolic name for the PHI, analyze the value coming around 5071 // the back-edge. 5072 const SCEV *BEValue = getSCEV(BEValueV); 5073 5074 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5075 // has a special value for the first iteration of the loop. 5076 5077 // If the value coming around the backedge is an add with the symbolic 5078 // value we just inserted, then we found a simple induction variable! 5079 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5080 // If there is a single occurrence of the symbolic value, replace it 5081 // with a recurrence. 5082 unsigned FoundIndex = Add->getNumOperands(); 5083 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5084 if (Add->getOperand(i) == SymbolicName) 5085 if (FoundIndex == e) { 5086 FoundIndex = i; 5087 break; 5088 } 5089 5090 if (FoundIndex != Add->getNumOperands()) { 5091 // Create an add with everything but the specified operand. 5092 SmallVector<const SCEV *, 8> Ops; 5093 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5094 if (i != FoundIndex) 5095 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5096 L, *this)); 5097 const SCEV *Accum = getAddExpr(Ops); 5098 5099 // This is not a valid addrec if the step amount is varying each 5100 // loop iteration, but is not itself an addrec in this loop. 5101 if (isLoopInvariant(Accum, L) || 5102 (isa<SCEVAddRecExpr>(Accum) && 5103 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5104 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5105 5106 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5107 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5108 if (BO->IsNUW) 5109 Flags = setFlags(Flags, SCEV::FlagNUW); 5110 if (BO->IsNSW) 5111 Flags = setFlags(Flags, SCEV::FlagNSW); 5112 } 5113 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5114 // If the increment is an inbounds GEP, then we know the address 5115 // space cannot be wrapped around. We cannot make any guarantee 5116 // about signed or unsigned overflow because pointers are 5117 // unsigned but we may have a negative index from the base 5118 // pointer. We can guarantee that no unsigned wrap occurs if the 5119 // indices form a positive value. 5120 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5121 Flags = setFlags(Flags, SCEV::FlagNW); 5122 5123 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5124 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5125 Flags = setFlags(Flags, SCEV::FlagNUW); 5126 } 5127 5128 // We cannot transfer nuw and nsw flags from subtraction 5129 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5130 // for instance. 5131 } 5132 5133 const SCEV *StartVal = getSCEV(StartValueV); 5134 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5135 5136 // Okay, for the entire analysis of this edge we assumed the PHI 5137 // to be symbolic. We now need to go back and purge all of the 5138 // entries for the scalars that use the symbolic expression. 5139 forgetSymbolicName(PN, SymbolicName); 5140 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5141 5142 // We can add Flags to the post-inc expression only if we 5143 // know that it is *undefined behavior* for BEValueV to 5144 // overflow. 5145 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5146 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5147 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5148 5149 return PHISCEV; 5150 } 5151 } 5152 } else { 5153 // Otherwise, this could be a loop like this: 5154 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5155 // In this case, j = {1,+,1} and BEValue is j. 5156 // Because the other in-value of i (0) fits the evolution of BEValue 5157 // i really is an addrec evolution. 5158 // 5159 // We can generalize this saying that i is the shifted value of BEValue 5160 // by one iteration: 5161 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5162 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5163 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5164 if (Shifted != getCouldNotCompute() && 5165 Start != getCouldNotCompute()) { 5166 const SCEV *StartVal = getSCEV(StartValueV); 5167 if (Start == StartVal) { 5168 // Okay, for the entire analysis of this edge we assumed the PHI 5169 // to be symbolic. We now need to go back and purge all of the 5170 // entries for the scalars that use the symbolic expression. 5171 forgetSymbolicName(PN, SymbolicName); 5172 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5173 return Shifted; 5174 } 5175 } 5176 } 5177 5178 // Remove the temporary PHI node SCEV that has been inserted while intending 5179 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5180 // as it will prevent later (possibly simpler) SCEV expressions to be added 5181 // to the ValueExprMap. 5182 eraseValueFromMap(PN); 5183 5184 return nullptr; 5185 } 5186 5187 // Checks if the SCEV S is available at BB. S is considered available at BB 5188 // if S can be materialized at BB without introducing a fault. 5189 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5190 BasicBlock *BB) { 5191 struct CheckAvailable { 5192 bool TraversalDone = false; 5193 bool Available = true; 5194 5195 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5196 BasicBlock *BB = nullptr; 5197 DominatorTree &DT; 5198 5199 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5200 : L(L), BB(BB), DT(DT) {} 5201 5202 bool setUnavailable() { 5203 TraversalDone = true; 5204 Available = false; 5205 return false; 5206 } 5207 5208 bool follow(const SCEV *S) { 5209 switch (S->getSCEVType()) { 5210 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5211 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5212 // These expressions are available if their operand(s) is/are. 5213 return true; 5214 5215 case scAddRecExpr: { 5216 // We allow add recurrences that are on the loop BB is in, or some 5217 // outer loop. This guarantees availability because the value of the 5218 // add recurrence at BB is simply the "current" value of the induction 5219 // variable. We can relax this in the future; for instance an add 5220 // recurrence on a sibling dominating loop is also available at BB. 5221 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5222 if (L && (ARLoop == L || ARLoop->contains(L))) 5223 return true; 5224 5225 return setUnavailable(); 5226 } 5227 5228 case scUnknown: { 5229 // For SCEVUnknown, we check for simple dominance. 5230 const auto *SU = cast<SCEVUnknown>(S); 5231 Value *V = SU->getValue(); 5232 5233 if (isa<Argument>(V)) 5234 return false; 5235 5236 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5237 return false; 5238 5239 return setUnavailable(); 5240 } 5241 5242 case scUDivExpr: 5243 case scCouldNotCompute: 5244 // We do not try to smart about these at all. 5245 return setUnavailable(); 5246 } 5247 llvm_unreachable("switch should be fully covered!"); 5248 } 5249 5250 bool isDone() { return TraversalDone; } 5251 }; 5252 5253 CheckAvailable CA(L, BB, DT); 5254 SCEVTraversal<CheckAvailable> ST(CA); 5255 5256 ST.visitAll(S); 5257 return CA.Available; 5258 } 5259 5260 // Try to match a control flow sequence that branches out at BI and merges back 5261 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5262 // match. 5263 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5264 Value *&C, Value *&LHS, Value *&RHS) { 5265 C = BI->getCondition(); 5266 5267 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5268 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5269 5270 if (!LeftEdge.isSingleEdge()) 5271 return false; 5272 5273 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5274 5275 Use &LeftUse = Merge->getOperandUse(0); 5276 Use &RightUse = Merge->getOperandUse(1); 5277 5278 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5279 LHS = LeftUse; 5280 RHS = RightUse; 5281 return true; 5282 } 5283 5284 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5285 LHS = RightUse; 5286 RHS = LeftUse; 5287 return true; 5288 } 5289 5290 return false; 5291 } 5292 5293 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5294 auto IsReachable = 5295 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5296 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5297 const Loop *L = LI.getLoopFor(PN->getParent()); 5298 5299 // We don't want to break LCSSA, even in a SCEV expression tree. 5300 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5301 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5302 return nullptr; 5303 5304 // Try to match 5305 // 5306 // br %cond, label %left, label %right 5307 // left: 5308 // br label %merge 5309 // right: 5310 // br label %merge 5311 // merge: 5312 // V = phi [ %x, %left ], [ %y, %right ] 5313 // 5314 // as "select %cond, %x, %y" 5315 5316 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5317 assert(IDom && "At least the entry block should dominate PN"); 5318 5319 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5320 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5321 5322 if (BI && BI->isConditional() && 5323 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5324 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5325 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5326 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5327 } 5328 5329 return nullptr; 5330 } 5331 5332 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5333 if (const SCEV *S = createAddRecFromPHI(PN)) 5334 return S; 5335 5336 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5337 return S; 5338 5339 // If the PHI has a single incoming value, follow that value, unless the 5340 // PHI's incoming blocks are in a different loop, in which case doing so 5341 // risks breaking LCSSA form. Instcombine would normally zap these, but 5342 // it doesn't have DominatorTree information, so it may miss cases. 5343 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5344 if (LI.replacementPreservesLCSSAForm(PN, V)) 5345 return getSCEV(V); 5346 5347 // If it's not a loop phi, we can't handle it yet. 5348 return getUnknown(PN); 5349 } 5350 5351 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5352 Value *Cond, 5353 Value *TrueVal, 5354 Value *FalseVal) { 5355 // Handle "constant" branch or select. This can occur for instance when a 5356 // loop pass transforms an inner loop and moves on to process the outer loop. 5357 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5358 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5359 5360 // Try to match some simple smax or umax patterns. 5361 auto *ICI = dyn_cast<ICmpInst>(Cond); 5362 if (!ICI) 5363 return getUnknown(I); 5364 5365 Value *LHS = ICI->getOperand(0); 5366 Value *RHS = ICI->getOperand(1); 5367 5368 switch (ICI->getPredicate()) { 5369 case ICmpInst::ICMP_SLT: 5370 case ICmpInst::ICMP_SLE: 5371 std::swap(LHS, RHS); 5372 LLVM_FALLTHROUGH; 5373 case ICmpInst::ICMP_SGT: 5374 case ICmpInst::ICMP_SGE: 5375 // a >s b ? a+x : b+x -> smax(a, b)+x 5376 // a >s b ? b+x : a+x -> smin(a, b)+x 5377 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5378 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5379 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5380 const SCEV *LA = getSCEV(TrueVal); 5381 const SCEV *RA = getSCEV(FalseVal); 5382 const SCEV *LDiff = getMinusSCEV(LA, LS); 5383 const SCEV *RDiff = getMinusSCEV(RA, RS); 5384 if (LDiff == RDiff) 5385 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5386 LDiff = getMinusSCEV(LA, RS); 5387 RDiff = getMinusSCEV(RA, LS); 5388 if (LDiff == RDiff) 5389 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5390 } 5391 break; 5392 case ICmpInst::ICMP_ULT: 5393 case ICmpInst::ICMP_ULE: 5394 std::swap(LHS, RHS); 5395 LLVM_FALLTHROUGH; 5396 case ICmpInst::ICMP_UGT: 5397 case ICmpInst::ICMP_UGE: 5398 // a >u b ? a+x : b+x -> umax(a, b)+x 5399 // a >u b ? b+x : a+x -> umin(a, b)+x 5400 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5401 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5402 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5403 const SCEV *LA = getSCEV(TrueVal); 5404 const SCEV *RA = getSCEV(FalseVal); 5405 const SCEV *LDiff = getMinusSCEV(LA, LS); 5406 const SCEV *RDiff = getMinusSCEV(RA, RS); 5407 if (LDiff == RDiff) 5408 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5409 LDiff = getMinusSCEV(LA, RS); 5410 RDiff = getMinusSCEV(RA, LS); 5411 if (LDiff == RDiff) 5412 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5413 } 5414 break; 5415 case ICmpInst::ICMP_NE: 5416 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5417 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5418 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5419 const SCEV *One = getOne(I->getType()); 5420 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5421 const SCEV *LA = getSCEV(TrueVal); 5422 const SCEV *RA = getSCEV(FalseVal); 5423 const SCEV *LDiff = getMinusSCEV(LA, LS); 5424 const SCEV *RDiff = getMinusSCEV(RA, One); 5425 if (LDiff == RDiff) 5426 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5427 } 5428 break; 5429 case ICmpInst::ICMP_EQ: 5430 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5431 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5432 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5433 const SCEV *One = getOne(I->getType()); 5434 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5435 const SCEV *LA = getSCEV(TrueVal); 5436 const SCEV *RA = getSCEV(FalseVal); 5437 const SCEV *LDiff = getMinusSCEV(LA, One); 5438 const SCEV *RDiff = getMinusSCEV(RA, LS); 5439 if (LDiff == RDiff) 5440 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5441 } 5442 break; 5443 default: 5444 break; 5445 } 5446 5447 return getUnknown(I); 5448 } 5449 5450 /// Expand GEP instructions into add and multiply operations. This allows them 5451 /// to be analyzed by regular SCEV code. 5452 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5453 // Don't attempt to analyze GEPs over unsized objects. 5454 if (!GEP->getSourceElementType()->isSized()) 5455 return getUnknown(GEP); 5456 5457 SmallVector<const SCEV *, 4> IndexExprs; 5458 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5459 IndexExprs.push_back(getSCEV(*Index)); 5460 return getGEPExpr(GEP, IndexExprs); 5461 } 5462 5463 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5464 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5465 return C->getAPInt().countTrailingZeros(); 5466 5467 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5468 return std::min(GetMinTrailingZeros(T->getOperand()), 5469 (uint32_t)getTypeSizeInBits(T->getType())); 5470 5471 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5472 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5473 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5474 ? getTypeSizeInBits(E->getType()) 5475 : OpRes; 5476 } 5477 5478 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5479 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5480 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5481 ? getTypeSizeInBits(E->getType()) 5482 : OpRes; 5483 } 5484 5485 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5486 // The result is the min of all operands results. 5487 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5488 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5489 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5490 return MinOpRes; 5491 } 5492 5493 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5494 // The result is the sum of all operands results. 5495 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5496 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5497 for (unsigned i = 1, e = M->getNumOperands(); 5498 SumOpRes != BitWidth && i != e; ++i) 5499 SumOpRes = 5500 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5501 return SumOpRes; 5502 } 5503 5504 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5505 // The result is the min of all operands results. 5506 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5507 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5508 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5509 return MinOpRes; 5510 } 5511 5512 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5513 // The result is the min of all operands results. 5514 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5515 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5516 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5517 return MinOpRes; 5518 } 5519 5520 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5521 // The result is the min of all operands results. 5522 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5523 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5524 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5525 return MinOpRes; 5526 } 5527 5528 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5529 // For a SCEVUnknown, ask ValueTracking. 5530 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5531 return Known.countMinTrailingZeros(); 5532 } 5533 5534 // SCEVUDivExpr 5535 return 0; 5536 } 5537 5538 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5539 auto I = MinTrailingZerosCache.find(S); 5540 if (I != MinTrailingZerosCache.end()) 5541 return I->second; 5542 5543 uint32_t Result = GetMinTrailingZerosImpl(S); 5544 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5545 assert(InsertPair.second && "Should insert a new key"); 5546 return InsertPair.first->second; 5547 } 5548 5549 /// Helper method to assign a range to V from metadata present in the IR. 5550 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5551 if (Instruction *I = dyn_cast<Instruction>(V)) 5552 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5553 return getConstantRangeFromMetadata(*MD); 5554 5555 return None; 5556 } 5557 5558 /// Determine the range for a particular SCEV. If SignHint is 5559 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5560 /// with a "cleaner" unsigned (resp. signed) representation. 5561 const ConstantRange & 5562 ScalarEvolution::getRangeRef(const SCEV *S, 5563 ScalarEvolution::RangeSignHint SignHint) { 5564 DenseMap<const SCEV *, ConstantRange> &Cache = 5565 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5566 : SignedRanges; 5567 5568 // See if we've computed this range already. 5569 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5570 if (I != Cache.end()) 5571 return I->second; 5572 5573 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5574 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5575 5576 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5577 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5578 5579 // If the value has known zeros, the maximum value will have those known zeros 5580 // as well. 5581 uint32_t TZ = GetMinTrailingZeros(S); 5582 if (TZ != 0) { 5583 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5584 ConservativeResult = 5585 ConstantRange(APInt::getMinValue(BitWidth), 5586 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5587 else 5588 ConservativeResult = ConstantRange( 5589 APInt::getSignedMinValue(BitWidth), 5590 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5591 } 5592 5593 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5594 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5595 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5596 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5597 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 5598 } 5599 5600 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5601 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5602 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5603 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5604 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 5605 } 5606 5607 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5608 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5609 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5610 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5611 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 5612 } 5613 5614 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5615 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5616 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5617 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5618 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 5619 } 5620 5621 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5622 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5623 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5624 return setRange(UDiv, SignHint, 5625 ConservativeResult.intersectWith(X.udiv(Y))); 5626 } 5627 5628 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5629 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5630 return setRange(ZExt, SignHint, 5631 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 5632 } 5633 5634 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5635 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5636 return setRange(SExt, SignHint, 5637 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 5638 } 5639 5640 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5641 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5642 return setRange(Trunc, SignHint, 5643 ConservativeResult.intersectWith(X.truncate(BitWidth))); 5644 } 5645 5646 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5647 // If there's no unsigned wrap, the value will never be less than its 5648 // initial value. 5649 if (AddRec->hasNoUnsignedWrap()) 5650 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5651 if (!C->getValue()->isZero()) 5652 ConservativeResult = ConservativeResult.intersectWith( 5653 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 5654 5655 // If there's no signed wrap, and all the operands have the same sign or 5656 // zero, the value won't ever change sign. 5657 if (AddRec->hasNoSignedWrap()) { 5658 bool AllNonNeg = true; 5659 bool AllNonPos = true; 5660 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5661 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5662 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5663 } 5664 if (AllNonNeg) 5665 ConservativeResult = ConservativeResult.intersectWith( 5666 ConstantRange(APInt(BitWidth, 0), 5667 APInt::getSignedMinValue(BitWidth))); 5668 else if (AllNonPos) 5669 ConservativeResult = ConservativeResult.intersectWith( 5670 ConstantRange(APInt::getSignedMinValue(BitWidth), 5671 APInt(BitWidth, 1))); 5672 } 5673 5674 // TODO: non-affine addrec 5675 if (AddRec->isAffine()) { 5676 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 5677 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5678 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5679 auto RangeFromAffine = getRangeForAffineAR( 5680 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5681 BitWidth); 5682 if (!RangeFromAffine.isFullSet()) 5683 ConservativeResult = 5684 ConservativeResult.intersectWith(RangeFromAffine); 5685 5686 auto RangeFromFactoring = getRangeViaFactoring( 5687 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5688 BitWidth); 5689 if (!RangeFromFactoring.isFullSet()) 5690 ConservativeResult = 5691 ConservativeResult.intersectWith(RangeFromFactoring); 5692 } 5693 } 5694 5695 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5696 } 5697 5698 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5699 // Check if the IR explicitly contains !range metadata. 5700 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5701 if (MDRange.hasValue()) 5702 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 5703 5704 // Split here to avoid paying the compile-time cost of calling both 5705 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5706 // if needed. 5707 const DataLayout &DL = getDataLayout(); 5708 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5709 // For a SCEVUnknown, ask ValueTracking. 5710 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5711 if (Known.One != ~Known.Zero + 1) 5712 ConservativeResult = 5713 ConservativeResult.intersectWith(ConstantRange(Known.One, 5714 ~Known.Zero + 1)); 5715 } else { 5716 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5717 "generalize as needed!"); 5718 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5719 if (NS > 1) 5720 ConservativeResult = ConservativeResult.intersectWith( 5721 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5722 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 5723 } 5724 5725 // A range of Phi is a subset of union of all ranges of its input. 5726 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5727 // Make sure that we do not run over cycled Phis. 5728 if (PendingPhiRanges.insert(Phi).second) { 5729 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5730 for (auto &Op : Phi->operands()) { 5731 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5732 RangeFromOps = RangeFromOps.unionWith(OpRange); 5733 // No point to continue if we already have a full set. 5734 if (RangeFromOps.isFullSet()) 5735 break; 5736 } 5737 ConservativeResult = ConservativeResult.intersectWith(RangeFromOps); 5738 bool Erased = PendingPhiRanges.erase(Phi); 5739 assert(Erased && "Failed to erase Phi properly?"); 5740 (void) Erased; 5741 } 5742 } 5743 5744 return setRange(U, SignHint, std::move(ConservativeResult)); 5745 } 5746 5747 return setRange(S, SignHint, std::move(ConservativeResult)); 5748 } 5749 5750 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5751 // values that the expression can take. Initially, the expression has a value 5752 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5753 // argument defines if we treat Step as signed or unsigned. 5754 static ConstantRange getRangeForAffineARHelper(APInt Step, 5755 const ConstantRange &StartRange, 5756 const APInt &MaxBECount, 5757 unsigned BitWidth, bool Signed) { 5758 // If either Step or MaxBECount is 0, then the expression won't change, and we 5759 // just need to return the initial range. 5760 if (Step == 0 || MaxBECount == 0) 5761 return StartRange; 5762 5763 // If we don't know anything about the initial value (i.e. StartRange is 5764 // FullRange), then we don't know anything about the final range either. 5765 // Return FullRange. 5766 if (StartRange.isFullSet()) 5767 return ConstantRange::getFull(BitWidth); 5768 5769 // If Step is signed and negative, then we use its absolute value, but we also 5770 // note that we're moving in the opposite direction. 5771 bool Descending = Signed && Step.isNegative(); 5772 5773 if (Signed) 5774 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5775 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5776 // This equations hold true due to the well-defined wrap-around behavior of 5777 // APInt. 5778 Step = Step.abs(); 5779 5780 // Check if Offset is more than full span of BitWidth. If it is, the 5781 // expression is guaranteed to overflow. 5782 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5783 return ConstantRange::getFull(BitWidth); 5784 5785 // Offset is by how much the expression can change. Checks above guarantee no 5786 // overflow here. 5787 APInt Offset = Step * MaxBECount; 5788 5789 // Minimum value of the final range will match the minimal value of StartRange 5790 // if the expression is increasing and will be decreased by Offset otherwise. 5791 // Maximum value of the final range will match the maximal value of StartRange 5792 // if the expression is decreasing and will be increased by Offset otherwise. 5793 APInt StartLower = StartRange.getLower(); 5794 APInt StartUpper = StartRange.getUpper() - 1; 5795 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5796 : (StartUpper + std::move(Offset)); 5797 5798 // It's possible that the new minimum/maximum value will fall into the initial 5799 // range (due to wrap around). This means that the expression can take any 5800 // value in this bitwidth, and we have to return full range. 5801 if (StartRange.contains(MovedBoundary)) 5802 return ConstantRange::getFull(BitWidth); 5803 5804 APInt NewLower = 5805 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5806 APInt NewUpper = 5807 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5808 NewUpper += 1; 5809 5810 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5811 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5812 } 5813 5814 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5815 const SCEV *Step, 5816 const SCEV *MaxBECount, 5817 unsigned BitWidth) { 5818 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5819 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5820 "Precondition!"); 5821 5822 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5823 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5824 5825 // First, consider step signed. 5826 ConstantRange StartSRange = getSignedRange(Start); 5827 ConstantRange StepSRange = getSignedRange(Step); 5828 5829 // If Step can be both positive and negative, we need to find ranges for the 5830 // maximum absolute step values in both directions and union them. 5831 ConstantRange SR = 5832 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5833 MaxBECountValue, BitWidth, /* Signed = */ true); 5834 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5835 StartSRange, MaxBECountValue, 5836 BitWidth, /* Signed = */ true)); 5837 5838 // Next, consider step unsigned. 5839 ConstantRange UR = getRangeForAffineARHelper( 5840 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5841 MaxBECountValue, BitWidth, /* Signed = */ false); 5842 5843 // Finally, intersect signed and unsigned ranges. 5844 return SR.intersectWith(UR); 5845 } 5846 5847 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5848 const SCEV *Step, 5849 const SCEV *MaxBECount, 5850 unsigned BitWidth) { 5851 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5852 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5853 5854 struct SelectPattern { 5855 Value *Condition = nullptr; 5856 APInt TrueValue; 5857 APInt FalseValue; 5858 5859 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5860 const SCEV *S) { 5861 Optional<unsigned> CastOp; 5862 APInt Offset(BitWidth, 0); 5863 5864 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5865 "Should be!"); 5866 5867 // Peel off a constant offset: 5868 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5869 // In the future we could consider being smarter here and handle 5870 // {Start+Step,+,Step} too. 5871 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5872 return; 5873 5874 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5875 S = SA->getOperand(1); 5876 } 5877 5878 // Peel off a cast operation 5879 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5880 CastOp = SCast->getSCEVType(); 5881 S = SCast->getOperand(); 5882 } 5883 5884 using namespace llvm::PatternMatch; 5885 5886 auto *SU = dyn_cast<SCEVUnknown>(S); 5887 const APInt *TrueVal, *FalseVal; 5888 if (!SU || 5889 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5890 m_APInt(FalseVal)))) { 5891 Condition = nullptr; 5892 return; 5893 } 5894 5895 TrueValue = *TrueVal; 5896 FalseValue = *FalseVal; 5897 5898 // Re-apply the cast we peeled off earlier 5899 if (CastOp.hasValue()) 5900 switch (*CastOp) { 5901 default: 5902 llvm_unreachable("Unknown SCEV cast type!"); 5903 5904 case scTruncate: 5905 TrueValue = TrueValue.trunc(BitWidth); 5906 FalseValue = FalseValue.trunc(BitWidth); 5907 break; 5908 case scZeroExtend: 5909 TrueValue = TrueValue.zext(BitWidth); 5910 FalseValue = FalseValue.zext(BitWidth); 5911 break; 5912 case scSignExtend: 5913 TrueValue = TrueValue.sext(BitWidth); 5914 FalseValue = FalseValue.sext(BitWidth); 5915 break; 5916 } 5917 5918 // Re-apply the constant offset we peeled off earlier 5919 TrueValue += Offset; 5920 FalseValue += Offset; 5921 } 5922 5923 bool isRecognized() { return Condition != nullptr; } 5924 }; 5925 5926 SelectPattern StartPattern(*this, BitWidth, Start); 5927 if (!StartPattern.isRecognized()) 5928 return ConstantRange::getFull(BitWidth); 5929 5930 SelectPattern StepPattern(*this, BitWidth, Step); 5931 if (!StepPattern.isRecognized()) 5932 return ConstantRange::getFull(BitWidth); 5933 5934 if (StartPattern.Condition != StepPattern.Condition) { 5935 // We don't handle this case today; but we could, by considering four 5936 // possibilities below instead of two. I'm not sure if there are cases where 5937 // that will help over what getRange already does, though. 5938 return ConstantRange::getFull(BitWidth); 5939 } 5940 5941 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5942 // construct arbitrary general SCEV expressions here. This function is called 5943 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5944 // say) can end up caching a suboptimal value. 5945 5946 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5947 // C2352 and C2512 (otherwise it isn't needed). 5948 5949 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5950 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5951 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5952 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5953 5954 ConstantRange TrueRange = 5955 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5956 ConstantRange FalseRange = 5957 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5958 5959 return TrueRange.unionWith(FalseRange); 5960 } 5961 5962 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5963 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5964 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5965 5966 // Return early if there are no flags to propagate to the SCEV. 5967 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5968 if (BinOp->hasNoUnsignedWrap()) 5969 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5970 if (BinOp->hasNoSignedWrap()) 5971 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5972 if (Flags == SCEV::FlagAnyWrap) 5973 return SCEV::FlagAnyWrap; 5974 5975 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5976 } 5977 5978 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5979 // Here we check that I is in the header of the innermost loop containing I, 5980 // since we only deal with instructions in the loop header. The actual loop we 5981 // need to check later will come from an add recurrence, but getting that 5982 // requires computing the SCEV of the operands, which can be expensive. This 5983 // check we can do cheaply to rule out some cases early. 5984 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5985 if (InnermostContainingLoop == nullptr || 5986 InnermostContainingLoop->getHeader() != I->getParent()) 5987 return false; 5988 5989 // Only proceed if we can prove that I does not yield poison. 5990 if (!programUndefinedIfFullPoison(I)) 5991 return false; 5992 5993 // At this point we know that if I is executed, then it does not wrap 5994 // according to at least one of NSW or NUW. If I is not executed, then we do 5995 // not know if the calculation that I represents would wrap. Multiple 5996 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5997 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5998 // derived from other instructions that map to the same SCEV. We cannot make 5999 // that guarantee for cases where I is not executed. So we need to find the 6000 // loop that I is considered in relation to and prove that I is executed for 6001 // every iteration of that loop. That implies that the value that I 6002 // calculates does not wrap anywhere in the loop, so then we can apply the 6003 // flags to the SCEV. 6004 // 6005 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6006 // from different loops, so that we know which loop to prove that I is 6007 // executed in. 6008 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6009 // I could be an extractvalue from a call to an overflow intrinsic. 6010 // TODO: We can do better here in some cases. 6011 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6012 return false; 6013 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6014 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6015 bool AllOtherOpsLoopInvariant = true; 6016 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6017 ++OtherOpIndex) { 6018 if (OtherOpIndex != OpIndex) { 6019 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6020 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6021 AllOtherOpsLoopInvariant = false; 6022 break; 6023 } 6024 } 6025 } 6026 if (AllOtherOpsLoopInvariant && 6027 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6028 return true; 6029 } 6030 } 6031 return false; 6032 } 6033 6034 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6035 // If we know that \c I can never be poison period, then that's enough. 6036 if (isSCEVExprNeverPoison(I)) 6037 return true; 6038 6039 // For an add recurrence specifically, we assume that infinite loops without 6040 // side effects are undefined behavior, and then reason as follows: 6041 // 6042 // If the add recurrence is poison in any iteration, it is poison on all 6043 // future iterations (since incrementing poison yields poison). If the result 6044 // of the add recurrence is fed into the loop latch condition and the loop 6045 // does not contain any throws or exiting blocks other than the latch, we now 6046 // have the ability to "choose" whether the backedge is taken or not (by 6047 // choosing a sufficiently evil value for the poison feeding into the branch) 6048 // for every iteration including and after the one in which \p I first became 6049 // poison. There are two possibilities (let's call the iteration in which \p 6050 // I first became poison as K): 6051 // 6052 // 1. In the set of iterations including and after K, the loop body executes 6053 // no side effects. In this case executing the backege an infinte number 6054 // of times will yield undefined behavior. 6055 // 6056 // 2. In the set of iterations including and after K, the loop body executes 6057 // at least one side effect. In this case, that specific instance of side 6058 // effect is control dependent on poison, which also yields undefined 6059 // behavior. 6060 6061 auto *ExitingBB = L->getExitingBlock(); 6062 auto *LatchBB = L->getLoopLatch(); 6063 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6064 return false; 6065 6066 SmallPtrSet<const Instruction *, 16> Pushed; 6067 SmallVector<const Instruction *, 8> PoisonStack; 6068 6069 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6070 // things that are known to be fully poison under that assumption go on the 6071 // PoisonStack. 6072 Pushed.insert(I); 6073 PoisonStack.push_back(I); 6074 6075 bool LatchControlDependentOnPoison = false; 6076 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6077 const Instruction *Poison = PoisonStack.pop_back_val(); 6078 6079 for (auto *PoisonUser : Poison->users()) { 6080 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 6081 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6082 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6083 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6084 assert(BI->isConditional() && "Only possibility!"); 6085 if (BI->getParent() == LatchBB) { 6086 LatchControlDependentOnPoison = true; 6087 break; 6088 } 6089 } 6090 } 6091 } 6092 6093 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6094 } 6095 6096 ScalarEvolution::LoopProperties 6097 ScalarEvolution::getLoopProperties(const Loop *L) { 6098 using LoopProperties = ScalarEvolution::LoopProperties; 6099 6100 auto Itr = LoopPropertiesCache.find(L); 6101 if (Itr == LoopPropertiesCache.end()) { 6102 auto HasSideEffects = [](Instruction *I) { 6103 if (auto *SI = dyn_cast<StoreInst>(I)) 6104 return !SI->isSimple(); 6105 6106 return I->mayHaveSideEffects(); 6107 }; 6108 6109 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6110 /*HasNoSideEffects*/ true}; 6111 6112 for (auto *BB : L->getBlocks()) 6113 for (auto &I : *BB) { 6114 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6115 LP.HasNoAbnormalExits = false; 6116 if (HasSideEffects(&I)) 6117 LP.HasNoSideEffects = false; 6118 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6119 break; // We're already as pessimistic as we can get. 6120 } 6121 6122 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6123 assert(InsertPair.second && "We just checked!"); 6124 Itr = InsertPair.first; 6125 } 6126 6127 return Itr->second; 6128 } 6129 6130 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6131 if (!isSCEVable(V->getType())) 6132 return getUnknown(V); 6133 6134 if (Instruction *I = dyn_cast<Instruction>(V)) { 6135 // Don't attempt to analyze instructions in blocks that aren't 6136 // reachable. Such instructions don't matter, and they aren't required 6137 // to obey basic rules for definitions dominating uses which this 6138 // analysis depends on. 6139 if (!DT.isReachableFromEntry(I->getParent())) 6140 return getUnknown(UndefValue::get(V->getType())); 6141 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6142 return getConstant(CI); 6143 else if (isa<ConstantPointerNull>(V)) 6144 return getZero(V->getType()); 6145 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6146 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6147 else if (!isa<ConstantExpr>(V)) 6148 return getUnknown(V); 6149 6150 Operator *U = cast<Operator>(V); 6151 if (auto BO = MatchBinaryOp(U, DT)) { 6152 switch (BO->Opcode) { 6153 case Instruction::Add: { 6154 // The simple thing to do would be to just call getSCEV on both operands 6155 // and call getAddExpr with the result. However if we're looking at a 6156 // bunch of things all added together, this can be quite inefficient, 6157 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6158 // Instead, gather up all the operands and make a single getAddExpr call. 6159 // LLVM IR canonical form means we need only traverse the left operands. 6160 SmallVector<const SCEV *, 4> AddOps; 6161 do { 6162 if (BO->Op) { 6163 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6164 AddOps.push_back(OpSCEV); 6165 break; 6166 } 6167 6168 // If a NUW or NSW flag can be applied to the SCEV for this 6169 // addition, then compute the SCEV for this addition by itself 6170 // with a separate call to getAddExpr. We need to do that 6171 // instead of pushing the operands of the addition onto AddOps, 6172 // since the flags are only known to apply to this particular 6173 // addition - they may not apply to other additions that can be 6174 // formed with operands from AddOps. 6175 const SCEV *RHS = getSCEV(BO->RHS); 6176 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6177 if (Flags != SCEV::FlagAnyWrap) { 6178 const SCEV *LHS = getSCEV(BO->LHS); 6179 if (BO->Opcode == Instruction::Sub) 6180 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6181 else 6182 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6183 break; 6184 } 6185 } 6186 6187 if (BO->Opcode == Instruction::Sub) 6188 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6189 else 6190 AddOps.push_back(getSCEV(BO->RHS)); 6191 6192 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6193 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6194 NewBO->Opcode != Instruction::Sub)) { 6195 AddOps.push_back(getSCEV(BO->LHS)); 6196 break; 6197 } 6198 BO = NewBO; 6199 } while (true); 6200 6201 return getAddExpr(AddOps); 6202 } 6203 6204 case Instruction::Mul: { 6205 SmallVector<const SCEV *, 4> MulOps; 6206 do { 6207 if (BO->Op) { 6208 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6209 MulOps.push_back(OpSCEV); 6210 break; 6211 } 6212 6213 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6214 if (Flags != SCEV::FlagAnyWrap) { 6215 MulOps.push_back( 6216 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6217 break; 6218 } 6219 } 6220 6221 MulOps.push_back(getSCEV(BO->RHS)); 6222 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6223 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6224 MulOps.push_back(getSCEV(BO->LHS)); 6225 break; 6226 } 6227 BO = NewBO; 6228 } while (true); 6229 6230 return getMulExpr(MulOps); 6231 } 6232 case Instruction::UDiv: 6233 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6234 case Instruction::URem: 6235 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6236 case Instruction::Sub: { 6237 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6238 if (BO->Op) 6239 Flags = getNoWrapFlagsFromUB(BO->Op); 6240 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6241 } 6242 case Instruction::And: 6243 // For an expression like x&255 that merely masks off the high bits, 6244 // use zext(trunc(x)) as the SCEV expression. 6245 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6246 if (CI->isZero()) 6247 return getSCEV(BO->RHS); 6248 if (CI->isMinusOne()) 6249 return getSCEV(BO->LHS); 6250 const APInt &A = CI->getValue(); 6251 6252 // Instcombine's ShrinkDemandedConstant may strip bits out of 6253 // constants, obscuring what would otherwise be a low-bits mask. 6254 // Use computeKnownBits to compute what ShrinkDemandedConstant 6255 // knew about to reconstruct a low-bits mask value. 6256 unsigned LZ = A.countLeadingZeros(); 6257 unsigned TZ = A.countTrailingZeros(); 6258 unsigned BitWidth = A.getBitWidth(); 6259 KnownBits Known(BitWidth); 6260 computeKnownBits(BO->LHS, Known, getDataLayout(), 6261 0, &AC, nullptr, &DT); 6262 6263 APInt EffectiveMask = 6264 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6265 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6266 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6267 const SCEV *LHS = getSCEV(BO->LHS); 6268 const SCEV *ShiftedLHS = nullptr; 6269 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6270 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6271 // For an expression like (x * 8) & 8, simplify the multiply. 6272 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6273 unsigned GCD = std::min(MulZeros, TZ); 6274 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6275 SmallVector<const SCEV*, 4> MulOps; 6276 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6277 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6278 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6279 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6280 } 6281 } 6282 if (!ShiftedLHS) 6283 ShiftedLHS = getUDivExpr(LHS, MulCount); 6284 return getMulExpr( 6285 getZeroExtendExpr( 6286 getTruncateExpr(ShiftedLHS, 6287 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6288 BO->LHS->getType()), 6289 MulCount); 6290 } 6291 } 6292 break; 6293 6294 case Instruction::Or: 6295 // If the RHS of the Or is a constant, we may have something like: 6296 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6297 // optimizations will transparently handle this case. 6298 // 6299 // In order for this transformation to be safe, the LHS must be of the 6300 // form X*(2^n) and the Or constant must be less than 2^n. 6301 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6302 const SCEV *LHS = getSCEV(BO->LHS); 6303 const APInt &CIVal = CI->getValue(); 6304 if (GetMinTrailingZeros(LHS) >= 6305 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6306 // Build a plain add SCEV. 6307 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6308 // If the LHS of the add was an addrec and it has no-wrap flags, 6309 // transfer the no-wrap flags, since an or won't introduce a wrap. 6310 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6311 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6312 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6313 OldAR->getNoWrapFlags()); 6314 } 6315 return S; 6316 } 6317 } 6318 break; 6319 6320 case Instruction::Xor: 6321 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6322 // If the RHS of xor is -1, then this is a not operation. 6323 if (CI->isMinusOne()) 6324 return getNotSCEV(getSCEV(BO->LHS)); 6325 6326 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6327 // This is a variant of the check for xor with -1, and it handles 6328 // the case where instcombine has trimmed non-demanded bits out 6329 // of an xor with -1. 6330 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6331 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6332 if (LBO->getOpcode() == Instruction::And && 6333 LCI->getValue() == CI->getValue()) 6334 if (const SCEVZeroExtendExpr *Z = 6335 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6336 Type *UTy = BO->LHS->getType(); 6337 const SCEV *Z0 = Z->getOperand(); 6338 Type *Z0Ty = Z0->getType(); 6339 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6340 6341 // If C is a low-bits mask, the zero extend is serving to 6342 // mask off the high bits. Complement the operand and 6343 // re-apply the zext. 6344 if (CI->getValue().isMask(Z0TySize)) 6345 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6346 6347 // If C is a single bit, it may be in the sign-bit position 6348 // before the zero-extend. In this case, represent the xor 6349 // using an add, which is equivalent, and re-apply the zext. 6350 APInt Trunc = CI->getValue().trunc(Z0TySize); 6351 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6352 Trunc.isSignMask()) 6353 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6354 UTy); 6355 } 6356 } 6357 break; 6358 6359 case Instruction::Shl: 6360 // Turn shift left of a constant amount into a multiply. 6361 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6362 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6363 6364 // If the shift count is not less than the bitwidth, the result of 6365 // the shift is undefined. Don't try to analyze it, because the 6366 // resolution chosen here may differ from the resolution chosen in 6367 // other parts of the compiler. 6368 if (SA->getValue().uge(BitWidth)) 6369 break; 6370 6371 // It is currently not resolved how to interpret NSW for left 6372 // shift by BitWidth - 1, so we avoid applying flags in that 6373 // case. Remove this check (or this comment) once the situation 6374 // is resolved. See 6375 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6376 // and http://reviews.llvm.org/D8890 . 6377 auto Flags = SCEV::FlagAnyWrap; 6378 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6379 Flags = getNoWrapFlagsFromUB(BO->Op); 6380 6381 Constant *X = ConstantInt::get( 6382 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6383 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6384 } 6385 break; 6386 6387 case Instruction::AShr: { 6388 // AShr X, C, where C is a constant. 6389 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6390 if (!CI) 6391 break; 6392 6393 Type *OuterTy = BO->LHS->getType(); 6394 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6395 // If the shift count is not less than the bitwidth, the result of 6396 // the shift is undefined. Don't try to analyze it, because the 6397 // resolution chosen here may differ from the resolution chosen in 6398 // other parts of the compiler. 6399 if (CI->getValue().uge(BitWidth)) 6400 break; 6401 6402 if (CI->isZero()) 6403 return getSCEV(BO->LHS); // shift by zero --> noop 6404 6405 uint64_t AShrAmt = CI->getZExtValue(); 6406 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6407 6408 Operator *L = dyn_cast<Operator>(BO->LHS); 6409 if (L && L->getOpcode() == Instruction::Shl) { 6410 // X = Shl A, n 6411 // Y = AShr X, m 6412 // Both n and m are constant. 6413 6414 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6415 if (L->getOperand(1) == BO->RHS) 6416 // For a two-shift sext-inreg, i.e. n = m, 6417 // use sext(trunc(x)) as the SCEV expression. 6418 return getSignExtendExpr( 6419 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6420 6421 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6422 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6423 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6424 if (ShlAmt > AShrAmt) { 6425 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6426 // expression. We already checked that ShlAmt < BitWidth, so 6427 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6428 // ShlAmt - AShrAmt < Amt. 6429 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6430 ShlAmt - AShrAmt); 6431 return getSignExtendExpr( 6432 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6433 getConstant(Mul)), OuterTy); 6434 } 6435 } 6436 } 6437 break; 6438 } 6439 } 6440 } 6441 6442 switch (U->getOpcode()) { 6443 case Instruction::Trunc: 6444 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6445 6446 case Instruction::ZExt: 6447 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6448 6449 case Instruction::SExt: 6450 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6451 // The NSW flag of a subtract does not always survive the conversion to 6452 // A + (-1)*B. By pushing sign extension onto its operands we are much 6453 // more likely to preserve NSW and allow later AddRec optimisations. 6454 // 6455 // NOTE: This is effectively duplicating this logic from getSignExtend: 6456 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6457 // but by that point the NSW information has potentially been lost. 6458 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6459 Type *Ty = U->getType(); 6460 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6461 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6462 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6463 } 6464 } 6465 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6466 6467 case Instruction::BitCast: 6468 // BitCasts are no-op casts so we just eliminate the cast. 6469 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6470 return getSCEV(U->getOperand(0)); 6471 break; 6472 6473 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6474 // lead to pointer expressions which cannot safely be expanded to GEPs, 6475 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6476 // simplifying integer expressions. 6477 6478 case Instruction::GetElementPtr: 6479 return createNodeForGEP(cast<GEPOperator>(U)); 6480 6481 case Instruction::PHI: 6482 return createNodeForPHI(cast<PHINode>(U)); 6483 6484 case Instruction::Select: 6485 // U can also be a select constant expr, which let fall through. Since 6486 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6487 // constant expressions cannot have instructions as operands, we'd have 6488 // returned getUnknown for a select constant expressions anyway. 6489 if (isa<Instruction>(U)) 6490 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6491 U->getOperand(1), U->getOperand(2)); 6492 break; 6493 6494 case Instruction::Call: 6495 case Instruction::Invoke: 6496 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6497 return getSCEV(RV); 6498 break; 6499 } 6500 6501 return getUnknown(V); 6502 } 6503 6504 //===----------------------------------------------------------------------===// 6505 // Iteration Count Computation Code 6506 // 6507 6508 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6509 if (!ExitCount) 6510 return 0; 6511 6512 ConstantInt *ExitConst = ExitCount->getValue(); 6513 6514 // Guard against huge trip counts. 6515 if (ExitConst->getValue().getActiveBits() > 32) 6516 return 0; 6517 6518 // In case of integer overflow, this returns 0, which is correct. 6519 return ((unsigned)ExitConst->getZExtValue()) + 1; 6520 } 6521 6522 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6523 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6524 return getSmallConstantTripCount(L, ExitingBB); 6525 6526 // No trip count information for multiple exits. 6527 return 0; 6528 } 6529 6530 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6531 BasicBlock *ExitingBlock) { 6532 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6533 assert(L->isLoopExiting(ExitingBlock) && 6534 "Exiting block must actually branch out of the loop!"); 6535 const SCEVConstant *ExitCount = 6536 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6537 return getConstantTripCount(ExitCount); 6538 } 6539 6540 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6541 const auto *MaxExitCount = 6542 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 6543 return getConstantTripCount(MaxExitCount); 6544 } 6545 6546 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6547 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6548 return getSmallConstantTripMultiple(L, ExitingBB); 6549 6550 // No trip multiple information for multiple exits. 6551 return 0; 6552 } 6553 6554 /// Returns the largest constant divisor of the trip count of this loop as a 6555 /// normal unsigned value, if possible. This means that the actual trip count is 6556 /// always a multiple of the returned value (don't forget the trip count could 6557 /// very well be zero as well!). 6558 /// 6559 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6560 /// multiple of a constant (which is also the case if the trip count is simply 6561 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6562 /// if the trip count is very large (>= 2^32). 6563 /// 6564 /// As explained in the comments for getSmallConstantTripCount, this assumes 6565 /// that control exits the loop via ExitingBlock. 6566 unsigned 6567 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6568 BasicBlock *ExitingBlock) { 6569 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6570 assert(L->isLoopExiting(ExitingBlock) && 6571 "Exiting block must actually branch out of the loop!"); 6572 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6573 if (ExitCount == getCouldNotCompute()) 6574 return 1; 6575 6576 // Get the trip count from the BE count by adding 1. 6577 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6578 6579 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6580 if (!TC) 6581 // Attempt to factor more general cases. Returns the greatest power of 6582 // two divisor. If overflow happens, the trip count expression is still 6583 // divisible by the greatest power of 2 divisor returned. 6584 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6585 6586 ConstantInt *Result = TC->getValue(); 6587 6588 // Guard against huge trip counts (this requires checking 6589 // for zero to handle the case where the trip count == -1 and the 6590 // addition wraps). 6591 if (!Result || Result->getValue().getActiveBits() > 32 || 6592 Result->getValue().getActiveBits() == 0) 6593 return 1; 6594 6595 return (unsigned)Result->getZExtValue(); 6596 } 6597 6598 /// Get the expression for the number of loop iterations for which this loop is 6599 /// guaranteed not to exit via ExitingBlock. Otherwise return 6600 /// SCEVCouldNotCompute. 6601 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6602 BasicBlock *ExitingBlock) { 6603 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6604 } 6605 6606 const SCEV * 6607 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6608 SCEVUnionPredicate &Preds) { 6609 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6610 } 6611 6612 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6613 return getBackedgeTakenInfo(L).getExact(L, this); 6614 } 6615 6616 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6617 /// known never to be less than the actual backedge taken count. 6618 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 6619 return getBackedgeTakenInfo(L).getMax(this); 6620 } 6621 6622 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6623 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6624 } 6625 6626 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6627 static void 6628 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6629 BasicBlock *Header = L->getHeader(); 6630 6631 // Push all Loop-header PHIs onto the Worklist stack. 6632 for (PHINode &PN : Header->phis()) 6633 Worklist.push_back(&PN); 6634 } 6635 6636 const ScalarEvolution::BackedgeTakenInfo & 6637 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6638 auto &BTI = getBackedgeTakenInfo(L); 6639 if (BTI.hasFullInfo()) 6640 return BTI; 6641 6642 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6643 6644 if (!Pair.second) 6645 return Pair.first->second; 6646 6647 BackedgeTakenInfo Result = 6648 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6649 6650 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6651 } 6652 6653 const ScalarEvolution::BackedgeTakenInfo & 6654 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6655 // Initially insert an invalid entry for this loop. If the insertion 6656 // succeeds, proceed to actually compute a backedge-taken count and 6657 // update the value. The temporary CouldNotCompute value tells SCEV 6658 // code elsewhere that it shouldn't attempt to request a new 6659 // backedge-taken count, which could result in infinite recursion. 6660 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6661 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6662 if (!Pair.second) 6663 return Pair.first->second; 6664 6665 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6666 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6667 // must be cleared in this scope. 6668 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6669 6670 // In product build, there are no usage of statistic. 6671 (void)NumTripCountsComputed; 6672 (void)NumTripCountsNotComputed; 6673 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6674 const SCEV *BEExact = Result.getExact(L, this); 6675 if (BEExact != getCouldNotCompute()) { 6676 assert(isLoopInvariant(BEExact, L) && 6677 isLoopInvariant(Result.getMax(this), L) && 6678 "Computed backedge-taken count isn't loop invariant for loop!"); 6679 ++NumTripCountsComputed; 6680 } 6681 else if (Result.getMax(this) == getCouldNotCompute() && 6682 isa<PHINode>(L->getHeader()->begin())) { 6683 // Only count loops that have phi nodes as not being computable. 6684 ++NumTripCountsNotComputed; 6685 } 6686 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6687 6688 // Now that we know more about the trip count for this loop, forget any 6689 // existing SCEV values for PHI nodes in this loop since they are only 6690 // conservative estimates made without the benefit of trip count 6691 // information. This is similar to the code in forgetLoop, except that 6692 // it handles SCEVUnknown PHI nodes specially. 6693 if (Result.hasAnyInfo()) { 6694 SmallVector<Instruction *, 16> Worklist; 6695 PushLoopPHIs(L, Worklist); 6696 6697 SmallPtrSet<Instruction *, 8> Discovered; 6698 while (!Worklist.empty()) { 6699 Instruction *I = Worklist.pop_back_val(); 6700 6701 ValueExprMapType::iterator It = 6702 ValueExprMap.find_as(static_cast<Value *>(I)); 6703 if (It != ValueExprMap.end()) { 6704 const SCEV *Old = It->second; 6705 6706 // SCEVUnknown for a PHI either means that it has an unrecognized 6707 // structure, or it's a PHI that's in the progress of being computed 6708 // by createNodeForPHI. In the former case, additional loop trip 6709 // count information isn't going to change anything. In the later 6710 // case, createNodeForPHI will perform the necessary updates on its 6711 // own when it gets to that point. 6712 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6713 eraseValueFromMap(It->first); 6714 forgetMemoizedResults(Old); 6715 } 6716 if (PHINode *PN = dyn_cast<PHINode>(I)) 6717 ConstantEvolutionLoopExitValue.erase(PN); 6718 } 6719 6720 // Since we don't need to invalidate anything for correctness and we're 6721 // only invalidating to make SCEV's results more precise, we get to stop 6722 // early to avoid invalidating too much. This is especially important in 6723 // cases like: 6724 // 6725 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6726 // loop0: 6727 // %pn0 = phi 6728 // ... 6729 // loop1: 6730 // %pn1 = phi 6731 // ... 6732 // 6733 // where both loop0 and loop1's backedge taken count uses the SCEV 6734 // expression for %v. If we don't have the early stop below then in cases 6735 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6736 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6737 // count for loop1, effectively nullifying SCEV's trip count cache. 6738 for (auto *U : I->users()) 6739 if (auto *I = dyn_cast<Instruction>(U)) { 6740 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6741 if (LoopForUser && L->contains(LoopForUser) && 6742 Discovered.insert(I).second) 6743 Worklist.push_back(I); 6744 } 6745 } 6746 } 6747 6748 // Re-lookup the insert position, since the call to 6749 // computeBackedgeTakenCount above could result in a 6750 // recusive call to getBackedgeTakenInfo (on a different 6751 // loop), which would invalidate the iterator computed 6752 // earlier. 6753 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6754 } 6755 6756 void ScalarEvolution::forgetAllLoops() { 6757 // This method is intended to forget all info about loops. It should 6758 // invalidate caches as if the following happened: 6759 // - The trip counts of all loops have changed arbitrarily 6760 // - Every llvm::Value has been updated in place to produce a different 6761 // result. 6762 BackedgeTakenCounts.clear(); 6763 PredicatedBackedgeTakenCounts.clear(); 6764 LoopPropertiesCache.clear(); 6765 ConstantEvolutionLoopExitValue.clear(); 6766 ValueExprMap.clear(); 6767 ValuesAtScopes.clear(); 6768 LoopDispositions.clear(); 6769 BlockDispositions.clear(); 6770 UnsignedRanges.clear(); 6771 SignedRanges.clear(); 6772 ExprValueMap.clear(); 6773 HasRecMap.clear(); 6774 MinTrailingZerosCache.clear(); 6775 PredicatedSCEVRewrites.clear(); 6776 } 6777 6778 void ScalarEvolution::forgetLoop(const Loop *L) { 6779 // Drop any stored trip count value. 6780 auto RemoveLoopFromBackedgeMap = 6781 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6782 auto BTCPos = Map.find(L); 6783 if (BTCPos != Map.end()) { 6784 BTCPos->second.clear(); 6785 Map.erase(BTCPos); 6786 } 6787 }; 6788 6789 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6790 SmallVector<Instruction *, 32> Worklist; 6791 SmallPtrSet<Instruction *, 16> Visited; 6792 6793 // Iterate over all the loops and sub-loops to drop SCEV information. 6794 while (!LoopWorklist.empty()) { 6795 auto *CurrL = LoopWorklist.pop_back_val(); 6796 6797 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6798 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6799 6800 // Drop information about predicated SCEV rewrites for this loop. 6801 for (auto I = PredicatedSCEVRewrites.begin(); 6802 I != PredicatedSCEVRewrites.end();) { 6803 std::pair<const SCEV *, const Loop *> Entry = I->first; 6804 if (Entry.second == CurrL) 6805 PredicatedSCEVRewrites.erase(I++); 6806 else 6807 ++I; 6808 } 6809 6810 auto LoopUsersItr = LoopUsers.find(CurrL); 6811 if (LoopUsersItr != LoopUsers.end()) { 6812 for (auto *S : LoopUsersItr->second) 6813 forgetMemoizedResults(S); 6814 LoopUsers.erase(LoopUsersItr); 6815 } 6816 6817 // Drop information about expressions based on loop-header PHIs. 6818 PushLoopPHIs(CurrL, Worklist); 6819 6820 while (!Worklist.empty()) { 6821 Instruction *I = Worklist.pop_back_val(); 6822 if (!Visited.insert(I).second) 6823 continue; 6824 6825 ValueExprMapType::iterator It = 6826 ValueExprMap.find_as(static_cast<Value *>(I)); 6827 if (It != ValueExprMap.end()) { 6828 eraseValueFromMap(It->first); 6829 forgetMemoizedResults(It->second); 6830 if (PHINode *PN = dyn_cast<PHINode>(I)) 6831 ConstantEvolutionLoopExitValue.erase(PN); 6832 } 6833 6834 PushDefUseChildren(I, Worklist); 6835 } 6836 6837 LoopPropertiesCache.erase(CurrL); 6838 // Forget all contained loops too, to avoid dangling entries in the 6839 // ValuesAtScopes map. 6840 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6841 } 6842 } 6843 6844 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6845 while (Loop *Parent = L->getParentLoop()) 6846 L = Parent; 6847 forgetLoop(L); 6848 } 6849 6850 void ScalarEvolution::forgetValue(Value *V) { 6851 Instruction *I = dyn_cast<Instruction>(V); 6852 if (!I) return; 6853 6854 // Drop information about expressions based on loop-header PHIs. 6855 SmallVector<Instruction *, 16> Worklist; 6856 Worklist.push_back(I); 6857 6858 SmallPtrSet<Instruction *, 8> Visited; 6859 while (!Worklist.empty()) { 6860 I = Worklist.pop_back_val(); 6861 if (!Visited.insert(I).second) 6862 continue; 6863 6864 ValueExprMapType::iterator It = 6865 ValueExprMap.find_as(static_cast<Value *>(I)); 6866 if (It != ValueExprMap.end()) { 6867 eraseValueFromMap(It->first); 6868 forgetMemoizedResults(It->second); 6869 if (PHINode *PN = dyn_cast<PHINode>(I)) 6870 ConstantEvolutionLoopExitValue.erase(PN); 6871 } 6872 6873 PushDefUseChildren(I, Worklist); 6874 } 6875 } 6876 6877 /// Get the exact loop backedge taken count considering all loop exits. A 6878 /// computable result can only be returned for loops with all exiting blocks 6879 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6880 /// is never skipped. This is a valid assumption as long as the loop exits via 6881 /// that test. For precise results, it is the caller's responsibility to specify 6882 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6883 const SCEV * 6884 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6885 SCEVUnionPredicate *Preds) const { 6886 // If any exits were not computable, the loop is not computable. 6887 if (!isComplete() || ExitNotTaken.empty()) 6888 return SE->getCouldNotCompute(); 6889 6890 const BasicBlock *Latch = L->getLoopLatch(); 6891 // All exiting blocks we have collected must dominate the only backedge. 6892 if (!Latch) 6893 return SE->getCouldNotCompute(); 6894 6895 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6896 // count is simply a minimum out of all these calculated exit counts. 6897 SmallVector<const SCEV *, 2> Ops; 6898 for (auto &ENT : ExitNotTaken) { 6899 const SCEV *BECount = ENT.ExactNotTaken; 6900 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6901 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6902 "We should only have known counts for exiting blocks that dominate " 6903 "latch!"); 6904 6905 Ops.push_back(BECount); 6906 6907 if (Preds && !ENT.hasAlwaysTruePredicate()) 6908 Preds->add(ENT.Predicate.get()); 6909 6910 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6911 "Predicate should be always true!"); 6912 } 6913 6914 return SE->getUMinFromMismatchedTypes(Ops); 6915 } 6916 6917 /// Get the exact not taken count for this loop exit. 6918 const SCEV * 6919 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6920 ScalarEvolution *SE) const { 6921 for (auto &ENT : ExitNotTaken) 6922 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6923 return ENT.ExactNotTaken; 6924 6925 return SE->getCouldNotCompute(); 6926 } 6927 6928 /// getMax - Get the max backedge taken count for the loop. 6929 const SCEV * 6930 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6931 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6932 return !ENT.hasAlwaysTruePredicate(); 6933 }; 6934 6935 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6936 return SE->getCouldNotCompute(); 6937 6938 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6939 "No point in having a non-constant max backedge taken count!"); 6940 return getMax(); 6941 } 6942 6943 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6944 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6945 return !ENT.hasAlwaysTruePredicate(); 6946 }; 6947 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6948 } 6949 6950 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6951 ScalarEvolution *SE) const { 6952 if (getMax() && getMax() != SE->getCouldNotCompute() && 6953 SE->hasOperand(getMax(), S)) 6954 return true; 6955 6956 for (auto &ENT : ExitNotTaken) 6957 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6958 SE->hasOperand(ENT.ExactNotTaken, S)) 6959 return true; 6960 6961 return false; 6962 } 6963 6964 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6965 : ExactNotTaken(E), MaxNotTaken(E) { 6966 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6967 isa<SCEVConstant>(MaxNotTaken)) && 6968 "No point in having a non-constant max backedge taken count!"); 6969 } 6970 6971 ScalarEvolution::ExitLimit::ExitLimit( 6972 const SCEV *E, const SCEV *M, bool MaxOrZero, 6973 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6974 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6975 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6976 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6977 "Exact is not allowed to be less precise than Max"); 6978 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6979 isa<SCEVConstant>(MaxNotTaken)) && 6980 "No point in having a non-constant max backedge taken count!"); 6981 for (auto *PredSet : PredSetList) 6982 for (auto *P : *PredSet) 6983 addPredicate(P); 6984 } 6985 6986 ScalarEvolution::ExitLimit::ExitLimit( 6987 const SCEV *E, const SCEV *M, bool MaxOrZero, 6988 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6989 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6990 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6991 isa<SCEVConstant>(MaxNotTaken)) && 6992 "No point in having a non-constant max backedge taken count!"); 6993 } 6994 6995 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6996 bool MaxOrZero) 6997 : ExitLimit(E, M, MaxOrZero, None) { 6998 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6999 isa<SCEVConstant>(MaxNotTaken)) && 7000 "No point in having a non-constant max backedge taken count!"); 7001 } 7002 7003 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7004 /// computable exit into a persistent ExitNotTakenInfo array. 7005 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7006 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 7007 ExitCounts, 7008 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 7009 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 7010 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7011 7012 ExitNotTaken.reserve(ExitCounts.size()); 7013 std::transform( 7014 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7015 [&](const EdgeExitInfo &EEI) { 7016 BasicBlock *ExitBB = EEI.first; 7017 const ExitLimit &EL = EEI.second; 7018 if (EL.Predicates.empty()) 7019 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 7020 7021 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7022 for (auto *Pred : EL.Predicates) 7023 Predicate->add(Pred); 7024 7025 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 7026 }); 7027 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 7028 "No point in having a non-constant max backedge taken count!"); 7029 } 7030 7031 /// Invalidate this result and free the ExitNotTakenInfo array. 7032 void ScalarEvolution::BackedgeTakenInfo::clear() { 7033 ExitNotTaken.clear(); 7034 } 7035 7036 /// Compute the number of times the backedge of the specified loop will execute. 7037 ScalarEvolution::BackedgeTakenInfo 7038 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7039 bool AllowPredicates) { 7040 SmallVector<BasicBlock *, 8> ExitingBlocks; 7041 L->getExitingBlocks(ExitingBlocks); 7042 7043 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7044 7045 SmallVector<EdgeExitInfo, 4> ExitCounts; 7046 bool CouldComputeBECount = true; 7047 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7048 const SCEV *MustExitMaxBECount = nullptr; 7049 const SCEV *MayExitMaxBECount = nullptr; 7050 bool MustExitMaxOrZero = false; 7051 7052 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7053 // and compute maxBECount. 7054 // Do a union of all the predicates here. 7055 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7056 BasicBlock *ExitBB = ExitingBlocks[i]; 7057 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7058 7059 assert((AllowPredicates || EL.Predicates.empty()) && 7060 "Predicated exit limit when predicates are not allowed!"); 7061 7062 // 1. For each exit that can be computed, add an entry to ExitCounts. 7063 // CouldComputeBECount is true only if all exits can be computed. 7064 if (EL.ExactNotTaken == getCouldNotCompute()) 7065 // We couldn't compute an exact value for this exit, so 7066 // we won't be able to compute an exact value for the loop. 7067 CouldComputeBECount = false; 7068 else 7069 ExitCounts.emplace_back(ExitBB, EL); 7070 7071 // 2. Derive the loop's MaxBECount from each exit's max number of 7072 // non-exiting iterations. Partition the loop exits into two kinds: 7073 // LoopMustExits and LoopMayExits. 7074 // 7075 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7076 // is a LoopMayExit. If any computable LoopMustExit is found, then 7077 // MaxBECount is the minimum EL.MaxNotTaken of computable 7078 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7079 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7080 // computable EL.MaxNotTaken. 7081 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7082 DT.dominates(ExitBB, Latch)) { 7083 if (!MustExitMaxBECount) { 7084 MustExitMaxBECount = EL.MaxNotTaken; 7085 MustExitMaxOrZero = EL.MaxOrZero; 7086 } else { 7087 MustExitMaxBECount = 7088 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7089 } 7090 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7091 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7092 MayExitMaxBECount = EL.MaxNotTaken; 7093 else { 7094 MayExitMaxBECount = 7095 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7096 } 7097 } 7098 } 7099 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7100 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7101 // The loop backedge will be taken the maximum or zero times if there's 7102 // a single exit that must be taken the maximum or zero times. 7103 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7104 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7105 MaxBECount, MaxOrZero); 7106 } 7107 7108 ScalarEvolution::ExitLimit 7109 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7110 bool AllowPredicates) { 7111 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7112 // If our exiting block does not dominate the latch, then its connection with 7113 // loop's exit limit may be far from trivial. 7114 const BasicBlock *Latch = L->getLoopLatch(); 7115 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7116 return getCouldNotCompute(); 7117 7118 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7119 Instruction *Term = ExitingBlock->getTerminator(); 7120 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7121 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7122 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7123 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7124 "It should have one successor in loop and one exit block!"); 7125 // Proceed to the next level to examine the exit condition expression. 7126 return computeExitLimitFromCond( 7127 L, BI->getCondition(), ExitIfTrue, 7128 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7129 } 7130 7131 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7132 // For switch, make sure that there is a single exit from the loop. 7133 BasicBlock *Exit = nullptr; 7134 for (auto *SBB : successors(ExitingBlock)) 7135 if (!L->contains(SBB)) { 7136 if (Exit) // Multiple exit successors. 7137 return getCouldNotCompute(); 7138 Exit = SBB; 7139 } 7140 assert(Exit && "Exiting block must have at least one exit"); 7141 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7142 /*ControlsExit=*/IsOnlyExit); 7143 } 7144 7145 return getCouldNotCompute(); 7146 } 7147 7148 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7149 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7150 bool ControlsExit, bool AllowPredicates) { 7151 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7152 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7153 ControlsExit, AllowPredicates); 7154 } 7155 7156 Optional<ScalarEvolution::ExitLimit> 7157 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7158 bool ExitIfTrue, bool ControlsExit, 7159 bool AllowPredicates) { 7160 (void)this->L; 7161 (void)this->ExitIfTrue; 7162 (void)this->AllowPredicates; 7163 7164 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7165 this->AllowPredicates == AllowPredicates && 7166 "Variance in assumed invariant key components!"); 7167 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7168 if (Itr == TripCountMap.end()) 7169 return None; 7170 return Itr->second; 7171 } 7172 7173 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7174 bool ExitIfTrue, 7175 bool ControlsExit, 7176 bool AllowPredicates, 7177 const ExitLimit &EL) { 7178 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7179 this->AllowPredicates == AllowPredicates && 7180 "Variance in assumed invariant key components!"); 7181 7182 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7183 assert(InsertResult.second && "Expected successful insertion!"); 7184 (void)InsertResult; 7185 (void)ExitIfTrue; 7186 } 7187 7188 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7189 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7190 bool ControlsExit, bool AllowPredicates) { 7191 7192 if (auto MaybeEL = 7193 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7194 return *MaybeEL; 7195 7196 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7197 ControlsExit, AllowPredicates); 7198 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7199 return EL; 7200 } 7201 7202 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7203 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7204 bool ControlsExit, bool AllowPredicates) { 7205 // Check if the controlling expression for this loop is an And or Or. 7206 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7207 if (BO->getOpcode() == Instruction::And) { 7208 // Recurse on the operands of the and. 7209 bool EitherMayExit = !ExitIfTrue; 7210 ExitLimit EL0 = computeExitLimitFromCondCached( 7211 Cache, L, BO->getOperand(0), ExitIfTrue, 7212 ControlsExit && !EitherMayExit, AllowPredicates); 7213 ExitLimit EL1 = computeExitLimitFromCondCached( 7214 Cache, L, BO->getOperand(1), ExitIfTrue, 7215 ControlsExit && !EitherMayExit, AllowPredicates); 7216 const SCEV *BECount = getCouldNotCompute(); 7217 const SCEV *MaxBECount = getCouldNotCompute(); 7218 if (EitherMayExit) { 7219 // Both conditions must be true for the loop to continue executing. 7220 // Choose the less conservative count. 7221 if (EL0.ExactNotTaken == getCouldNotCompute() || 7222 EL1.ExactNotTaken == getCouldNotCompute()) 7223 BECount = getCouldNotCompute(); 7224 else 7225 BECount = 7226 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7227 if (EL0.MaxNotTaken == getCouldNotCompute()) 7228 MaxBECount = EL1.MaxNotTaken; 7229 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7230 MaxBECount = EL0.MaxNotTaken; 7231 else 7232 MaxBECount = 7233 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7234 } else { 7235 // Both conditions must be true at the same time for the loop to exit. 7236 // For now, be conservative. 7237 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7238 MaxBECount = EL0.MaxNotTaken; 7239 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7240 BECount = EL0.ExactNotTaken; 7241 } 7242 7243 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7244 // to be more aggressive when computing BECount than when computing 7245 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7246 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7247 // to not. 7248 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7249 !isa<SCEVCouldNotCompute>(BECount)) 7250 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7251 7252 return ExitLimit(BECount, MaxBECount, false, 7253 {&EL0.Predicates, &EL1.Predicates}); 7254 } 7255 if (BO->getOpcode() == Instruction::Or) { 7256 // Recurse on the operands of the or. 7257 bool EitherMayExit = ExitIfTrue; 7258 ExitLimit EL0 = computeExitLimitFromCondCached( 7259 Cache, L, BO->getOperand(0), ExitIfTrue, 7260 ControlsExit && !EitherMayExit, AllowPredicates); 7261 ExitLimit EL1 = computeExitLimitFromCondCached( 7262 Cache, L, BO->getOperand(1), ExitIfTrue, 7263 ControlsExit && !EitherMayExit, AllowPredicates); 7264 const SCEV *BECount = getCouldNotCompute(); 7265 const SCEV *MaxBECount = getCouldNotCompute(); 7266 if (EitherMayExit) { 7267 // Both conditions must be false for the loop to continue executing. 7268 // Choose the less conservative count. 7269 if (EL0.ExactNotTaken == getCouldNotCompute() || 7270 EL1.ExactNotTaken == getCouldNotCompute()) 7271 BECount = getCouldNotCompute(); 7272 else 7273 BECount = 7274 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7275 if (EL0.MaxNotTaken == getCouldNotCompute()) 7276 MaxBECount = EL1.MaxNotTaken; 7277 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7278 MaxBECount = EL0.MaxNotTaken; 7279 else 7280 MaxBECount = 7281 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7282 } else { 7283 // Both conditions must be false at the same time for the loop to exit. 7284 // For now, be conservative. 7285 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7286 MaxBECount = EL0.MaxNotTaken; 7287 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7288 BECount = EL0.ExactNotTaken; 7289 } 7290 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7291 // to be more aggressive when computing BECount than when computing 7292 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7293 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7294 // to not. 7295 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7296 !isa<SCEVCouldNotCompute>(BECount)) 7297 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7298 7299 return ExitLimit(BECount, MaxBECount, false, 7300 {&EL0.Predicates, &EL1.Predicates}); 7301 } 7302 } 7303 7304 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7305 // Proceed to the next level to examine the icmp. 7306 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7307 ExitLimit EL = 7308 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7309 if (EL.hasFullInfo() || !AllowPredicates) 7310 return EL; 7311 7312 // Try again, but use SCEV predicates this time. 7313 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7314 /*AllowPredicates=*/true); 7315 } 7316 7317 // Check for a constant condition. These are normally stripped out by 7318 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7319 // preserve the CFG and is temporarily leaving constant conditions 7320 // in place. 7321 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7322 if (ExitIfTrue == !CI->getZExtValue()) 7323 // The backedge is always taken. 7324 return getCouldNotCompute(); 7325 else 7326 // The backedge is never taken. 7327 return getZero(CI->getType()); 7328 } 7329 7330 // If it's not an integer or pointer comparison then compute it the hard way. 7331 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7332 } 7333 7334 ScalarEvolution::ExitLimit 7335 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7336 ICmpInst *ExitCond, 7337 bool ExitIfTrue, 7338 bool ControlsExit, 7339 bool AllowPredicates) { 7340 // If the condition was exit on true, convert the condition to exit on false 7341 ICmpInst::Predicate Pred; 7342 if (!ExitIfTrue) 7343 Pred = ExitCond->getPredicate(); 7344 else 7345 Pred = ExitCond->getInversePredicate(); 7346 const ICmpInst::Predicate OriginalPred = Pred; 7347 7348 // Handle common loops like: for (X = "string"; *X; ++X) 7349 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7350 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7351 ExitLimit ItCnt = 7352 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7353 if (ItCnt.hasAnyInfo()) 7354 return ItCnt; 7355 } 7356 7357 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7358 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7359 7360 // Try to evaluate any dependencies out of the loop. 7361 LHS = getSCEVAtScope(LHS, L); 7362 RHS = getSCEVAtScope(RHS, L); 7363 7364 // At this point, we would like to compute how many iterations of the 7365 // loop the predicate will return true for these inputs. 7366 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7367 // If there is a loop-invariant, force it into the RHS. 7368 std::swap(LHS, RHS); 7369 Pred = ICmpInst::getSwappedPredicate(Pred); 7370 } 7371 7372 // Simplify the operands before analyzing them. 7373 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7374 7375 // If we have a comparison of a chrec against a constant, try to use value 7376 // ranges to answer this query. 7377 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7378 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7379 if (AddRec->getLoop() == L) { 7380 // Form the constant range. 7381 ConstantRange CompRange = 7382 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7383 7384 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7385 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7386 } 7387 7388 switch (Pred) { 7389 case ICmpInst::ICMP_NE: { // while (X != Y) 7390 // Convert to: while (X-Y != 0) 7391 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7392 AllowPredicates); 7393 if (EL.hasAnyInfo()) return EL; 7394 break; 7395 } 7396 case ICmpInst::ICMP_EQ: { // while (X == Y) 7397 // Convert to: while (X-Y == 0) 7398 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7399 if (EL.hasAnyInfo()) return EL; 7400 break; 7401 } 7402 case ICmpInst::ICMP_SLT: 7403 case ICmpInst::ICMP_ULT: { // while (X < Y) 7404 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7405 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7406 AllowPredicates); 7407 if (EL.hasAnyInfo()) return EL; 7408 break; 7409 } 7410 case ICmpInst::ICMP_SGT: 7411 case ICmpInst::ICMP_UGT: { // while (X > Y) 7412 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7413 ExitLimit EL = 7414 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7415 AllowPredicates); 7416 if (EL.hasAnyInfo()) return EL; 7417 break; 7418 } 7419 default: 7420 break; 7421 } 7422 7423 auto *ExhaustiveCount = 7424 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7425 7426 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7427 return ExhaustiveCount; 7428 7429 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7430 ExitCond->getOperand(1), L, OriginalPred); 7431 } 7432 7433 ScalarEvolution::ExitLimit 7434 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7435 SwitchInst *Switch, 7436 BasicBlock *ExitingBlock, 7437 bool ControlsExit) { 7438 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7439 7440 // Give up if the exit is the default dest of a switch. 7441 if (Switch->getDefaultDest() == ExitingBlock) 7442 return getCouldNotCompute(); 7443 7444 assert(L->contains(Switch->getDefaultDest()) && 7445 "Default case must not exit the loop!"); 7446 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7447 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7448 7449 // while (X != Y) --> while (X-Y != 0) 7450 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7451 if (EL.hasAnyInfo()) 7452 return EL; 7453 7454 return getCouldNotCompute(); 7455 } 7456 7457 static ConstantInt * 7458 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7459 ScalarEvolution &SE) { 7460 const SCEV *InVal = SE.getConstant(C); 7461 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7462 assert(isa<SCEVConstant>(Val) && 7463 "Evaluation of SCEV at constant didn't fold correctly?"); 7464 return cast<SCEVConstant>(Val)->getValue(); 7465 } 7466 7467 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7468 /// compute the backedge execution count. 7469 ScalarEvolution::ExitLimit 7470 ScalarEvolution::computeLoadConstantCompareExitLimit( 7471 LoadInst *LI, 7472 Constant *RHS, 7473 const Loop *L, 7474 ICmpInst::Predicate predicate) { 7475 if (LI->isVolatile()) return getCouldNotCompute(); 7476 7477 // Check to see if the loaded pointer is a getelementptr of a global. 7478 // TODO: Use SCEV instead of manually grubbing with GEPs. 7479 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7480 if (!GEP) return getCouldNotCompute(); 7481 7482 // Make sure that it is really a constant global we are gepping, with an 7483 // initializer, and make sure the first IDX is really 0. 7484 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7485 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7486 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7487 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7488 return getCouldNotCompute(); 7489 7490 // Okay, we allow one non-constant index into the GEP instruction. 7491 Value *VarIdx = nullptr; 7492 std::vector<Constant*> Indexes; 7493 unsigned VarIdxNum = 0; 7494 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7495 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7496 Indexes.push_back(CI); 7497 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7498 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7499 VarIdx = GEP->getOperand(i); 7500 VarIdxNum = i-2; 7501 Indexes.push_back(nullptr); 7502 } 7503 7504 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7505 if (!VarIdx) 7506 return getCouldNotCompute(); 7507 7508 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7509 // Check to see if X is a loop variant variable value now. 7510 const SCEV *Idx = getSCEV(VarIdx); 7511 Idx = getSCEVAtScope(Idx, L); 7512 7513 // We can only recognize very limited forms of loop index expressions, in 7514 // particular, only affine AddRec's like {C1,+,C2}. 7515 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7516 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7517 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7518 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7519 return getCouldNotCompute(); 7520 7521 unsigned MaxSteps = MaxBruteForceIterations; 7522 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7523 ConstantInt *ItCst = ConstantInt::get( 7524 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7525 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7526 7527 // Form the GEP offset. 7528 Indexes[VarIdxNum] = Val; 7529 7530 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7531 Indexes); 7532 if (!Result) break; // Cannot compute! 7533 7534 // Evaluate the condition for this iteration. 7535 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7536 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7537 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7538 ++NumArrayLenItCounts; 7539 return getConstant(ItCst); // Found terminating iteration! 7540 } 7541 } 7542 return getCouldNotCompute(); 7543 } 7544 7545 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7546 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7547 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7548 if (!RHS) 7549 return getCouldNotCompute(); 7550 7551 const BasicBlock *Latch = L->getLoopLatch(); 7552 if (!Latch) 7553 return getCouldNotCompute(); 7554 7555 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7556 if (!Predecessor) 7557 return getCouldNotCompute(); 7558 7559 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7560 // Return LHS in OutLHS and shift_opt in OutOpCode. 7561 auto MatchPositiveShift = 7562 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7563 7564 using namespace PatternMatch; 7565 7566 ConstantInt *ShiftAmt; 7567 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7568 OutOpCode = Instruction::LShr; 7569 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7570 OutOpCode = Instruction::AShr; 7571 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7572 OutOpCode = Instruction::Shl; 7573 else 7574 return false; 7575 7576 return ShiftAmt->getValue().isStrictlyPositive(); 7577 }; 7578 7579 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7580 // 7581 // loop: 7582 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7583 // %iv.shifted = lshr i32 %iv, <positive constant> 7584 // 7585 // Return true on a successful match. Return the corresponding PHI node (%iv 7586 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7587 auto MatchShiftRecurrence = 7588 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7589 Optional<Instruction::BinaryOps> PostShiftOpCode; 7590 7591 { 7592 Instruction::BinaryOps OpC; 7593 Value *V; 7594 7595 // If we encounter a shift instruction, "peel off" the shift operation, 7596 // and remember that we did so. Later when we inspect %iv's backedge 7597 // value, we will make sure that the backedge value uses the same 7598 // operation. 7599 // 7600 // Note: the peeled shift operation does not have to be the same 7601 // instruction as the one feeding into the PHI's backedge value. We only 7602 // really care about it being the same *kind* of shift instruction -- 7603 // that's all that is required for our later inferences to hold. 7604 if (MatchPositiveShift(LHS, V, OpC)) { 7605 PostShiftOpCode = OpC; 7606 LHS = V; 7607 } 7608 } 7609 7610 PNOut = dyn_cast<PHINode>(LHS); 7611 if (!PNOut || PNOut->getParent() != L->getHeader()) 7612 return false; 7613 7614 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7615 Value *OpLHS; 7616 7617 return 7618 // The backedge value for the PHI node must be a shift by a positive 7619 // amount 7620 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7621 7622 // of the PHI node itself 7623 OpLHS == PNOut && 7624 7625 // and the kind of shift should be match the kind of shift we peeled 7626 // off, if any. 7627 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7628 }; 7629 7630 PHINode *PN; 7631 Instruction::BinaryOps OpCode; 7632 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7633 return getCouldNotCompute(); 7634 7635 const DataLayout &DL = getDataLayout(); 7636 7637 // The key rationale for this optimization is that for some kinds of shift 7638 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7639 // within a finite number of iterations. If the condition guarding the 7640 // backedge (in the sense that the backedge is taken if the condition is true) 7641 // is false for the value the shift recurrence stabilizes to, then we know 7642 // that the backedge is taken only a finite number of times. 7643 7644 ConstantInt *StableValue = nullptr; 7645 switch (OpCode) { 7646 default: 7647 llvm_unreachable("Impossible case!"); 7648 7649 case Instruction::AShr: { 7650 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7651 // bitwidth(K) iterations. 7652 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7653 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7654 Predecessor->getTerminator(), &DT); 7655 auto *Ty = cast<IntegerType>(RHS->getType()); 7656 if (Known.isNonNegative()) 7657 StableValue = ConstantInt::get(Ty, 0); 7658 else if (Known.isNegative()) 7659 StableValue = ConstantInt::get(Ty, -1, true); 7660 else 7661 return getCouldNotCompute(); 7662 7663 break; 7664 } 7665 case Instruction::LShr: 7666 case Instruction::Shl: 7667 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7668 // stabilize to 0 in at most bitwidth(K) iterations. 7669 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7670 break; 7671 } 7672 7673 auto *Result = 7674 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7675 assert(Result->getType()->isIntegerTy(1) && 7676 "Otherwise cannot be an operand to a branch instruction"); 7677 7678 if (Result->isZeroValue()) { 7679 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7680 const SCEV *UpperBound = 7681 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7682 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7683 } 7684 7685 return getCouldNotCompute(); 7686 } 7687 7688 /// Return true if we can constant fold an instruction of the specified type, 7689 /// assuming that all operands were constants. 7690 static bool CanConstantFold(const Instruction *I) { 7691 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7692 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7693 isa<LoadInst>(I)) 7694 return true; 7695 7696 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7697 if (const Function *F = CI->getCalledFunction()) 7698 return canConstantFoldCallTo(CI, F); 7699 return false; 7700 } 7701 7702 /// Determine whether this instruction can constant evolve within this loop 7703 /// assuming its operands can all constant evolve. 7704 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7705 // An instruction outside of the loop can't be derived from a loop PHI. 7706 if (!L->contains(I)) return false; 7707 7708 if (isa<PHINode>(I)) { 7709 // We don't currently keep track of the control flow needed to evaluate 7710 // PHIs, so we cannot handle PHIs inside of loops. 7711 return L->getHeader() == I->getParent(); 7712 } 7713 7714 // If we won't be able to constant fold this expression even if the operands 7715 // are constants, bail early. 7716 return CanConstantFold(I); 7717 } 7718 7719 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7720 /// recursing through each instruction operand until reaching a loop header phi. 7721 static PHINode * 7722 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7723 DenseMap<Instruction *, PHINode *> &PHIMap, 7724 unsigned Depth) { 7725 if (Depth > MaxConstantEvolvingDepth) 7726 return nullptr; 7727 7728 // Otherwise, we can evaluate this instruction if all of its operands are 7729 // constant or derived from a PHI node themselves. 7730 PHINode *PHI = nullptr; 7731 for (Value *Op : UseInst->operands()) { 7732 if (isa<Constant>(Op)) continue; 7733 7734 Instruction *OpInst = dyn_cast<Instruction>(Op); 7735 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7736 7737 PHINode *P = dyn_cast<PHINode>(OpInst); 7738 if (!P) 7739 // If this operand is already visited, reuse the prior result. 7740 // We may have P != PHI if this is the deepest point at which the 7741 // inconsistent paths meet. 7742 P = PHIMap.lookup(OpInst); 7743 if (!P) { 7744 // Recurse and memoize the results, whether a phi is found or not. 7745 // This recursive call invalidates pointers into PHIMap. 7746 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7747 PHIMap[OpInst] = P; 7748 } 7749 if (!P) 7750 return nullptr; // Not evolving from PHI 7751 if (PHI && PHI != P) 7752 return nullptr; // Evolving from multiple different PHIs. 7753 PHI = P; 7754 } 7755 // This is a expression evolving from a constant PHI! 7756 return PHI; 7757 } 7758 7759 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7760 /// in the loop that V is derived from. We allow arbitrary operations along the 7761 /// way, but the operands of an operation must either be constants or a value 7762 /// derived from a constant PHI. If this expression does not fit with these 7763 /// constraints, return null. 7764 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7765 Instruction *I = dyn_cast<Instruction>(V); 7766 if (!I || !canConstantEvolve(I, L)) return nullptr; 7767 7768 if (PHINode *PN = dyn_cast<PHINode>(I)) 7769 return PN; 7770 7771 // Record non-constant instructions contained by the loop. 7772 DenseMap<Instruction *, PHINode *> PHIMap; 7773 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7774 } 7775 7776 /// EvaluateExpression - Given an expression that passes the 7777 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7778 /// in the loop has the value PHIVal. If we can't fold this expression for some 7779 /// reason, return null. 7780 static Constant *EvaluateExpression(Value *V, const Loop *L, 7781 DenseMap<Instruction *, Constant *> &Vals, 7782 const DataLayout &DL, 7783 const TargetLibraryInfo *TLI) { 7784 // Convenient constant check, but redundant for recursive calls. 7785 if (Constant *C = dyn_cast<Constant>(V)) return C; 7786 Instruction *I = dyn_cast<Instruction>(V); 7787 if (!I) return nullptr; 7788 7789 if (Constant *C = Vals.lookup(I)) return C; 7790 7791 // An instruction inside the loop depends on a value outside the loop that we 7792 // weren't given a mapping for, or a value such as a call inside the loop. 7793 if (!canConstantEvolve(I, L)) return nullptr; 7794 7795 // An unmapped PHI can be due to a branch or another loop inside this loop, 7796 // or due to this not being the initial iteration through a loop where we 7797 // couldn't compute the evolution of this particular PHI last time. 7798 if (isa<PHINode>(I)) return nullptr; 7799 7800 std::vector<Constant*> Operands(I->getNumOperands()); 7801 7802 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7803 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7804 if (!Operand) { 7805 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7806 if (!Operands[i]) return nullptr; 7807 continue; 7808 } 7809 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7810 Vals[Operand] = C; 7811 if (!C) return nullptr; 7812 Operands[i] = C; 7813 } 7814 7815 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7816 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7817 Operands[1], DL, TLI); 7818 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7819 if (!LI->isVolatile()) 7820 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7821 } 7822 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7823 } 7824 7825 7826 // If every incoming value to PN except the one for BB is a specific Constant, 7827 // return that, else return nullptr. 7828 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7829 Constant *IncomingVal = nullptr; 7830 7831 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7832 if (PN->getIncomingBlock(i) == BB) 7833 continue; 7834 7835 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7836 if (!CurrentVal) 7837 return nullptr; 7838 7839 if (IncomingVal != CurrentVal) { 7840 if (IncomingVal) 7841 return nullptr; 7842 IncomingVal = CurrentVal; 7843 } 7844 } 7845 7846 return IncomingVal; 7847 } 7848 7849 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7850 /// in the header of its containing loop, we know the loop executes a 7851 /// constant number of times, and the PHI node is just a recurrence 7852 /// involving constants, fold it. 7853 Constant * 7854 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7855 const APInt &BEs, 7856 const Loop *L) { 7857 auto I = ConstantEvolutionLoopExitValue.find(PN); 7858 if (I != ConstantEvolutionLoopExitValue.end()) 7859 return I->second; 7860 7861 if (BEs.ugt(MaxBruteForceIterations)) 7862 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7863 7864 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7865 7866 DenseMap<Instruction *, Constant *> CurrentIterVals; 7867 BasicBlock *Header = L->getHeader(); 7868 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7869 7870 BasicBlock *Latch = L->getLoopLatch(); 7871 if (!Latch) 7872 return nullptr; 7873 7874 for (PHINode &PHI : Header->phis()) { 7875 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7876 CurrentIterVals[&PHI] = StartCST; 7877 } 7878 if (!CurrentIterVals.count(PN)) 7879 return RetVal = nullptr; 7880 7881 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7882 7883 // Execute the loop symbolically to determine the exit value. 7884 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7885 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7886 7887 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7888 unsigned IterationNum = 0; 7889 const DataLayout &DL = getDataLayout(); 7890 for (; ; ++IterationNum) { 7891 if (IterationNum == NumIterations) 7892 return RetVal = CurrentIterVals[PN]; // Got exit value! 7893 7894 // Compute the value of the PHIs for the next iteration. 7895 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7896 DenseMap<Instruction *, Constant *> NextIterVals; 7897 Constant *NextPHI = 7898 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7899 if (!NextPHI) 7900 return nullptr; // Couldn't evaluate! 7901 NextIterVals[PN] = NextPHI; 7902 7903 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7904 7905 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7906 // cease to be able to evaluate one of them or if they stop evolving, 7907 // because that doesn't necessarily prevent us from computing PN. 7908 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7909 for (const auto &I : CurrentIterVals) { 7910 PHINode *PHI = dyn_cast<PHINode>(I.first); 7911 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7912 PHIsToCompute.emplace_back(PHI, I.second); 7913 } 7914 // We use two distinct loops because EvaluateExpression may invalidate any 7915 // iterators into CurrentIterVals. 7916 for (const auto &I : PHIsToCompute) { 7917 PHINode *PHI = I.first; 7918 Constant *&NextPHI = NextIterVals[PHI]; 7919 if (!NextPHI) { // Not already computed. 7920 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7921 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7922 } 7923 if (NextPHI != I.second) 7924 StoppedEvolving = false; 7925 } 7926 7927 // If all entries in CurrentIterVals == NextIterVals then we can stop 7928 // iterating, the loop can't continue to change. 7929 if (StoppedEvolving) 7930 return RetVal = CurrentIterVals[PN]; 7931 7932 CurrentIterVals.swap(NextIterVals); 7933 } 7934 } 7935 7936 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7937 Value *Cond, 7938 bool ExitWhen) { 7939 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7940 if (!PN) return getCouldNotCompute(); 7941 7942 // If the loop is canonicalized, the PHI will have exactly two entries. 7943 // That's the only form we support here. 7944 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7945 7946 DenseMap<Instruction *, Constant *> CurrentIterVals; 7947 BasicBlock *Header = L->getHeader(); 7948 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7949 7950 BasicBlock *Latch = L->getLoopLatch(); 7951 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7952 7953 for (PHINode &PHI : Header->phis()) { 7954 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7955 CurrentIterVals[&PHI] = StartCST; 7956 } 7957 if (!CurrentIterVals.count(PN)) 7958 return getCouldNotCompute(); 7959 7960 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7961 // the loop symbolically to determine when the condition gets a value of 7962 // "ExitWhen". 7963 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7964 const DataLayout &DL = getDataLayout(); 7965 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7966 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7967 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7968 7969 // Couldn't symbolically evaluate. 7970 if (!CondVal) return getCouldNotCompute(); 7971 7972 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7973 ++NumBruteForceTripCountsComputed; 7974 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7975 } 7976 7977 // Update all the PHI nodes for the next iteration. 7978 DenseMap<Instruction *, Constant *> NextIterVals; 7979 7980 // Create a list of which PHIs we need to compute. We want to do this before 7981 // calling EvaluateExpression on them because that may invalidate iterators 7982 // into CurrentIterVals. 7983 SmallVector<PHINode *, 8> PHIsToCompute; 7984 for (const auto &I : CurrentIterVals) { 7985 PHINode *PHI = dyn_cast<PHINode>(I.first); 7986 if (!PHI || PHI->getParent() != Header) continue; 7987 PHIsToCompute.push_back(PHI); 7988 } 7989 for (PHINode *PHI : PHIsToCompute) { 7990 Constant *&NextPHI = NextIterVals[PHI]; 7991 if (NextPHI) continue; // Already computed! 7992 7993 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7994 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7995 } 7996 CurrentIterVals.swap(NextIterVals); 7997 } 7998 7999 // Too many iterations were needed to evaluate. 8000 return getCouldNotCompute(); 8001 } 8002 8003 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8004 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8005 ValuesAtScopes[V]; 8006 // Check to see if we've folded this expression at this loop before. 8007 for (auto &LS : Values) 8008 if (LS.first == L) 8009 return LS.second ? LS.second : V; 8010 8011 Values.emplace_back(L, nullptr); 8012 8013 // Otherwise compute it. 8014 const SCEV *C = computeSCEVAtScope(V, L); 8015 for (auto &LS : reverse(ValuesAtScopes[V])) 8016 if (LS.first == L) { 8017 LS.second = C; 8018 break; 8019 } 8020 return C; 8021 } 8022 8023 /// This builds up a Constant using the ConstantExpr interface. That way, we 8024 /// will return Constants for objects which aren't represented by a 8025 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8026 /// Returns NULL if the SCEV isn't representable as a Constant. 8027 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8028 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 8029 case scCouldNotCompute: 8030 case scAddRecExpr: 8031 break; 8032 case scConstant: 8033 return cast<SCEVConstant>(V)->getValue(); 8034 case scUnknown: 8035 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8036 case scSignExtend: { 8037 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8038 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8039 return ConstantExpr::getSExt(CastOp, SS->getType()); 8040 break; 8041 } 8042 case scZeroExtend: { 8043 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8044 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8045 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8046 break; 8047 } 8048 case scTruncate: { 8049 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8050 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8051 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8052 break; 8053 } 8054 case scAddExpr: { 8055 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8056 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8057 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8058 unsigned AS = PTy->getAddressSpace(); 8059 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8060 C = ConstantExpr::getBitCast(C, DestPtrTy); 8061 } 8062 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8063 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8064 if (!C2) return nullptr; 8065 8066 // First pointer! 8067 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8068 unsigned AS = C2->getType()->getPointerAddressSpace(); 8069 std::swap(C, C2); 8070 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8071 // The offsets have been converted to bytes. We can add bytes to an 8072 // i8* by GEP with the byte count in the first index. 8073 C = ConstantExpr::getBitCast(C, DestPtrTy); 8074 } 8075 8076 // Don't bother trying to sum two pointers. We probably can't 8077 // statically compute a load that results from it anyway. 8078 if (C2->getType()->isPointerTy()) 8079 return nullptr; 8080 8081 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8082 if (PTy->getElementType()->isStructTy()) 8083 C2 = ConstantExpr::getIntegerCast( 8084 C2, Type::getInt32Ty(C->getContext()), true); 8085 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8086 } else 8087 C = ConstantExpr::getAdd(C, C2); 8088 } 8089 return C; 8090 } 8091 break; 8092 } 8093 case scMulExpr: { 8094 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8095 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8096 // Don't bother with pointers at all. 8097 if (C->getType()->isPointerTy()) return nullptr; 8098 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8099 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8100 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8101 C = ConstantExpr::getMul(C, C2); 8102 } 8103 return C; 8104 } 8105 break; 8106 } 8107 case scUDivExpr: { 8108 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8109 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8110 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8111 if (LHS->getType() == RHS->getType()) 8112 return ConstantExpr::getUDiv(LHS, RHS); 8113 break; 8114 } 8115 case scSMaxExpr: 8116 case scUMaxExpr: 8117 break; // TODO: smax, umax. 8118 } 8119 return nullptr; 8120 } 8121 8122 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8123 if (isa<SCEVConstant>(V)) return V; 8124 8125 // If this instruction is evolved from a constant-evolving PHI, compute the 8126 // exit value from the loop without using SCEVs. 8127 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8128 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8129 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8130 const Loop *LI = this->LI[I->getParent()]; 8131 // Looking for loop exit value. 8132 if (LI && LI->getParentLoop() == L && 8133 PN->getParent() == LI->getHeader()) { 8134 // Okay, there is no closed form solution for the PHI node. Check 8135 // to see if the loop that contains it has a known backedge-taken 8136 // count. If so, we may be able to force computation of the exit 8137 // value. 8138 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8139 if (const SCEVConstant *BTCC = 8140 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8141 8142 // This trivial case can show up in some degenerate cases where 8143 // the incoming IR has not yet been fully simplified. 8144 if (BTCC->getValue()->isZero()) { 8145 Value *InitValue = nullptr; 8146 bool MultipleInitValues = false; 8147 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8148 if (!LI->contains(PN->getIncomingBlock(i))) { 8149 if (!InitValue) 8150 InitValue = PN->getIncomingValue(i); 8151 else if (InitValue != PN->getIncomingValue(i)) { 8152 MultipleInitValues = true; 8153 break; 8154 } 8155 } 8156 if (!MultipleInitValues && InitValue) 8157 return getSCEV(InitValue); 8158 } 8159 } 8160 // Okay, we know how many times the containing loop executes. If 8161 // this is a constant evolving PHI node, get the final value at 8162 // the specified iteration number. 8163 Constant *RV = 8164 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8165 if (RV) return getSCEV(RV); 8166 } 8167 } 8168 } 8169 8170 // Okay, this is an expression that we cannot symbolically evaluate 8171 // into a SCEV. Check to see if it's possible to symbolically evaluate 8172 // the arguments into constants, and if so, try to constant propagate the 8173 // result. This is particularly useful for computing loop exit values. 8174 if (CanConstantFold(I)) { 8175 SmallVector<Constant *, 4> Operands; 8176 bool MadeImprovement = false; 8177 for (Value *Op : I->operands()) { 8178 if (Constant *C = dyn_cast<Constant>(Op)) { 8179 Operands.push_back(C); 8180 continue; 8181 } 8182 8183 // If any of the operands is non-constant and if they are 8184 // non-integer and non-pointer, don't even try to analyze them 8185 // with scev techniques. 8186 if (!isSCEVable(Op->getType())) 8187 return V; 8188 8189 const SCEV *OrigV = getSCEV(Op); 8190 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8191 MadeImprovement |= OrigV != OpV; 8192 8193 Constant *C = BuildConstantFromSCEV(OpV); 8194 if (!C) return V; 8195 if (C->getType() != Op->getType()) 8196 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8197 Op->getType(), 8198 false), 8199 C, Op->getType()); 8200 Operands.push_back(C); 8201 } 8202 8203 // Check to see if getSCEVAtScope actually made an improvement. 8204 if (MadeImprovement) { 8205 Constant *C = nullptr; 8206 const DataLayout &DL = getDataLayout(); 8207 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8208 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8209 Operands[1], DL, &TLI); 8210 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8211 if (!LI->isVolatile()) 8212 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8213 } else 8214 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8215 if (!C) return V; 8216 return getSCEV(C); 8217 } 8218 } 8219 } 8220 8221 // This is some other type of SCEVUnknown, just return it. 8222 return V; 8223 } 8224 8225 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8226 // Avoid performing the look-up in the common case where the specified 8227 // expression has no loop-variant portions. 8228 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8229 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8230 if (OpAtScope != Comm->getOperand(i)) { 8231 // Okay, at least one of these operands is loop variant but might be 8232 // foldable. Build a new instance of the folded commutative expression. 8233 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8234 Comm->op_begin()+i); 8235 NewOps.push_back(OpAtScope); 8236 8237 for (++i; i != e; ++i) { 8238 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8239 NewOps.push_back(OpAtScope); 8240 } 8241 if (isa<SCEVAddExpr>(Comm)) 8242 return getAddExpr(NewOps); 8243 if (isa<SCEVMulExpr>(Comm)) 8244 return getMulExpr(NewOps); 8245 if (isa<SCEVSMaxExpr>(Comm)) 8246 return getSMaxExpr(NewOps); 8247 if (isa<SCEVUMaxExpr>(Comm)) 8248 return getUMaxExpr(NewOps); 8249 llvm_unreachable("Unknown commutative SCEV type!"); 8250 } 8251 } 8252 // If we got here, all operands are loop invariant. 8253 return Comm; 8254 } 8255 8256 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8257 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8258 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8259 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8260 return Div; // must be loop invariant 8261 return getUDivExpr(LHS, RHS); 8262 } 8263 8264 // If this is a loop recurrence for a loop that does not contain L, then we 8265 // are dealing with the final value computed by the loop. 8266 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8267 // First, attempt to evaluate each operand. 8268 // Avoid performing the look-up in the common case where the specified 8269 // expression has no loop-variant portions. 8270 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8271 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8272 if (OpAtScope == AddRec->getOperand(i)) 8273 continue; 8274 8275 // Okay, at least one of these operands is loop variant but might be 8276 // foldable. Build a new instance of the folded commutative expression. 8277 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8278 AddRec->op_begin()+i); 8279 NewOps.push_back(OpAtScope); 8280 for (++i; i != e; ++i) 8281 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8282 8283 const SCEV *FoldedRec = 8284 getAddRecExpr(NewOps, AddRec->getLoop(), 8285 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8286 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8287 // The addrec may be folded to a nonrecurrence, for example, if the 8288 // induction variable is multiplied by zero after constant folding. Go 8289 // ahead and return the folded value. 8290 if (!AddRec) 8291 return FoldedRec; 8292 break; 8293 } 8294 8295 // If the scope is outside the addrec's loop, evaluate it by using the 8296 // loop exit value of the addrec. 8297 if (!AddRec->getLoop()->contains(L)) { 8298 // To evaluate this recurrence, we need to know how many times the AddRec 8299 // loop iterates. Compute this now. 8300 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8301 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8302 8303 // Then, evaluate the AddRec. 8304 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8305 } 8306 8307 return AddRec; 8308 } 8309 8310 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8311 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8312 if (Op == Cast->getOperand()) 8313 return Cast; // must be loop invariant 8314 return getZeroExtendExpr(Op, Cast->getType()); 8315 } 8316 8317 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8318 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8319 if (Op == Cast->getOperand()) 8320 return Cast; // must be loop invariant 8321 return getSignExtendExpr(Op, Cast->getType()); 8322 } 8323 8324 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8325 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8326 if (Op == Cast->getOperand()) 8327 return Cast; // must be loop invariant 8328 return getTruncateExpr(Op, Cast->getType()); 8329 } 8330 8331 llvm_unreachable("Unknown SCEV type!"); 8332 } 8333 8334 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8335 return getSCEVAtScope(getSCEV(V), L); 8336 } 8337 8338 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8339 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8340 return stripInjectiveFunctions(ZExt->getOperand()); 8341 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8342 return stripInjectiveFunctions(SExt->getOperand()); 8343 return S; 8344 } 8345 8346 /// Finds the minimum unsigned root of the following equation: 8347 /// 8348 /// A * X = B (mod N) 8349 /// 8350 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8351 /// A and B isn't important. 8352 /// 8353 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8354 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8355 ScalarEvolution &SE) { 8356 uint32_t BW = A.getBitWidth(); 8357 assert(BW == SE.getTypeSizeInBits(B->getType())); 8358 assert(A != 0 && "A must be non-zero."); 8359 8360 // 1. D = gcd(A, N) 8361 // 8362 // The gcd of A and N may have only one prime factor: 2. The number of 8363 // trailing zeros in A is its multiplicity 8364 uint32_t Mult2 = A.countTrailingZeros(); 8365 // D = 2^Mult2 8366 8367 // 2. Check if B is divisible by D. 8368 // 8369 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8370 // is not less than multiplicity of this prime factor for D. 8371 if (SE.GetMinTrailingZeros(B) < Mult2) 8372 return SE.getCouldNotCompute(); 8373 8374 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8375 // modulo (N / D). 8376 // 8377 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8378 // (N / D) in general. The inverse itself always fits into BW bits, though, 8379 // so we immediately truncate it. 8380 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8381 APInt Mod(BW + 1, 0); 8382 Mod.setBit(BW - Mult2); // Mod = N / D 8383 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8384 8385 // 4. Compute the minimum unsigned root of the equation: 8386 // I * (B / D) mod (N / D) 8387 // To simplify the computation, we factor out the divide by D: 8388 // (I * B mod N) / D 8389 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8390 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8391 } 8392 8393 /// For a given quadratic addrec, generate coefficients of the corresponding 8394 /// quadratic equation, multiplied by a common value to ensure that they are 8395 /// integers. 8396 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8397 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8398 /// were multiplied by, and BitWidth is the bit width of the original addrec 8399 /// coefficients. 8400 /// This function returns None if the addrec coefficients are not compile- 8401 /// time constants. 8402 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8403 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8404 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8405 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8406 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8407 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8408 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8409 << *AddRec << '\n'); 8410 8411 // We currently can only solve this if the coefficients are constants. 8412 if (!LC || !MC || !NC) { 8413 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8414 return None; 8415 } 8416 8417 APInt L = LC->getAPInt(); 8418 APInt M = MC->getAPInt(); 8419 APInt N = NC->getAPInt(); 8420 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8421 8422 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8423 unsigned NewWidth = BitWidth + 1; 8424 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8425 << BitWidth << '\n'); 8426 // The sign-extension (as opposed to a zero-extension) here matches the 8427 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8428 N = N.sext(NewWidth); 8429 M = M.sext(NewWidth); 8430 L = L.sext(NewWidth); 8431 8432 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8433 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8434 // L+M, L+2M+N, L+3M+3N, ... 8435 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8436 // 8437 // The equation Acc = 0 is then 8438 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8439 // In a quadratic form it becomes: 8440 // N n^2 + (2M-N) n + 2L = 0. 8441 8442 APInt A = N; 8443 APInt B = 2 * M - A; 8444 APInt C = 2 * L; 8445 APInt T = APInt(NewWidth, 2); 8446 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8447 << "x + " << C << ", coeff bw: " << NewWidth 8448 << ", multiplied by " << T << '\n'); 8449 return std::make_tuple(A, B, C, T, BitWidth); 8450 } 8451 8452 /// Helper function to compare optional APInts: 8453 /// (a) if X and Y both exist, return min(X, Y), 8454 /// (b) if neither X nor Y exist, return None, 8455 /// (c) if exactly one of X and Y exists, return that value. 8456 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8457 if (X.hasValue() && Y.hasValue()) { 8458 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8459 APInt XW = X->sextOrSelf(W); 8460 APInt YW = Y->sextOrSelf(W); 8461 return XW.slt(YW) ? *X : *Y; 8462 } 8463 if (!X.hasValue() && !Y.hasValue()) 8464 return None; 8465 return X.hasValue() ? *X : *Y; 8466 } 8467 8468 /// Helper function to truncate an optional APInt to a given BitWidth. 8469 /// When solving addrec-related equations, it is preferable to return a value 8470 /// that has the same bit width as the original addrec's coefficients. If the 8471 /// solution fits in the original bit width, truncate it (except for i1). 8472 /// Returning a value of a different bit width may inhibit some optimizations. 8473 /// 8474 /// In general, a solution to a quadratic equation generated from an addrec 8475 /// may require BW+1 bits, where BW is the bit width of the addrec's 8476 /// coefficients. The reason is that the coefficients of the quadratic 8477 /// equation are BW+1 bits wide (to avoid truncation when converting from 8478 /// the addrec to the equation). 8479 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8480 if (!X.hasValue()) 8481 return None; 8482 unsigned W = X->getBitWidth(); 8483 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8484 return X->trunc(BitWidth); 8485 return X; 8486 } 8487 8488 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8489 /// iterations. The values L, M, N are assumed to be signed, and they 8490 /// should all have the same bit widths. 8491 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8492 /// where BW is the bit width of the addrec's coefficients. 8493 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8494 /// returned as such, otherwise the bit width of the returned value may 8495 /// be greater than BW. 8496 /// 8497 /// This function returns None if 8498 /// (a) the addrec coefficients are not constant, or 8499 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8500 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8501 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8502 static Optional<APInt> 8503 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8504 APInt A, B, C, M; 8505 unsigned BitWidth; 8506 auto T = GetQuadraticEquation(AddRec); 8507 if (!T.hasValue()) 8508 return None; 8509 8510 std::tie(A, B, C, M, BitWidth) = *T; 8511 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8512 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8513 if (!X.hasValue()) 8514 return None; 8515 8516 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8517 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8518 if (!V->isZero()) 8519 return None; 8520 8521 return TruncIfPossible(X, BitWidth); 8522 } 8523 8524 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8525 /// iterations. The values M, N are assumed to be signed, and they 8526 /// should all have the same bit widths. 8527 /// Find the least n such that c(n) does not belong to the given range, 8528 /// while c(n-1) does. 8529 /// 8530 /// This function returns None if 8531 /// (a) the addrec coefficients are not constant, or 8532 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8533 /// bounds of the range. 8534 static Optional<APInt> 8535 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8536 const ConstantRange &Range, ScalarEvolution &SE) { 8537 assert(AddRec->getOperand(0)->isZero() && 8538 "Starting value of addrec should be 0"); 8539 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8540 << Range << ", addrec " << *AddRec << '\n'); 8541 // This case is handled in getNumIterationsInRange. Here we can assume that 8542 // we start in the range. 8543 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8544 "Addrec's initial value should be in range"); 8545 8546 APInt A, B, C, M; 8547 unsigned BitWidth; 8548 auto T = GetQuadraticEquation(AddRec); 8549 if (!T.hasValue()) 8550 return None; 8551 8552 // Be careful about the return value: there can be two reasons for not 8553 // returning an actual number. First, if no solutions to the equations 8554 // were found, and second, if the solutions don't leave the given range. 8555 // The first case means that the actual solution is "unknown", the second 8556 // means that it's known, but not valid. If the solution is unknown, we 8557 // cannot make any conclusions. 8558 // Return a pair: the optional solution and a flag indicating if the 8559 // solution was found. 8560 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8561 // Solve for signed overflow and unsigned overflow, pick the lower 8562 // solution. 8563 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8564 << Bound << " (before multiplying by " << M << ")\n"); 8565 Bound *= M; // The quadratic equation multiplier. 8566 8567 Optional<APInt> SO = None; 8568 if (BitWidth > 1) { 8569 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8570 "signed overflow\n"); 8571 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8572 } 8573 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8574 "unsigned overflow\n"); 8575 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8576 BitWidth+1); 8577 8578 auto LeavesRange = [&] (const APInt &X) { 8579 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8580 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8581 if (Range.contains(V0->getValue())) 8582 return false; 8583 // X should be at least 1, so X-1 is non-negative. 8584 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8585 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8586 if (Range.contains(V1->getValue())) 8587 return true; 8588 return false; 8589 }; 8590 8591 // If SolveQuadraticEquationWrap returns None, it means that there can 8592 // be a solution, but the function failed to find it. We cannot treat it 8593 // as "no solution". 8594 if (!SO.hasValue() || !UO.hasValue()) 8595 return { None, false }; 8596 8597 // Check the smaller value first to see if it leaves the range. 8598 // At this point, both SO and UO must have values. 8599 Optional<APInt> Min = MinOptional(SO, UO); 8600 if (LeavesRange(*Min)) 8601 return { Min, true }; 8602 Optional<APInt> Max = Min == SO ? UO : SO; 8603 if (LeavesRange(*Max)) 8604 return { Max, true }; 8605 8606 // Solutions were found, but were eliminated, hence the "true". 8607 return { None, true }; 8608 }; 8609 8610 std::tie(A, B, C, M, BitWidth) = *T; 8611 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8612 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8613 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8614 auto SL = SolveForBoundary(Lower); 8615 auto SU = SolveForBoundary(Upper); 8616 // If any of the solutions was unknown, no meaninigful conclusions can 8617 // be made. 8618 if (!SL.second || !SU.second) 8619 return None; 8620 8621 // Claim: The correct solution is not some value between Min and Max. 8622 // 8623 // Justification: Assuming that Min and Max are different values, one of 8624 // them is when the first signed overflow happens, the other is when the 8625 // first unsigned overflow happens. Crossing the range boundary is only 8626 // possible via an overflow (treating 0 as a special case of it, modeling 8627 // an overflow as crossing k*2^W for some k). 8628 // 8629 // The interesting case here is when Min was eliminated as an invalid 8630 // solution, but Max was not. The argument is that if there was another 8631 // overflow between Min and Max, it would also have been eliminated if 8632 // it was considered. 8633 // 8634 // For a given boundary, it is possible to have two overflows of the same 8635 // type (signed/unsigned) without having the other type in between: this 8636 // can happen when the vertex of the parabola is between the iterations 8637 // corresponding to the overflows. This is only possible when the two 8638 // overflows cross k*2^W for the same k. In such case, if the second one 8639 // left the range (and was the first one to do so), the first overflow 8640 // would have to enter the range, which would mean that either we had left 8641 // the range before or that we started outside of it. Both of these cases 8642 // are contradictions. 8643 // 8644 // Claim: In the case where SolveForBoundary returns None, the correct 8645 // solution is not some value between the Max for this boundary and the 8646 // Min of the other boundary. 8647 // 8648 // Justification: Assume that we had such Max_A and Min_B corresponding 8649 // to range boundaries A and B and such that Max_A < Min_B. If there was 8650 // a solution between Max_A and Min_B, it would have to be caused by an 8651 // overflow corresponding to either A or B. It cannot correspond to B, 8652 // since Min_B is the first occurrence of such an overflow. If it 8653 // corresponded to A, it would have to be either a signed or an unsigned 8654 // overflow that is larger than both eliminated overflows for A. But 8655 // between the eliminated overflows and this overflow, the values would 8656 // cover the entire value space, thus crossing the other boundary, which 8657 // is a contradiction. 8658 8659 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8660 } 8661 8662 ScalarEvolution::ExitLimit 8663 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8664 bool AllowPredicates) { 8665 8666 // This is only used for loops with a "x != y" exit test. The exit condition 8667 // is now expressed as a single expression, V = x-y. So the exit test is 8668 // effectively V != 0. We know and take advantage of the fact that this 8669 // expression only being used in a comparison by zero context. 8670 8671 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8672 // If the value is a constant 8673 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8674 // If the value is already zero, the branch will execute zero times. 8675 if (C->getValue()->isZero()) return C; 8676 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8677 } 8678 8679 const SCEVAddRecExpr *AddRec = 8680 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8681 8682 if (!AddRec && AllowPredicates) 8683 // Try to make this an AddRec using runtime tests, in the first X 8684 // iterations of this loop, where X is the SCEV expression found by the 8685 // algorithm below. 8686 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8687 8688 if (!AddRec || AddRec->getLoop() != L) 8689 return getCouldNotCompute(); 8690 8691 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8692 // the quadratic equation to solve it. 8693 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8694 // We can only use this value if the chrec ends up with an exact zero 8695 // value at this index. When solving for "X*X != 5", for example, we 8696 // should not accept a root of 2. 8697 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8698 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8699 return ExitLimit(R, R, false, Predicates); 8700 } 8701 return getCouldNotCompute(); 8702 } 8703 8704 // Otherwise we can only handle this if it is affine. 8705 if (!AddRec->isAffine()) 8706 return getCouldNotCompute(); 8707 8708 // If this is an affine expression, the execution count of this branch is 8709 // the minimum unsigned root of the following equation: 8710 // 8711 // Start + Step*N = 0 (mod 2^BW) 8712 // 8713 // equivalent to: 8714 // 8715 // Step*N = -Start (mod 2^BW) 8716 // 8717 // where BW is the common bit width of Start and Step. 8718 8719 // Get the initial value for the loop. 8720 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8721 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8722 8723 // For now we handle only constant steps. 8724 // 8725 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8726 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8727 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8728 // We have not yet seen any such cases. 8729 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8730 if (!StepC || StepC->getValue()->isZero()) 8731 return getCouldNotCompute(); 8732 8733 // For positive steps (counting up until unsigned overflow): 8734 // N = -Start/Step (as unsigned) 8735 // For negative steps (counting down to zero): 8736 // N = Start/-Step 8737 // First compute the unsigned distance from zero in the direction of Step. 8738 bool CountDown = StepC->getAPInt().isNegative(); 8739 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8740 8741 // Handle unitary steps, which cannot wraparound. 8742 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8743 // N = Distance (as unsigned) 8744 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8745 APInt MaxBECount = getUnsignedRangeMax(Distance); 8746 8747 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8748 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8749 // case, and see if we can improve the bound. 8750 // 8751 // Explicitly handling this here is necessary because getUnsignedRange 8752 // isn't context-sensitive; it doesn't know that we only care about the 8753 // range inside the loop. 8754 const SCEV *Zero = getZero(Distance->getType()); 8755 const SCEV *One = getOne(Distance->getType()); 8756 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8757 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8758 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8759 // as "unsigned_max(Distance + 1) - 1". 8760 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8761 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8762 } 8763 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8764 } 8765 8766 // If the condition controls loop exit (the loop exits only if the expression 8767 // is true) and the addition is no-wrap we can use unsigned divide to 8768 // compute the backedge count. In this case, the step may not divide the 8769 // distance, but we don't care because if the condition is "missed" the loop 8770 // will have undefined behavior due to wrapping. 8771 if (ControlsExit && AddRec->hasNoSelfWrap() && 8772 loopHasNoAbnormalExits(AddRec->getLoop())) { 8773 const SCEV *Exact = 8774 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8775 const SCEV *Max = 8776 Exact == getCouldNotCompute() 8777 ? Exact 8778 : getConstant(getUnsignedRangeMax(Exact)); 8779 return ExitLimit(Exact, Max, false, Predicates); 8780 } 8781 8782 // Solve the general equation. 8783 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8784 getNegativeSCEV(Start), *this); 8785 const SCEV *M = E == getCouldNotCompute() 8786 ? E 8787 : getConstant(getUnsignedRangeMax(E)); 8788 return ExitLimit(E, M, false, Predicates); 8789 } 8790 8791 ScalarEvolution::ExitLimit 8792 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8793 // Loops that look like: while (X == 0) are very strange indeed. We don't 8794 // handle them yet except for the trivial case. This could be expanded in the 8795 // future as needed. 8796 8797 // If the value is a constant, check to see if it is known to be non-zero 8798 // already. If so, the backedge will execute zero times. 8799 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8800 if (!C->getValue()->isZero()) 8801 return getZero(C->getType()); 8802 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8803 } 8804 8805 // We could implement others, but I really doubt anyone writes loops like 8806 // this, and if they did, they would already be constant folded. 8807 return getCouldNotCompute(); 8808 } 8809 8810 std::pair<BasicBlock *, BasicBlock *> 8811 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8812 // If the block has a unique predecessor, then there is no path from the 8813 // predecessor to the block that does not go through the direct edge 8814 // from the predecessor to the block. 8815 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8816 return {Pred, BB}; 8817 8818 // A loop's header is defined to be a block that dominates the loop. 8819 // If the header has a unique predecessor outside the loop, it must be 8820 // a block that has exactly one successor that can reach the loop. 8821 if (Loop *L = LI.getLoopFor(BB)) 8822 return {L->getLoopPredecessor(), L->getHeader()}; 8823 8824 return {nullptr, nullptr}; 8825 } 8826 8827 /// SCEV structural equivalence is usually sufficient for testing whether two 8828 /// expressions are equal, however for the purposes of looking for a condition 8829 /// guarding a loop, it can be useful to be a little more general, since a 8830 /// front-end may have replicated the controlling expression. 8831 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8832 // Quick check to see if they are the same SCEV. 8833 if (A == B) return true; 8834 8835 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8836 // Not all instructions that are "identical" compute the same value. For 8837 // instance, two distinct alloca instructions allocating the same type are 8838 // identical and do not read memory; but compute distinct values. 8839 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8840 }; 8841 8842 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8843 // two different instructions with the same value. Check for this case. 8844 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8845 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8846 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8847 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8848 if (ComputesEqualValues(AI, BI)) 8849 return true; 8850 8851 // Otherwise assume they may have a different value. 8852 return false; 8853 } 8854 8855 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8856 const SCEV *&LHS, const SCEV *&RHS, 8857 unsigned Depth) { 8858 bool Changed = false; 8859 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8860 // '0 != 0'. 8861 auto TrivialCase = [&](bool TriviallyTrue) { 8862 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8863 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8864 return true; 8865 }; 8866 // If we hit the max recursion limit bail out. 8867 if (Depth >= 3) 8868 return false; 8869 8870 // Canonicalize a constant to the right side. 8871 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8872 // Check for both operands constant. 8873 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8874 if (ConstantExpr::getICmp(Pred, 8875 LHSC->getValue(), 8876 RHSC->getValue())->isNullValue()) 8877 return TrivialCase(false); 8878 else 8879 return TrivialCase(true); 8880 } 8881 // Otherwise swap the operands to put the constant on the right. 8882 std::swap(LHS, RHS); 8883 Pred = ICmpInst::getSwappedPredicate(Pred); 8884 Changed = true; 8885 } 8886 8887 // If we're comparing an addrec with a value which is loop-invariant in the 8888 // addrec's loop, put the addrec on the left. Also make a dominance check, 8889 // as both operands could be addrecs loop-invariant in each other's loop. 8890 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8891 const Loop *L = AR->getLoop(); 8892 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8893 std::swap(LHS, RHS); 8894 Pred = ICmpInst::getSwappedPredicate(Pred); 8895 Changed = true; 8896 } 8897 } 8898 8899 // If there's a constant operand, canonicalize comparisons with boundary 8900 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8901 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8902 const APInt &RA = RC->getAPInt(); 8903 8904 bool SimplifiedByConstantRange = false; 8905 8906 if (!ICmpInst::isEquality(Pred)) { 8907 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8908 if (ExactCR.isFullSet()) 8909 return TrivialCase(true); 8910 else if (ExactCR.isEmptySet()) 8911 return TrivialCase(false); 8912 8913 APInt NewRHS; 8914 CmpInst::Predicate NewPred; 8915 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8916 ICmpInst::isEquality(NewPred)) { 8917 // We were able to convert an inequality to an equality. 8918 Pred = NewPred; 8919 RHS = getConstant(NewRHS); 8920 Changed = SimplifiedByConstantRange = true; 8921 } 8922 } 8923 8924 if (!SimplifiedByConstantRange) { 8925 switch (Pred) { 8926 default: 8927 break; 8928 case ICmpInst::ICMP_EQ: 8929 case ICmpInst::ICMP_NE: 8930 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8931 if (!RA) 8932 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8933 if (const SCEVMulExpr *ME = 8934 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8935 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8936 ME->getOperand(0)->isAllOnesValue()) { 8937 RHS = AE->getOperand(1); 8938 LHS = ME->getOperand(1); 8939 Changed = true; 8940 } 8941 break; 8942 8943 8944 // The "Should have been caught earlier!" messages refer to the fact 8945 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8946 // should have fired on the corresponding cases, and canonicalized the 8947 // check to trivial case. 8948 8949 case ICmpInst::ICMP_UGE: 8950 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8951 Pred = ICmpInst::ICMP_UGT; 8952 RHS = getConstant(RA - 1); 8953 Changed = true; 8954 break; 8955 case ICmpInst::ICMP_ULE: 8956 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8957 Pred = ICmpInst::ICMP_ULT; 8958 RHS = getConstant(RA + 1); 8959 Changed = true; 8960 break; 8961 case ICmpInst::ICMP_SGE: 8962 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8963 Pred = ICmpInst::ICMP_SGT; 8964 RHS = getConstant(RA - 1); 8965 Changed = true; 8966 break; 8967 case ICmpInst::ICMP_SLE: 8968 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8969 Pred = ICmpInst::ICMP_SLT; 8970 RHS = getConstant(RA + 1); 8971 Changed = true; 8972 break; 8973 } 8974 } 8975 } 8976 8977 // Check for obvious equality. 8978 if (HasSameValue(LHS, RHS)) { 8979 if (ICmpInst::isTrueWhenEqual(Pred)) 8980 return TrivialCase(true); 8981 if (ICmpInst::isFalseWhenEqual(Pred)) 8982 return TrivialCase(false); 8983 } 8984 8985 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8986 // adding or subtracting 1 from one of the operands. 8987 switch (Pred) { 8988 case ICmpInst::ICMP_SLE: 8989 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8990 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8991 SCEV::FlagNSW); 8992 Pred = ICmpInst::ICMP_SLT; 8993 Changed = true; 8994 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8995 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8996 SCEV::FlagNSW); 8997 Pred = ICmpInst::ICMP_SLT; 8998 Changed = true; 8999 } 9000 break; 9001 case ICmpInst::ICMP_SGE: 9002 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9003 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9004 SCEV::FlagNSW); 9005 Pred = ICmpInst::ICMP_SGT; 9006 Changed = true; 9007 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9008 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9009 SCEV::FlagNSW); 9010 Pred = ICmpInst::ICMP_SGT; 9011 Changed = true; 9012 } 9013 break; 9014 case ICmpInst::ICMP_ULE: 9015 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9016 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9017 SCEV::FlagNUW); 9018 Pred = ICmpInst::ICMP_ULT; 9019 Changed = true; 9020 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9021 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9022 Pred = ICmpInst::ICMP_ULT; 9023 Changed = true; 9024 } 9025 break; 9026 case ICmpInst::ICMP_UGE: 9027 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9028 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9029 Pred = ICmpInst::ICMP_UGT; 9030 Changed = true; 9031 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9032 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9033 SCEV::FlagNUW); 9034 Pred = ICmpInst::ICMP_UGT; 9035 Changed = true; 9036 } 9037 break; 9038 default: 9039 break; 9040 } 9041 9042 // TODO: More simplifications are possible here. 9043 9044 // Recursively simplify until we either hit a recursion limit or nothing 9045 // changes. 9046 if (Changed) 9047 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9048 9049 return Changed; 9050 } 9051 9052 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9053 return getSignedRangeMax(S).isNegative(); 9054 } 9055 9056 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9057 return getSignedRangeMin(S).isStrictlyPositive(); 9058 } 9059 9060 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9061 return !getSignedRangeMin(S).isNegative(); 9062 } 9063 9064 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9065 return !getSignedRangeMax(S).isStrictlyPositive(); 9066 } 9067 9068 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9069 return isKnownNegative(S) || isKnownPositive(S); 9070 } 9071 9072 std::pair<const SCEV *, const SCEV *> 9073 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9074 // Compute SCEV on entry of loop L. 9075 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9076 if (Start == getCouldNotCompute()) 9077 return { Start, Start }; 9078 // Compute post increment SCEV for loop L. 9079 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9080 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9081 return { Start, PostInc }; 9082 } 9083 9084 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9085 const SCEV *LHS, const SCEV *RHS) { 9086 // First collect all loops. 9087 SmallPtrSet<const Loop *, 8> LoopsUsed; 9088 getUsedLoops(LHS, LoopsUsed); 9089 getUsedLoops(RHS, LoopsUsed); 9090 9091 if (LoopsUsed.empty()) 9092 return false; 9093 9094 // Domination relationship must be a linear order on collected loops. 9095 #ifndef NDEBUG 9096 for (auto *L1 : LoopsUsed) 9097 for (auto *L2 : LoopsUsed) 9098 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9099 DT.dominates(L2->getHeader(), L1->getHeader())) && 9100 "Domination relationship is not a linear order"); 9101 #endif 9102 9103 const Loop *MDL = 9104 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9105 [&](const Loop *L1, const Loop *L2) { 9106 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9107 }); 9108 9109 // Get init and post increment value for LHS. 9110 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9111 // if LHS contains unknown non-invariant SCEV then bail out. 9112 if (SplitLHS.first == getCouldNotCompute()) 9113 return false; 9114 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9115 // Get init and post increment value for RHS. 9116 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9117 // if RHS contains unknown non-invariant SCEV then bail out. 9118 if (SplitRHS.first == getCouldNotCompute()) 9119 return false; 9120 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9121 // It is possible that init SCEV contains an invariant load but it does 9122 // not dominate MDL and is not available at MDL loop entry, so we should 9123 // check it here. 9124 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9125 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9126 return false; 9127 9128 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 9129 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9130 SplitRHS.second); 9131 } 9132 9133 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9134 const SCEV *LHS, const SCEV *RHS) { 9135 // Canonicalize the inputs first. 9136 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9137 9138 if (isKnownViaInduction(Pred, LHS, RHS)) 9139 return true; 9140 9141 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9142 return true; 9143 9144 // Otherwise see what can be done with some simple reasoning. 9145 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9146 } 9147 9148 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9149 const SCEVAddRecExpr *LHS, 9150 const SCEV *RHS) { 9151 const Loop *L = LHS->getLoop(); 9152 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9153 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9154 } 9155 9156 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9157 ICmpInst::Predicate Pred, 9158 bool &Increasing) { 9159 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9160 9161 #ifndef NDEBUG 9162 // Verify an invariant: inverting the predicate should turn a monotonically 9163 // increasing change to a monotonically decreasing one, and vice versa. 9164 bool IncreasingSwapped; 9165 bool ResultSwapped = isMonotonicPredicateImpl( 9166 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9167 9168 assert(Result == ResultSwapped && "should be able to analyze both!"); 9169 if (ResultSwapped) 9170 assert(Increasing == !IncreasingSwapped && 9171 "monotonicity should flip as we flip the predicate"); 9172 #endif 9173 9174 return Result; 9175 } 9176 9177 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9178 ICmpInst::Predicate Pred, 9179 bool &Increasing) { 9180 9181 // A zero step value for LHS means the induction variable is essentially a 9182 // loop invariant value. We don't really depend on the predicate actually 9183 // flipping from false to true (for increasing predicates, and the other way 9184 // around for decreasing predicates), all we care about is that *if* the 9185 // predicate changes then it only changes from false to true. 9186 // 9187 // A zero step value in itself is not very useful, but there may be places 9188 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9189 // as general as possible. 9190 9191 switch (Pred) { 9192 default: 9193 return false; // Conservative answer 9194 9195 case ICmpInst::ICMP_UGT: 9196 case ICmpInst::ICMP_UGE: 9197 case ICmpInst::ICMP_ULT: 9198 case ICmpInst::ICMP_ULE: 9199 if (!LHS->hasNoUnsignedWrap()) 9200 return false; 9201 9202 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9203 return true; 9204 9205 case ICmpInst::ICMP_SGT: 9206 case ICmpInst::ICMP_SGE: 9207 case ICmpInst::ICMP_SLT: 9208 case ICmpInst::ICMP_SLE: { 9209 if (!LHS->hasNoSignedWrap()) 9210 return false; 9211 9212 const SCEV *Step = LHS->getStepRecurrence(*this); 9213 9214 if (isKnownNonNegative(Step)) { 9215 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9216 return true; 9217 } 9218 9219 if (isKnownNonPositive(Step)) { 9220 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9221 return true; 9222 } 9223 9224 return false; 9225 } 9226 9227 } 9228 9229 llvm_unreachable("switch has default clause!"); 9230 } 9231 9232 bool ScalarEvolution::isLoopInvariantPredicate( 9233 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9234 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9235 const SCEV *&InvariantRHS) { 9236 9237 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9238 if (!isLoopInvariant(RHS, L)) { 9239 if (!isLoopInvariant(LHS, L)) 9240 return false; 9241 9242 std::swap(LHS, RHS); 9243 Pred = ICmpInst::getSwappedPredicate(Pred); 9244 } 9245 9246 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9247 if (!ArLHS || ArLHS->getLoop() != L) 9248 return false; 9249 9250 bool Increasing; 9251 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9252 return false; 9253 9254 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9255 // true as the loop iterates, and the backedge is control dependent on 9256 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9257 // 9258 // * if the predicate was false in the first iteration then the predicate 9259 // is never evaluated again, since the loop exits without taking the 9260 // backedge. 9261 // * if the predicate was true in the first iteration then it will 9262 // continue to be true for all future iterations since it is 9263 // monotonically increasing. 9264 // 9265 // For both the above possibilities, we can replace the loop varying 9266 // predicate with its value on the first iteration of the loop (which is 9267 // loop invariant). 9268 // 9269 // A similar reasoning applies for a monotonically decreasing predicate, by 9270 // replacing true with false and false with true in the above two bullets. 9271 9272 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9273 9274 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9275 return false; 9276 9277 InvariantPred = Pred; 9278 InvariantLHS = ArLHS->getStart(); 9279 InvariantRHS = RHS; 9280 return true; 9281 } 9282 9283 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9284 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9285 if (HasSameValue(LHS, RHS)) 9286 return ICmpInst::isTrueWhenEqual(Pred); 9287 9288 // This code is split out from isKnownPredicate because it is called from 9289 // within isLoopEntryGuardedByCond. 9290 9291 auto CheckRanges = 9292 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9293 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9294 .contains(RangeLHS); 9295 }; 9296 9297 // The check at the top of the function catches the case where the values are 9298 // known to be equal. 9299 if (Pred == CmpInst::ICMP_EQ) 9300 return false; 9301 9302 if (Pred == CmpInst::ICMP_NE) 9303 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9304 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9305 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9306 9307 if (CmpInst::isSigned(Pred)) 9308 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9309 9310 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9311 } 9312 9313 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9314 const SCEV *LHS, 9315 const SCEV *RHS) { 9316 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9317 // Return Y via OutY. 9318 auto MatchBinaryAddToConst = 9319 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9320 SCEV::NoWrapFlags ExpectedFlags) { 9321 const SCEV *NonConstOp, *ConstOp; 9322 SCEV::NoWrapFlags FlagsPresent; 9323 9324 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9325 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9326 return false; 9327 9328 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9329 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9330 }; 9331 9332 APInt C; 9333 9334 switch (Pred) { 9335 default: 9336 break; 9337 9338 case ICmpInst::ICMP_SGE: 9339 std::swap(LHS, RHS); 9340 LLVM_FALLTHROUGH; 9341 case ICmpInst::ICMP_SLE: 9342 // X s<= (X + C)<nsw> if C >= 0 9343 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9344 return true; 9345 9346 // (X + C)<nsw> s<= X if C <= 0 9347 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9348 !C.isStrictlyPositive()) 9349 return true; 9350 break; 9351 9352 case ICmpInst::ICMP_SGT: 9353 std::swap(LHS, RHS); 9354 LLVM_FALLTHROUGH; 9355 case ICmpInst::ICMP_SLT: 9356 // X s< (X + C)<nsw> if C > 0 9357 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9358 C.isStrictlyPositive()) 9359 return true; 9360 9361 // (X + C)<nsw> s< X if C < 0 9362 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9363 return true; 9364 break; 9365 } 9366 9367 return false; 9368 } 9369 9370 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9371 const SCEV *LHS, 9372 const SCEV *RHS) { 9373 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9374 return false; 9375 9376 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9377 // the stack can result in exponential time complexity. 9378 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9379 9380 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9381 // 9382 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9383 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9384 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9385 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9386 // use isKnownPredicate later if needed. 9387 return isKnownNonNegative(RHS) && 9388 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9389 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9390 } 9391 9392 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9393 ICmpInst::Predicate Pred, 9394 const SCEV *LHS, const SCEV *RHS) { 9395 // No need to even try if we know the module has no guards. 9396 if (!HasGuards) 9397 return false; 9398 9399 return any_of(*BB, [&](Instruction &I) { 9400 using namespace llvm::PatternMatch; 9401 9402 Value *Condition; 9403 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9404 m_Value(Condition))) && 9405 isImpliedCond(Pred, LHS, RHS, Condition, false); 9406 }); 9407 } 9408 9409 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9410 /// protected by a conditional between LHS and RHS. This is used to 9411 /// to eliminate casts. 9412 bool 9413 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9414 ICmpInst::Predicate Pred, 9415 const SCEV *LHS, const SCEV *RHS) { 9416 // Interpret a null as meaning no loop, where there is obviously no guard 9417 // (interprocedural conditions notwithstanding). 9418 if (!L) return true; 9419 9420 if (VerifyIR) 9421 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9422 "This cannot be done on broken IR!"); 9423 9424 9425 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9426 return true; 9427 9428 BasicBlock *Latch = L->getLoopLatch(); 9429 if (!Latch) 9430 return false; 9431 9432 BranchInst *LoopContinuePredicate = 9433 dyn_cast<BranchInst>(Latch->getTerminator()); 9434 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9435 isImpliedCond(Pred, LHS, RHS, 9436 LoopContinuePredicate->getCondition(), 9437 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9438 return true; 9439 9440 // We don't want more than one activation of the following loops on the stack 9441 // -- that can lead to O(n!) time complexity. 9442 if (WalkingBEDominatingConds) 9443 return false; 9444 9445 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9446 9447 // See if we can exploit a trip count to prove the predicate. 9448 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9449 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9450 if (LatchBECount != getCouldNotCompute()) { 9451 // We know that Latch branches back to the loop header exactly 9452 // LatchBECount times. This means the backdege condition at Latch is 9453 // equivalent to "{0,+,1} u< LatchBECount". 9454 Type *Ty = LatchBECount->getType(); 9455 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9456 const SCEV *LoopCounter = 9457 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9458 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9459 LatchBECount)) 9460 return true; 9461 } 9462 9463 // Check conditions due to any @llvm.assume intrinsics. 9464 for (auto &AssumeVH : AC.assumptions()) { 9465 if (!AssumeVH) 9466 continue; 9467 auto *CI = cast<CallInst>(AssumeVH); 9468 if (!DT.dominates(CI, Latch->getTerminator())) 9469 continue; 9470 9471 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9472 return true; 9473 } 9474 9475 // If the loop is not reachable from the entry block, we risk running into an 9476 // infinite loop as we walk up into the dom tree. These loops do not matter 9477 // anyway, so we just return a conservative answer when we see them. 9478 if (!DT.isReachableFromEntry(L->getHeader())) 9479 return false; 9480 9481 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9482 return true; 9483 9484 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9485 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9486 assert(DTN && "should reach the loop header before reaching the root!"); 9487 9488 BasicBlock *BB = DTN->getBlock(); 9489 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9490 return true; 9491 9492 BasicBlock *PBB = BB->getSinglePredecessor(); 9493 if (!PBB) 9494 continue; 9495 9496 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9497 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9498 continue; 9499 9500 Value *Condition = ContinuePredicate->getCondition(); 9501 9502 // If we have an edge `E` within the loop body that dominates the only 9503 // latch, the condition guarding `E` also guards the backedge. This 9504 // reasoning works only for loops with a single latch. 9505 9506 BasicBlockEdge DominatingEdge(PBB, BB); 9507 if (DominatingEdge.isSingleEdge()) { 9508 // We're constructively (and conservatively) enumerating edges within the 9509 // loop body that dominate the latch. The dominator tree better agree 9510 // with us on this: 9511 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9512 9513 if (isImpliedCond(Pred, LHS, RHS, Condition, 9514 BB != ContinuePredicate->getSuccessor(0))) 9515 return true; 9516 } 9517 } 9518 9519 return false; 9520 } 9521 9522 bool 9523 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9524 ICmpInst::Predicate Pred, 9525 const SCEV *LHS, const SCEV *RHS) { 9526 // Interpret a null as meaning no loop, where there is obviously no guard 9527 // (interprocedural conditions notwithstanding). 9528 if (!L) return false; 9529 9530 if (VerifyIR) 9531 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9532 "This cannot be done on broken IR!"); 9533 9534 // Both LHS and RHS must be available at loop entry. 9535 assert(isAvailableAtLoopEntry(LHS, L) && 9536 "LHS is not available at Loop Entry"); 9537 assert(isAvailableAtLoopEntry(RHS, L) && 9538 "RHS is not available at Loop Entry"); 9539 9540 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9541 return true; 9542 9543 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9544 // the facts (a >= b && a != b) separately. A typical situation is when the 9545 // non-strict comparison is known from ranges and non-equality is known from 9546 // dominating predicates. If we are proving strict comparison, we always try 9547 // to prove non-equality and non-strict comparison separately. 9548 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9549 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9550 bool ProvedNonStrictComparison = false; 9551 bool ProvedNonEquality = false; 9552 9553 if (ProvingStrictComparison) { 9554 ProvedNonStrictComparison = 9555 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9556 ProvedNonEquality = 9557 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9558 if (ProvedNonStrictComparison && ProvedNonEquality) 9559 return true; 9560 } 9561 9562 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9563 auto ProveViaGuard = [&](BasicBlock *Block) { 9564 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9565 return true; 9566 if (ProvingStrictComparison) { 9567 if (!ProvedNonStrictComparison) 9568 ProvedNonStrictComparison = 9569 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9570 if (!ProvedNonEquality) 9571 ProvedNonEquality = 9572 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9573 if (ProvedNonStrictComparison && ProvedNonEquality) 9574 return true; 9575 } 9576 return false; 9577 }; 9578 9579 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9580 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9581 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9582 return true; 9583 if (ProvingStrictComparison) { 9584 if (!ProvedNonStrictComparison) 9585 ProvedNonStrictComparison = 9586 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9587 if (!ProvedNonEquality) 9588 ProvedNonEquality = 9589 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9590 if (ProvedNonStrictComparison && ProvedNonEquality) 9591 return true; 9592 } 9593 return false; 9594 }; 9595 9596 // Starting at the loop predecessor, climb up the predecessor chain, as long 9597 // as there are predecessors that can be found that have unique successors 9598 // leading to the original header. 9599 for (std::pair<BasicBlock *, BasicBlock *> 9600 Pair(L->getLoopPredecessor(), L->getHeader()); 9601 Pair.first; 9602 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9603 9604 if (ProveViaGuard(Pair.first)) 9605 return true; 9606 9607 BranchInst *LoopEntryPredicate = 9608 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9609 if (!LoopEntryPredicate || 9610 LoopEntryPredicate->isUnconditional()) 9611 continue; 9612 9613 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9614 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9615 return true; 9616 } 9617 9618 // Check conditions due to any @llvm.assume intrinsics. 9619 for (auto &AssumeVH : AC.assumptions()) { 9620 if (!AssumeVH) 9621 continue; 9622 auto *CI = cast<CallInst>(AssumeVH); 9623 if (!DT.dominates(CI, L->getHeader())) 9624 continue; 9625 9626 if (ProveViaCond(CI->getArgOperand(0), false)) 9627 return true; 9628 } 9629 9630 return false; 9631 } 9632 9633 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9634 const SCEV *LHS, const SCEV *RHS, 9635 Value *FoundCondValue, 9636 bool Inverse) { 9637 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9638 return false; 9639 9640 auto ClearOnExit = 9641 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9642 9643 // Recursively handle And and Or conditions. 9644 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9645 if (BO->getOpcode() == Instruction::And) { 9646 if (!Inverse) 9647 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9648 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9649 } else if (BO->getOpcode() == Instruction::Or) { 9650 if (Inverse) 9651 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9652 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9653 } 9654 } 9655 9656 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9657 if (!ICI) return false; 9658 9659 // Now that we found a conditional branch that dominates the loop or controls 9660 // the loop latch. Check to see if it is the comparison we are looking for. 9661 ICmpInst::Predicate FoundPred; 9662 if (Inverse) 9663 FoundPred = ICI->getInversePredicate(); 9664 else 9665 FoundPred = ICI->getPredicate(); 9666 9667 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9668 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9669 9670 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9671 } 9672 9673 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9674 const SCEV *RHS, 9675 ICmpInst::Predicate FoundPred, 9676 const SCEV *FoundLHS, 9677 const SCEV *FoundRHS) { 9678 // Balance the types. 9679 if (getTypeSizeInBits(LHS->getType()) < 9680 getTypeSizeInBits(FoundLHS->getType())) { 9681 if (CmpInst::isSigned(Pred)) { 9682 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9683 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9684 } else { 9685 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9686 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9687 } 9688 } else if (getTypeSizeInBits(LHS->getType()) > 9689 getTypeSizeInBits(FoundLHS->getType())) { 9690 if (CmpInst::isSigned(FoundPred)) { 9691 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9692 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9693 } else { 9694 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9695 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9696 } 9697 } 9698 9699 // Canonicalize the query to match the way instcombine will have 9700 // canonicalized the comparison. 9701 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9702 if (LHS == RHS) 9703 return CmpInst::isTrueWhenEqual(Pred); 9704 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9705 if (FoundLHS == FoundRHS) 9706 return CmpInst::isFalseWhenEqual(FoundPred); 9707 9708 // Check to see if we can make the LHS or RHS match. 9709 if (LHS == FoundRHS || RHS == FoundLHS) { 9710 if (isa<SCEVConstant>(RHS)) { 9711 std::swap(FoundLHS, FoundRHS); 9712 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9713 } else { 9714 std::swap(LHS, RHS); 9715 Pred = ICmpInst::getSwappedPredicate(Pred); 9716 } 9717 } 9718 9719 // Check whether the found predicate is the same as the desired predicate. 9720 if (FoundPred == Pred) 9721 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9722 9723 // Check whether swapping the found predicate makes it the same as the 9724 // desired predicate. 9725 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9726 if (isa<SCEVConstant>(RHS)) 9727 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9728 else 9729 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9730 RHS, LHS, FoundLHS, FoundRHS); 9731 } 9732 9733 // Unsigned comparison is the same as signed comparison when both the operands 9734 // are non-negative. 9735 if (CmpInst::isUnsigned(FoundPred) && 9736 CmpInst::getSignedPredicate(FoundPred) == Pred && 9737 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9738 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9739 9740 // Check if we can make progress by sharpening ranges. 9741 if (FoundPred == ICmpInst::ICMP_NE && 9742 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9743 9744 const SCEVConstant *C = nullptr; 9745 const SCEV *V = nullptr; 9746 9747 if (isa<SCEVConstant>(FoundLHS)) { 9748 C = cast<SCEVConstant>(FoundLHS); 9749 V = FoundRHS; 9750 } else { 9751 C = cast<SCEVConstant>(FoundRHS); 9752 V = FoundLHS; 9753 } 9754 9755 // The guarding predicate tells us that C != V. If the known range 9756 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9757 // range we consider has to correspond to same signedness as the 9758 // predicate we're interested in folding. 9759 9760 APInt Min = ICmpInst::isSigned(Pred) ? 9761 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9762 9763 if (Min == C->getAPInt()) { 9764 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9765 // This is true even if (Min + 1) wraps around -- in case of 9766 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9767 9768 APInt SharperMin = Min + 1; 9769 9770 switch (Pred) { 9771 case ICmpInst::ICMP_SGE: 9772 case ICmpInst::ICMP_UGE: 9773 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9774 // RHS, we're done. 9775 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9776 getConstant(SharperMin))) 9777 return true; 9778 LLVM_FALLTHROUGH; 9779 9780 case ICmpInst::ICMP_SGT: 9781 case ICmpInst::ICMP_UGT: 9782 // We know from the range information that (V `Pred` Min || 9783 // V == Min). We know from the guarding condition that !(V 9784 // == Min). This gives us 9785 // 9786 // V `Pred` Min || V == Min && !(V == Min) 9787 // => V `Pred` Min 9788 // 9789 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9790 9791 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9792 return true; 9793 LLVM_FALLTHROUGH; 9794 9795 default: 9796 // No change 9797 break; 9798 } 9799 } 9800 } 9801 9802 // Check whether the actual condition is beyond sufficient. 9803 if (FoundPred == ICmpInst::ICMP_EQ) 9804 if (ICmpInst::isTrueWhenEqual(Pred)) 9805 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9806 return true; 9807 if (Pred == ICmpInst::ICMP_NE) 9808 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9809 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9810 return true; 9811 9812 // Otherwise assume the worst. 9813 return false; 9814 } 9815 9816 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9817 const SCEV *&L, const SCEV *&R, 9818 SCEV::NoWrapFlags &Flags) { 9819 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9820 if (!AE || AE->getNumOperands() != 2) 9821 return false; 9822 9823 L = AE->getOperand(0); 9824 R = AE->getOperand(1); 9825 Flags = AE->getNoWrapFlags(); 9826 return true; 9827 } 9828 9829 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9830 const SCEV *Less) { 9831 // We avoid subtracting expressions here because this function is usually 9832 // fairly deep in the call stack (i.e. is called many times). 9833 9834 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9835 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9836 const auto *MAR = cast<SCEVAddRecExpr>(More); 9837 9838 if (LAR->getLoop() != MAR->getLoop()) 9839 return None; 9840 9841 // We look at affine expressions only; not for correctness but to keep 9842 // getStepRecurrence cheap. 9843 if (!LAR->isAffine() || !MAR->isAffine()) 9844 return None; 9845 9846 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9847 return None; 9848 9849 Less = LAR->getStart(); 9850 More = MAR->getStart(); 9851 9852 // fall through 9853 } 9854 9855 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9856 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9857 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9858 return M - L; 9859 } 9860 9861 SCEV::NoWrapFlags Flags; 9862 const SCEV *LLess = nullptr, *RLess = nullptr; 9863 const SCEV *LMore = nullptr, *RMore = nullptr; 9864 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9865 // Compare (X + C1) vs X. 9866 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9867 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9868 if (RLess == More) 9869 return -(C1->getAPInt()); 9870 9871 // Compare X vs (X + C2). 9872 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9873 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9874 if (RMore == Less) 9875 return C2->getAPInt(); 9876 9877 // Compare (X + C1) vs (X + C2). 9878 if (C1 && C2 && RLess == RMore) 9879 return C2->getAPInt() - C1->getAPInt(); 9880 9881 return None; 9882 } 9883 9884 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9885 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9886 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9887 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9888 return false; 9889 9890 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9891 if (!AddRecLHS) 9892 return false; 9893 9894 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9895 if (!AddRecFoundLHS) 9896 return false; 9897 9898 // We'd like to let SCEV reason about control dependencies, so we constrain 9899 // both the inequalities to be about add recurrences on the same loop. This 9900 // way we can use isLoopEntryGuardedByCond later. 9901 9902 const Loop *L = AddRecFoundLHS->getLoop(); 9903 if (L != AddRecLHS->getLoop()) 9904 return false; 9905 9906 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9907 // 9908 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9909 // ... (2) 9910 // 9911 // Informal proof for (2), assuming (1) [*]: 9912 // 9913 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9914 // 9915 // Then 9916 // 9917 // FoundLHS s< FoundRHS s< INT_MIN - C 9918 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9919 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9920 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9921 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9922 // <=> FoundLHS + C s< FoundRHS + C 9923 // 9924 // [*]: (1) can be proved by ruling out overflow. 9925 // 9926 // [**]: This can be proved by analyzing all the four possibilities: 9927 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9928 // (A s>= 0, B s>= 0). 9929 // 9930 // Note: 9931 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9932 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9933 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9934 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9935 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9936 // C)". 9937 9938 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9939 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9940 if (!LDiff || !RDiff || *LDiff != *RDiff) 9941 return false; 9942 9943 if (LDiff->isMinValue()) 9944 return true; 9945 9946 APInt FoundRHSLimit; 9947 9948 if (Pred == CmpInst::ICMP_ULT) { 9949 FoundRHSLimit = -(*RDiff); 9950 } else { 9951 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9952 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9953 } 9954 9955 // Try to prove (1) or (2), as needed. 9956 return isAvailableAtLoopEntry(FoundRHS, L) && 9957 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9958 getConstant(FoundRHSLimit)); 9959 } 9960 9961 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 9962 const SCEV *LHS, const SCEV *RHS, 9963 const SCEV *FoundLHS, 9964 const SCEV *FoundRHS, unsigned Depth) { 9965 const PHINode *LPhi = nullptr, *RPhi = nullptr; 9966 9967 auto ClearOnExit = make_scope_exit([&]() { 9968 if (LPhi) { 9969 bool Erased = PendingMerges.erase(LPhi); 9970 assert(Erased && "Failed to erase LPhi!"); 9971 (void)Erased; 9972 } 9973 if (RPhi) { 9974 bool Erased = PendingMerges.erase(RPhi); 9975 assert(Erased && "Failed to erase RPhi!"); 9976 (void)Erased; 9977 } 9978 }); 9979 9980 // Find respective Phis and check that they are not being pending. 9981 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 9982 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 9983 if (!PendingMerges.insert(Phi).second) 9984 return false; 9985 LPhi = Phi; 9986 } 9987 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 9988 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 9989 // If we detect a loop of Phi nodes being processed by this method, for 9990 // example: 9991 // 9992 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 9993 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 9994 // 9995 // we don't want to deal with a case that complex, so return conservative 9996 // answer false. 9997 if (!PendingMerges.insert(Phi).second) 9998 return false; 9999 RPhi = Phi; 10000 } 10001 10002 // If none of LHS, RHS is a Phi, nothing to do here. 10003 if (!LPhi && !RPhi) 10004 return false; 10005 10006 // If there is a SCEVUnknown Phi we are interested in, make it left. 10007 if (!LPhi) { 10008 std::swap(LHS, RHS); 10009 std::swap(FoundLHS, FoundRHS); 10010 std::swap(LPhi, RPhi); 10011 Pred = ICmpInst::getSwappedPredicate(Pred); 10012 } 10013 10014 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10015 const BasicBlock *LBB = LPhi->getParent(); 10016 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10017 10018 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10019 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10020 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10021 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10022 }; 10023 10024 if (RPhi && RPhi->getParent() == LBB) { 10025 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10026 // If we compare two Phis from the same block, and for each entry block 10027 // the predicate is true for incoming values from this block, then the 10028 // predicate is also true for the Phis. 10029 for (const BasicBlock *IncBB : predecessors(LBB)) { 10030 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10031 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10032 if (!ProvedEasily(L, R)) 10033 return false; 10034 } 10035 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10036 // Case two: RHS is also a Phi from the same basic block, and it is an 10037 // AddRec. It means that there is a loop which has both AddRec and Unknown 10038 // PHIs, for it we can compare incoming values of AddRec from above the loop 10039 // and latch with their respective incoming values of LPhi. 10040 // TODO: Generalize to handle loops with many inputs in a header. 10041 if (LPhi->getNumIncomingValues() != 2) return false; 10042 10043 auto *RLoop = RAR->getLoop(); 10044 auto *Predecessor = RLoop->getLoopPredecessor(); 10045 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10046 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10047 if (!ProvedEasily(L1, RAR->getStart())) 10048 return false; 10049 auto *Latch = RLoop->getLoopLatch(); 10050 assert(Latch && "Loop with AddRec with no latch?"); 10051 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10052 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10053 return false; 10054 } else { 10055 // In all other cases go over inputs of LHS and compare each of them to RHS, 10056 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10057 // At this point RHS is either a non-Phi, or it is a Phi from some block 10058 // different from LBB. 10059 for (const BasicBlock *IncBB : predecessors(LBB)) { 10060 // Check that RHS is available in this block. 10061 if (!dominates(RHS, IncBB)) 10062 return false; 10063 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10064 if (!ProvedEasily(L, RHS)) 10065 return false; 10066 } 10067 } 10068 return true; 10069 } 10070 10071 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10072 const SCEV *LHS, const SCEV *RHS, 10073 const SCEV *FoundLHS, 10074 const SCEV *FoundRHS) { 10075 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10076 return true; 10077 10078 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10079 return true; 10080 10081 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10082 FoundLHS, FoundRHS) || 10083 // ~x < ~y --> x > y 10084 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10085 getNotSCEV(FoundRHS), 10086 getNotSCEV(FoundLHS)); 10087 } 10088 10089 /// If Expr computes ~A, return A else return nullptr 10090 static const SCEV *MatchNotExpr(const SCEV *Expr) { 10091 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 10092 if (!Add || Add->getNumOperands() != 2 || 10093 !Add->getOperand(0)->isAllOnesValue()) 10094 return nullptr; 10095 10096 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 10097 if (!AddRHS || AddRHS->getNumOperands() != 2 || 10098 !AddRHS->getOperand(0)->isAllOnesValue()) 10099 return nullptr; 10100 10101 return AddRHS->getOperand(1); 10102 } 10103 10104 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 10105 template<typename MaxExprType> 10106 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 10107 const SCEV *Candidate) { 10108 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 10109 if (!MaxExpr) return false; 10110 10111 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 10112 } 10113 10114 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 10115 template<typename MaxExprType> 10116 static bool IsMinConsistingOf(ScalarEvolution &SE, 10117 const SCEV *MaybeMinExpr, 10118 const SCEV *Candidate) { 10119 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 10120 if (!MaybeMaxExpr) 10121 return false; 10122 10123 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 10124 } 10125 10126 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10127 ICmpInst::Predicate Pred, 10128 const SCEV *LHS, const SCEV *RHS) { 10129 // If both sides are affine addrecs for the same loop, with equal 10130 // steps, and we know the recurrences don't wrap, then we only 10131 // need to check the predicate on the starting values. 10132 10133 if (!ICmpInst::isRelational(Pred)) 10134 return false; 10135 10136 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10137 if (!LAR) 10138 return false; 10139 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10140 if (!RAR) 10141 return false; 10142 if (LAR->getLoop() != RAR->getLoop()) 10143 return false; 10144 if (!LAR->isAffine() || !RAR->isAffine()) 10145 return false; 10146 10147 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10148 return false; 10149 10150 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10151 SCEV::FlagNSW : SCEV::FlagNUW; 10152 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10153 return false; 10154 10155 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10156 } 10157 10158 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10159 /// expression? 10160 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10161 ICmpInst::Predicate Pred, 10162 const SCEV *LHS, const SCEV *RHS) { 10163 switch (Pred) { 10164 default: 10165 return false; 10166 10167 case ICmpInst::ICMP_SGE: 10168 std::swap(LHS, RHS); 10169 LLVM_FALLTHROUGH; 10170 case ICmpInst::ICMP_SLE: 10171 return 10172 // min(A, ...) <= A 10173 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 10174 // A <= max(A, ...) 10175 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10176 10177 case ICmpInst::ICMP_UGE: 10178 std::swap(LHS, RHS); 10179 LLVM_FALLTHROUGH; 10180 case ICmpInst::ICMP_ULE: 10181 return 10182 // min(A, ...) <= A 10183 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 10184 // A <= max(A, ...) 10185 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10186 } 10187 10188 llvm_unreachable("covered switch fell through?!"); 10189 } 10190 10191 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10192 const SCEV *LHS, const SCEV *RHS, 10193 const SCEV *FoundLHS, 10194 const SCEV *FoundRHS, 10195 unsigned Depth) { 10196 assert(getTypeSizeInBits(LHS->getType()) == 10197 getTypeSizeInBits(RHS->getType()) && 10198 "LHS and RHS have different sizes?"); 10199 assert(getTypeSizeInBits(FoundLHS->getType()) == 10200 getTypeSizeInBits(FoundRHS->getType()) && 10201 "FoundLHS and FoundRHS have different sizes?"); 10202 // We want to avoid hurting the compile time with analysis of too big trees. 10203 if (Depth > MaxSCEVOperationsImplicationDepth) 10204 return false; 10205 // We only want to work with ICMP_SGT comparison so far. 10206 // TODO: Extend to ICMP_UGT? 10207 if (Pred == ICmpInst::ICMP_SLT) { 10208 Pred = ICmpInst::ICMP_SGT; 10209 std::swap(LHS, RHS); 10210 std::swap(FoundLHS, FoundRHS); 10211 } 10212 if (Pred != ICmpInst::ICMP_SGT) 10213 return false; 10214 10215 auto GetOpFromSExt = [&](const SCEV *S) { 10216 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10217 return Ext->getOperand(); 10218 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10219 // the constant in some cases. 10220 return S; 10221 }; 10222 10223 // Acquire values from extensions. 10224 auto *OrigLHS = LHS; 10225 auto *OrigFoundLHS = FoundLHS; 10226 LHS = GetOpFromSExt(LHS); 10227 FoundLHS = GetOpFromSExt(FoundLHS); 10228 10229 // Is the SGT predicate can be proved trivially or using the found context. 10230 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10231 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10232 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10233 FoundRHS, Depth + 1); 10234 }; 10235 10236 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10237 // We want to avoid creation of any new non-constant SCEV. Since we are 10238 // going to compare the operands to RHS, we should be certain that we don't 10239 // need any size extensions for this. So let's decline all cases when the 10240 // sizes of types of LHS and RHS do not match. 10241 // TODO: Maybe try to get RHS from sext to catch more cases? 10242 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10243 return false; 10244 10245 // Should not overflow. 10246 if (!LHSAddExpr->hasNoSignedWrap()) 10247 return false; 10248 10249 auto *LL = LHSAddExpr->getOperand(0); 10250 auto *LR = LHSAddExpr->getOperand(1); 10251 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10252 10253 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10254 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10255 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10256 }; 10257 // Try to prove the following rule: 10258 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10259 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10260 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10261 return true; 10262 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10263 Value *LL, *LR; 10264 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10265 10266 using namespace llvm::PatternMatch; 10267 10268 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10269 // Rules for division. 10270 // We are going to perform some comparisons with Denominator and its 10271 // derivative expressions. In general case, creating a SCEV for it may 10272 // lead to a complex analysis of the entire graph, and in particular it 10273 // can request trip count recalculation for the same loop. This would 10274 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10275 // this, we only want to create SCEVs that are constants in this section. 10276 // So we bail if Denominator is not a constant. 10277 if (!isa<ConstantInt>(LR)) 10278 return false; 10279 10280 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10281 10282 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10283 // then a SCEV for the numerator already exists and matches with FoundLHS. 10284 auto *Numerator = getExistingSCEV(LL); 10285 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10286 return false; 10287 10288 // Make sure that the numerator matches with FoundLHS and the denominator 10289 // is positive. 10290 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10291 return false; 10292 10293 auto *DTy = Denominator->getType(); 10294 auto *FRHSTy = FoundRHS->getType(); 10295 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10296 // One of types is a pointer and another one is not. We cannot extend 10297 // them properly to a wider type, so let us just reject this case. 10298 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10299 // to avoid this check. 10300 return false; 10301 10302 // Given that: 10303 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10304 auto *WTy = getWiderType(DTy, FRHSTy); 10305 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10306 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10307 10308 // Try to prove the following rule: 10309 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10310 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10311 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10312 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10313 if (isKnownNonPositive(RHS) && 10314 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10315 return true; 10316 10317 // Try to prove the following rule: 10318 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10319 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10320 // If we divide it by Denominator > 2, then: 10321 // 1. If FoundLHS is negative, then the result is 0. 10322 // 2. If FoundLHS is non-negative, then the result is non-negative. 10323 // Anyways, the result is non-negative. 10324 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10325 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10326 if (isKnownNegative(RHS) && 10327 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10328 return true; 10329 } 10330 } 10331 10332 // If our expression contained SCEVUnknown Phis, and we split it down and now 10333 // need to prove something for them, try to prove the predicate for every 10334 // possible incoming values of those Phis. 10335 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10336 return true; 10337 10338 return false; 10339 } 10340 10341 bool 10342 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10343 const SCEV *LHS, const SCEV *RHS) { 10344 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10345 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10346 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10347 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10348 } 10349 10350 bool 10351 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10352 const SCEV *LHS, const SCEV *RHS, 10353 const SCEV *FoundLHS, 10354 const SCEV *FoundRHS) { 10355 switch (Pred) { 10356 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10357 case ICmpInst::ICMP_EQ: 10358 case ICmpInst::ICMP_NE: 10359 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10360 return true; 10361 break; 10362 case ICmpInst::ICMP_SLT: 10363 case ICmpInst::ICMP_SLE: 10364 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10365 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10366 return true; 10367 break; 10368 case ICmpInst::ICMP_SGT: 10369 case ICmpInst::ICMP_SGE: 10370 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10371 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10372 return true; 10373 break; 10374 case ICmpInst::ICMP_ULT: 10375 case ICmpInst::ICMP_ULE: 10376 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10377 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10378 return true; 10379 break; 10380 case ICmpInst::ICMP_UGT: 10381 case ICmpInst::ICMP_UGE: 10382 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10383 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10384 return true; 10385 break; 10386 } 10387 10388 // Maybe it can be proved via operations? 10389 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10390 return true; 10391 10392 return false; 10393 } 10394 10395 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10396 const SCEV *LHS, 10397 const SCEV *RHS, 10398 const SCEV *FoundLHS, 10399 const SCEV *FoundRHS) { 10400 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10401 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10402 // reduce the compile time impact of this optimization. 10403 return false; 10404 10405 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10406 if (!Addend) 10407 return false; 10408 10409 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10410 10411 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10412 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10413 ConstantRange FoundLHSRange = 10414 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10415 10416 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10417 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10418 10419 // We can also compute the range of values for `LHS` that satisfy the 10420 // consequent, "`LHS` `Pred` `RHS`": 10421 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10422 ConstantRange SatisfyingLHSRange = 10423 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10424 10425 // The antecedent implies the consequent if every value of `LHS` that 10426 // satisfies the antecedent also satisfies the consequent. 10427 return SatisfyingLHSRange.contains(LHSRange); 10428 } 10429 10430 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10431 bool IsSigned, bool NoWrap) { 10432 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10433 10434 if (NoWrap) return false; 10435 10436 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10437 const SCEV *One = getOne(Stride->getType()); 10438 10439 if (IsSigned) { 10440 APInt MaxRHS = getSignedRangeMax(RHS); 10441 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10442 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10443 10444 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10445 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10446 } 10447 10448 APInt MaxRHS = getUnsignedRangeMax(RHS); 10449 APInt MaxValue = APInt::getMaxValue(BitWidth); 10450 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10451 10452 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10453 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10454 } 10455 10456 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10457 bool IsSigned, bool NoWrap) { 10458 if (NoWrap) return false; 10459 10460 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10461 const SCEV *One = getOne(Stride->getType()); 10462 10463 if (IsSigned) { 10464 APInt MinRHS = getSignedRangeMin(RHS); 10465 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10466 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10467 10468 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10469 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10470 } 10471 10472 APInt MinRHS = getUnsignedRangeMin(RHS); 10473 APInt MinValue = APInt::getMinValue(BitWidth); 10474 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10475 10476 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10477 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10478 } 10479 10480 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10481 bool Equality) { 10482 const SCEV *One = getOne(Step->getType()); 10483 Delta = Equality ? getAddExpr(Delta, Step) 10484 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10485 return getUDivExpr(Delta, Step); 10486 } 10487 10488 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10489 const SCEV *Stride, 10490 const SCEV *End, 10491 unsigned BitWidth, 10492 bool IsSigned) { 10493 10494 assert(!isKnownNonPositive(Stride) && 10495 "Stride is expected strictly positive!"); 10496 // Calculate the maximum backedge count based on the range of values 10497 // permitted by Start, End, and Stride. 10498 const SCEV *MaxBECount; 10499 APInt MinStart = 10500 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10501 10502 APInt StrideForMaxBECount = 10503 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10504 10505 // We already know that the stride is positive, so we paper over conservatism 10506 // in our range computation by forcing StrideForMaxBECount to be at least one. 10507 // In theory this is unnecessary, but we expect MaxBECount to be a 10508 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10509 // is nothing to constant fold it to). 10510 APInt One(BitWidth, 1, IsSigned); 10511 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10512 10513 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10514 : APInt::getMaxValue(BitWidth); 10515 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10516 10517 // Although End can be a MAX expression we estimate MaxEnd considering only 10518 // the case End = RHS of the loop termination condition. This is safe because 10519 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10520 // taken count. 10521 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10522 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10523 10524 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10525 getConstant(StrideForMaxBECount) /* Step */, 10526 false /* Equality */); 10527 10528 return MaxBECount; 10529 } 10530 10531 ScalarEvolution::ExitLimit 10532 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10533 const Loop *L, bool IsSigned, 10534 bool ControlsExit, bool AllowPredicates) { 10535 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10536 10537 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10538 bool PredicatedIV = false; 10539 10540 if (!IV && AllowPredicates) { 10541 // Try to make this an AddRec using runtime tests, in the first X 10542 // iterations of this loop, where X is the SCEV expression found by the 10543 // algorithm below. 10544 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10545 PredicatedIV = true; 10546 } 10547 10548 // Avoid weird loops 10549 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10550 return getCouldNotCompute(); 10551 10552 bool NoWrap = ControlsExit && 10553 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10554 10555 const SCEV *Stride = IV->getStepRecurrence(*this); 10556 10557 bool PositiveStride = isKnownPositive(Stride); 10558 10559 // Avoid negative or zero stride values. 10560 if (!PositiveStride) { 10561 // We can compute the correct backedge taken count for loops with unknown 10562 // strides if we can prove that the loop is not an infinite loop with side 10563 // effects. Here's the loop structure we are trying to handle - 10564 // 10565 // i = start 10566 // do { 10567 // A[i] = i; 10568 // i += s; 10569 // } while (i < end); 10570 // 10571 // The backedge taken count for such loops is evaluated as - 10572 // (max(end, start + stride) - start - 1) /u stride 10573 // 10574 // The additional preconditions that we need to check to prove correctness 10575 // of the above formula is as follows - 10576 // 10577 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10578 // NoWrap flag). 10579 // b) loop is single exit with no side effects. 10580 // 10581 // 10582 // Precondition a) implies that if the stride is negative, this is a single 10583 // trip loop. The backedge taken count formula reduces to zero in this case. 10584 // 10585 // Precondition b) implies that the unknown stride cannot be zero otherwise 10586 // we have UB. 10587 // 10588 // The positive stride case is the same as isKnownPositive(Stride) returning 10589 // true (original behavior of the function). 10590 // 10591 // We want to make sure that the stride is truly unknown as there are edge 10592 // cases where ScalarEvolution propagates no wrap flags to the 10593 // post-increment/decrement IV even though the increment/decrement operation 10594 // itself is wrapping. The computed backedge taken count may be wrong in 10595 // such cases. This is prevented by checking that the stride is not known to 10596 // be either positive or non-positive. For example, no wrap flags are 10597 // propagated to the post-increment IV of this loop with a trip count of 2 - 10598 // 10599 // unsigned char i; 10600 // for(i=127; i<128; i+=129) 10601 // A[i] = i; 10602 // 10603 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10604 !loopHasNoSideEffects(L)) 10605 return getCouldNotCompute(); 10606 } else if (!Stride->isOne() && 10607 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10608 // Avoid proven overflow cases: this will ensure that the backedge taken 10609 // count will not generate any unsigned overflow. Relaxed no-overflow 10610 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10611 // undefined behaviors like the case of C language. 10612 return getCouldNotCompute(); 10613 10614 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10615 : ICmpInst::ICMP_ULT; 10616 const SCEV *Start = IV->getStart(); 10617 const SCEV *End = RHS; 10618 // When the RHS is not invariant, we do not know the end bound of the loop and 10619 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10620 // calculate the MaxBECount, given the start, stride and max value for the end 10621 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10622 // checked above). 10623 if (!isLoopInvariant(RHS, L)) { 10624 const SCEV *MaxBECount = computeMaxBECountForLT( 10625 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10626 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10627 false /*MaxOrZero*/, Predicates); 10628 } 10629 // If the backedge is taken at least once, then it will be taken 10630 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10631 // is the LHS value of the less-than comparison the first time it is evaluated 10632 // and End is the RHS. 10633 const SCEV *BECountIfBackedgeTaken = 10634 computeBECount(getMinusSCEV(End, Start), Stride, false); 10635 // If the loop entry is guarded by the result of the backedge test of the 10636 // first loop iteration, then we know the backedge will be taken at least 10637 // once and so the backedge taken count is as above. If not then we use the 10638 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10639 // as if the backedge is taken at least once max(End,Start) is End and so the 10640 // result is as above, and if not max(End,Start) is Start so we get a backedge 10641 // count of zero. 10642 const SCEV *BECount; 10643 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10644 BECount = BECountIfBackedgeTaken; 10645 else { 10646 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10647 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10648 } 10649 10650 const SCEV *MaxBECount; 10651 bool MaxOrZero = false; 10652 if (isa<SCEVConstant>(BECount)) 10653 MaxBECount = BECount; 10654 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10655 // If we know exactly how many times the backedge will be taken if it's 10656 // taken at least once, then the backedge count will either be that or 10657 // zero. 10658 MaxBECount = BECountIfBackedgeTaken; 10659 MaxOrZero = true; 10660 } else { 10661 MaxBECount = computeMaxBECountForLT( 10662 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10663 } 10664 10665 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10666 !isa<SCEVCouldNotCompute>(BECount)) 10667 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10668 10669 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10670 } 10671 10672 ScalarEvolution::ExitLimit 10673 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10674 const Loop *L, bool IsSigned, 10675 bool ControlsExit, bool AllowPredicates) { 10676 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10677 // We handle only IV > Invariant 10678 if (!isLoopInvariant(RHS, L)) 10679 return getCouldNotCompute(); 10680 10681 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10682 if (!IV && AllowPredicates) 10683 // Try to make this an AddRec using runtime tests, in the first X 10684 // iterations of this loop, where X is the SCEV expression found by the 10685 // algorithm below. 10686 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10687 10688 // Avoid weird loops 10689 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10690 return getCouldNotCompute(); 10691 10692 bool NoWrap = ControlsExit && 10693 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10694 10695 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10696 10697 // Avoid negative or zero stride values 10698 if (!isKnownPositive(Stride)) 10699 return getCouldNotCompute(); 10700 10701 // Avoid proven overflow cases: this will ensure that the backedge taken count 10702 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10703 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10704 // behaviors like the case of C language. 10705 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10706 return getCouldNotCompute(); 10707 10708 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10709 : ICmpInst::ICMP_UGT; 10710 10711 const SCEV *Start = IV->getStart(); 10712 const SCEV *End = RHS; 10713 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10714 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10715 10716 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10717 10718 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10719 : getUnsignedRangeMax(Start); 10720 10721 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10722 : getUnsignedRangeMin(Stride); 10723 10724 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10725 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10726 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10727 10728 // Although End can be a MIN expression we estimate MinEnd considering only 10729 // the case End = RHS. This is safe because in the other case (Start - End) 10730 // is zero, leading to a zero maximum backedge taken count. 10731 APInt MinEnd = 10732 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10733 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10734 10735 10736 const SCEV *MaxBECount = getCouldNotCompute(); 10737 if (isa<SCEVConstant>(BECount)) 10738 MaxBECount = BECount; 10739 else 10740 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 10741 getConstant(MinStride), false); 10742 10743 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10744 MaxBECount = BECount; 10745 10746 return ExitLimit(BECount, MaxBECount, false, Predicates); 10747 } 10748 10749 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10750 ScalarEvolution &SE) const { 10751 if (Range.isFullSet()) // Infinite loop. 10752 return SE.getCouldNotCompute(); 10753 10754 // If the start is a non-zero constant, shift the range to simplify things. 10755 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10756 if (!SC->getValue()->isZero()) { 10757 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10758 Operands[0] = SE.getZero(SC->getType()); 10759 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10760 getNoWrapFlags(FlagNW)); 10761 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10762 return ShiftedAddRec->getNumIterationsInRange( 10763 Range.subtract(SC->getAPInt()), SE); 10764 // This is strange and shouldn't happen. 10765 return SE.getCouldNotCompute(); 10766 } 10767 10768 // The only time we can solve this is when we have all constant indices. 10769 // Otherwise, we cannot determine the overflow conditions. 10770 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10771 return SE.getCouldNotCompute(); 10772 10773 // Okay at this point we know that all elements of the chrec are constants and 10774 // that the start element is zero. 10775 10776 // First check to see if the range contains zero. If not, the first 10777 // iteration exits. 10778 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10779 if (!Range.contains(APInt(BitWidth, 0))) 10780 return SE.getZero(getType()); 10781 10782 if (isAffine()) { 10783 // If this is an affine expression then we have this situation: 10784 // Solve {0,+,A} in Range === Ax in Range 10785 10786 // We know that zero is in the range. If A is positive then we know that 10787 // the upper value of the range must be the first possible exit value. 10788 // If A is negative then the lower of the range is the last possible loop 10789 // value. Also note that we already checked for a full range. 10790 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10791 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10792 10793 // The exit value should be (End+A)/A. 10794 APInt ExitVal = (End + A).udiv(A); 10795 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10796 10797 // Evaluate at the exit value. If we really did fall out of the valid 10798 // range, then we computed our trip count, otherwise wrap around or other 10799 // things must have happened. 10800 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10801 if (Range.contains(Val->getValue())) 10802 return SE.getCouldNotCompute(); // Something strange happened 10803 10804 // Ensure that the previous value is in the range. This is a sanity check. 10805 assert(Range.contains( 10806 EvaluateConstantChrecAtConstant(this, 10807 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10808 "Linear scev computation is off in a bad way!"); 10809 return SE.getConstant(ExitValue); 10810 } 10811 10812 if (isQuadratic()) { 10813 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10814 return SE.getConstant(S.getValue()); 10815 } 10816 10817 return SE.getCouldNotCompute(); 10818 } 10819 10820 const SCEVAddRecExpr * 10821 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10822 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10823 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10824 // but in this case we cannot guarantee that the value returned will be an 10825 // AddRec because SCEV does not have a fixed point where it stops 10826 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10827 // may happen if we reach arithmetic depth limit while simplifying. So we 10828 // construct the returned value explicitly. 10829 SmallVector<const SCEV *, 3> Ops; 10830 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10831 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10832 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10833 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10834 // We know that the last operand is not a constant zero (otherwise it would 10835 // have been popped out earlier). This guarantees us that if the result has 10836 // the same last operand, then it will also not be popped out, meaning that 10837 // the returned value will be an AddRec. 10838 const SCEV *Last = getOperand(getNumOperands() - 1); 10839 assert(!Last->isZero() && "Recurrency with zero step?"); 10840 Ops.push_back(Last); 10841 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10842 SCEV::FlagAnyWrap)); 10843 } 10844 10845 // Return true when S contains at least an undef value. 10846 static inline bool containsUndefs(const SCEV *S) { 10847 return SCEVExprContains(S, [](const SCEV *S) { 10848 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10849 return isa<UndefValue>(SU->getValue()); 10850 return false; 10851 }); 10852 } 10853 10854 namespace { 10855 10856 // Collect all steps of SCEV expressions. 10857 struct SCEVCollectStrides { 10858 ScalarEvolution &SE; 10859 SmallVectorImpl<const SCEV *> &Strides; 10860 10861 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10862 : SE(SE), Strides(S) {} 10863 10864 bool follow(const SCEV *S) { 10865 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10866 Strides.push_back(AR->getStepRecurrence(SE)); 10867 return true; 10868 } 10869 10870 bool isDone() const { return false; } 10871 }; 10872 10873 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10874 struct SCEVCollectTerms { 10875 SmallVectorImpl<const SCEV *> &Terms; 10876 10877 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10878 10879 bool follow(const SCEV *S) { 10880 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10881 isa<SCEVSignExtendExpr>(S)) { 10882 if (!containsUndefs(S)) 10883 Terms.push_back(S); 10884 10885 // Stop recursion: once we collected a term, do not walk its operands. 10886 return false; 10887 } 10888 10889 // Keep looking. 10890 return true; 10891 } 10892 10893 bool isDone() const { return false; } 10894 }; 10895 10896 // Check if a SCEV contains an AddRecExpr. 10897 struct SCEVHasAddRec { 10898 bool &ContainsAddRec; 10899 10900 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10901 ContainsAddRec = false; 10902 } 10903 10904 bool follow(const SCEV *S) { 10905 if (isa<SCEVAddRecExpr>(S)) { 10906 ContainsAddRec = true; 10907 10908 // Stop recursion: once we collected a term, do not walk its operands. 10909 return false; 10910 } 10911 10912 // Keep looking. 10913 return true; 10914 } 10915 10916 bool isDone() const { return false; } 10917 }; 10918 10919 // Find factors that are multiplied with an expression that (possibly as a 10920 // subexpression) contains an AddRecExpr. In the expression: 10921 // 10922 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10923 // 10924 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10925 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10926 // parameters as they form a product with an induction variable. 10927 // 10928 // This collector expects all array size parameters to be in the same MulExpr. 10929 // It might be necessary to later add support for collecting parameters that are 10930 // spread over different nested MulExpr. 10931 struct SCEVCollectAddRecMultiplies { 10932 SmallVectorImpl<const SCEV *> &Terms; 10933 ScalarEvolution &SE; 10934 10935 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10936 : Terms(T), SE(SE) {} 10937 10938 bool follow(const SCEV *S) { 10939 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10940 bool HasAddRec = false; 10941 SmallVector<const SCEV *, 0> Operands; 10942 for (auto Op : Mul->operands()) { 10943 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10944 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10945 Operands.push_back(Op); 10946 } else if (Unknown) { 10947 HasAddRec = true; 10948 } else { 10949 bool ContainsAddRec; 10950 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10951 visitAll(Op, ContiansAddRec); 10952 HasAddRec |= ContainsAddRec; 10953 } 10954 } 10955 if (Operands.size() == 0) 10956 return true; 10957 10958 if (!HasAddRec) 10959 return false; 10960 10961 Terms.push_back(SE.getMulExpr(Operands)); 10962 // Stop recursion: once we collected a term, do not walk its operands. 10963 return false; 10964 } 10965 10966 // Keep looking. 10967 return true; 10968 } 10969 10970 bool isDone() const { return false; } 10971 }; 10972 10973 } // end anonymous namespace 10974 10975 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 10976 /// two places: 10977 /// 1) The strides of AddRec expressions. 10978 /// 2) Unknowns that are multiplied with AddRec expressions. 10979 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 10980 SmallVectorImpl<const SCEV *> &Terms) { 10981 SmallVector<const SCEV *, 4> Strides; 10982 SCEVCollectStrides StrideCollector(*this, Strides); 10983 visitAll(Expr, StrideCollector); 10984 10985 LLVM_DEBUG({ 10986 dbgs() << "Strides:\n"; 10987 for (const SCEV *S : Strides) 10988 dbgs() << *S << "\n"; 10989 }); 10990 10991 for (const SCEV *S : Strides) { 10992 SCEVCollectTerms TermCollector(Terms); 10993 visitAll(S, TermCollector); 10994 } 10995 10996 LLVM_DEBUG({ 10997 dbgs() << "Terms:\n"; 10998 for (const SCEV *T : Terms) 10999 dbgs() << *T << "\n"; 11000 }); 11001 11002 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11003 visitAll(Expr, MulCollector); 11004 } 11005 11006 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11007 SmallVectorImpl<const SCEV *> &Terms, 11008 SmallVectorImpl<const SCEV *> &Sizes) { 11009 int Last = Terms.size() - 1; 11010 const SCEV *Step = Terms[Last]; 11011 11012 // End of recursion. 11013 if (Last == 0) { 11014 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11015 SmallVector<const SCEV *, 2> Qs; 11016 for (const SCEV *Op : M->operands()) 11017 if (!isa<SCEVConstant>(Op)) 11018 Qs.push_back(Op); 11019 11020 Step = SE.getMulExpr(Qs); 11021 } 11022 11023 Sizes.push_back(Step); 11024 return true; 11025 } 11026 11027 for (const SCEV *&Term : Terms) { 11028 // Normalize the terms before the next call to findArrayDimensionsRec. 11029 const SCEV *Q, *R; 11030 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11031 11032 // Bail out when GCD does not evenly divide one of the terms. 11033 if (!R->isZero()) 11034 return false; 11035 11036 Term = Q; 11037 } 11038 11039 // Remove all SCEVConstants. 11040 Terms.erase( 11041 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11042 Terms.end()); 11043 11044 if (Terms.size() > 0) 11045 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11046 return false; 11047 11048 Sizes.push_back(Step); 11049 return true; 11050 } 11051 11052 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11053 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11054 for (const SCEV *T : Terms) 11055 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 11056 return true; 11057 return false; 11058 } 11059 11060 // Return the number of product terms in S. 11061 static inline int numberOfTerms(const SCEV *S) { 11062 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11063 return Expr->getNumOperands(); 11064 return 1; 11065 } 11066 11067 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11068 if (isa<SCEVConstant>(T)) 11069 return nullptr; 11070 11071 if (isa<SCEVUnknown>(T)) 11072 return T; 11073 11074 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11075 SmallVector<const SCEV *, 2> Factors; 11076 for (const SCEV *Op : M->operands()) 11077 if (!isa<SCEVConstant>(Op)) 11078 Factors.push_back(Op); 11079 11080 return SE.getMulExpr(Factors); 11081 } 11082 11083 return T; 11084 } 11085 11086 /// Return the size of an element read or written by Inst. 11087 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11088 Type *Ty; 11089 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11090 Ty = Store->getValueOperand()->getType(); 11091 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11092 Ty = Load->getType(); 11093 else 11094 return nullptr; 11095 11096 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11097 return getSizeOfExpr(ETy, Ty); 11098 } 11099 11100 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11101 SmallVectorImpl<const SCEV *> &Sizes, 11102 const SCEV *ElementSize) { 11103 if (Terms.size() < 1 || !ElementSize) 11104 return; 11105 11106 // Early return when Terms do not contain parameters: we do not delinearize 11107 // non parametric SCEVs. 11108 if (!containsParameters(Terms)) 11109 return; 11110 11111 LLVM_DEBUG({ 11112 dbgs() << "Terms:\n"; 11113 for (const SCEV *T : Terms) 11114 dbgs() << *T << "\n"; 11115 }); 11116 11117 // Remove duplicates. 11118 array_pod_sort(Terms.begin(), Terms.end()); 11119 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11120 11121 // Put larger terms first. 11122 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11123 return numberOfTerms(LHS) > numberOfTerms(RHS); 11124 }); 11125 11126 // Try to divide all terms by the element size. If term is not divisible by 11127 // element size, proceed with the original term. 11128 for (const SCEV *&Term : Terms) { 11129 const SCEV *Q, *R; 11130 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11131 if (!Q->isZero()) 11132 Term = Q; 11133 } 11134 11135 SmallVector<const SCEV *, 4> NewTerms; 11136 11137 // Remove constant factors. 11138 for (const SCEV *T : Terms) 11139 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11140 NewTerms.push_back(NewT); 11141 11142 LLVM_DEBUG({ 11143 dbgs() << "Terms after sorting:\n"; 11144 for (const SCEV *T : NewTerms) 11145 dbgs() << *T << "\n"; 11146 }); 11147 11148 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11149 Sizes.clear(); 11150 return; 11151 } 11152 11153 // The last element to be pushed into Sizes is the size of an element. 11154 Sizes.push_back(ElementSize); 11155 11156 LLVM_DEBUG({ 11157 dbgs() << "Sizes:\n"; 11158 for (const SCEV *S : Sizes) 11159 dbgs() << *S << "\n"; 11160 }); 11161 } 11162 11163 void ScalarEvolution::computeAccessFunctions( 11164 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11165 SmallVectorImpl<const SCEV *> &Sizes) { 11166 // Early exit in case this SCEV is not an affine multivariate function. 11167 if (Sizes.empty()) 11168 return; 11169 11170 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11171 if (!AR->isAffine()) 11172 return; 11173 11174 const SCEV *Res = Expr; 11175 int Last = Sizes.size() - 1; 11176 for (int i = Last; i >= 0; i--) { 11177 const SCEV *Q, *R; 11178 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11179 11180 LLVM_DEBUG({ 11181 dbgs() << "Res: " << *Res << "\n"; 11182 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11183 dbgs() << "Res divided by Sizes[i]:\n"; 11184 dbgs() << "Quotient: " << *Q << "\n"; 11185 dbgs() << "Remainder: " << *R << "\n"; 11186 }); 11187 11188 Res = Q; 11189 11190 // Do not record the last subscript corresponding to the size of elements in 11191 // the array. 11192 if (i == Last) { 11193 11194 // Bail out if the remainder is too complex. 11195 if (isa<SCEVAddRecExpr>(R)) { 11196 Subscripts.clear(); 11197 Sizes.clear(); 11198 return; 11199 } 11200 11201 continue; 11202 } 11203 11204 // Record the access function for the current subscript. 11205 Subscripts.push_back(R); 11206 } 11207 11208 // Also push in last position the remainder of the last division: it will be 11209 // the access function of the innermost dimension. 11210 Subscripts.push_back(Res); 11211 11212 std::reverse(Subscripts.begin(), Subscripts.end()); 11213 11214 LLVM_DEBUG({ 11215 dbgs() << "Subscripts:\n"; 11216 for (const SCEV *S : Subscripts) 11217 dbgs() << *S << "\n"; 11218 }); 11219 } 11220 11221 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11222 /// sizes of an array access. Returns the remainder of the delinearization that 11223 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11224 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11225 /// expressions in the stride and base of a SCEV corresponding to the 11226 /// computation of a GCD (greatest common divisor) of base and stride. When 11227 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11228 /// 11229 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11230 /// 11231 /// void foo(long n, long m, long o, double A[n][m][o]) { 11232 /// 11233 /// for (long i = 0; i < n; i++) 11234 /// for (long j = 0; j < m; j++) 11235 /// for (long k = 0; k < o; k++) 11236 /// A[i][j][k] = 1.0; 11237 /// } 11238 /// 11239 /// the delinearization input is the following AddRec SCEV: 11240 /// 11241 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11242 /// 11243 /// From this SCEV, we are able to say that the base offset of the access is %A 11244 /// because it appears as an offset that does not divide any of the strides in 11245 /// the loops: 11246 /// 11247 /// CHECK: Base offset: %A 11248 /// 11249 /// and then SCEV->delinearize determines the size of some of the dimensions of 11250 /// the array as these are the multiples by which the strides are happening: 11251 /// 11252 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11253 /// 11254 /// Note that the outermost dimension remains of UnknownSize because there are 11255 /// no strides that would help identifying the size of the last dimension: when 11256 /// the array has been statically allocated, one could compute the size of that 11257 /// dimension by dividing the overall size of the array by the size of the known 11258 /// dimensions: %m * %o * 8. 11259 /// 11260 /// Finally delinearize provides the access functions for the array reference 11261 /// that does correspond to A[i][j][k] of the above C testcase: 11262 /// 11263 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11264 /// 11265 /// The testcases are checking the output of a function pass: 11266 /// DelinearizationPass that walks through all loads and stores of a function 11267 /// asking for the SCEV of the memory access with respect to all enclosing 11268 /// loops, calling SCEV->delinearize on that and printing the results. 11269 void ScalarEvolution::delinearize(const SCEV *Expr, 11270 SmallVectorImpl<const SCEV *> &Subscripts, 11271 SmallVectorImpl<const SCEV *> &Sizes, 11272 const SCEV *ElementSize) { 11273 // First step: collect parametric terms. 11274 SmallVector<const SCEV *, 4> Terms; 11275 collectParametricTerms(Expr, Terms); 11276 11277 if (Terms.empty()) 11278 return; 11279 11280 // Second step: find subscript sizes. 11281 findArrayDimensions(Terms, Sizes, ElementSize); 11282 11283 if (Sizes.empty()) 11284 return; 11285 11286 // Third step: compute the access functions for each subscript. 11287 computeAccessFunctions(Expr, Subscripts, Sizes); 11288 11289 if (Subscripts.empty()) 11290 return; 11291 11292 LLVM_DEBUG({ 11293 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11294 dbgs() << "ArrayDecl[UnknownSize]"; 11295 for (const SCEV *S : Sizes) 11296 dbgs() << "[" << *S << "]"; 11297 11298 dbgs() << "\nArrayRef"; 11299 for (const SCEV *S : Subscripts) 11300 dbgs() << "[" << *S << "]"; 11301 dbgs() << "\n"; 11302 }); 11303 } 11304 11305 //===----------------------------------------------------------------------===// 11306 // SCEVCallbackVH Class Implementation 11307 //===----------------------------------------------------------------------===// 11308 11309 void ScalarEvolution::SCEVCallbackVH::deleted() { 11310 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11311 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11312 SE->ConstantEvolutionLoopExitValue.erase(PN); 11313 SE->eraseValueFromMap(getValPtr()); 11314 // this now dangles! 11315 } 11316 11317 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11318 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11319 11320 // Forget all the expressions associated with users of the old value, 11321 // so that future queries will recompute the expressions using the new 11322 // value. 11323 Value *Old = getValPtr(); 11324 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11325 SmallPtrSet<User *, 8> Visited; 11326 while (!Worklist.empty()) { 11327 User *U = Worklist.pop_back_val(); 11328 // Deleting the Old value will cause this to dangle. Postpone 11329 // that until everything else is done. 11330 if (U == Old) 11331 continue; 11332 if (!Visited.insert(U).second) 11333 continue; 11334 if (PHINode *PN = dyn_cast<PHINode>(U)) 11335 SE->ConstantEvolutionLoopExitValue.erase(PN); 11336 SE->eraseValueFromMap(U); 11337 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11338 } 11339 // Delete the Old value. 11340 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11341 SE->ConstantEvolutionLoopExitValue.erase(PN); 11342 SE->eraseValueFromMap(Old); 11343 // this now dangles! 11344 } 11345 11346 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11347 : CallbackVH(V), SE(se) {} 11348 11349 //===----------------------------------------------------------------------===// 11350 // ScalarEvolution Class Implementation 11351 //===----------------------------------------------------------------------===// 11352 11353 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11354 AssumptionCache &AC, DominatorTree &DT, 11355 LoopInfo &LI) 11356 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11357 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11358 LoopDispositions(64), BlockDispositions(64) { 11359 // To use guards for proving predicates, we need to scan every instruction in 11360 // relevant basic blocks, and not just terminators. Doing this is a waste of 11361 // time if the IR does not actually contain any calls to 11362 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11363 // 11364 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11365 // to _add_ guards to the module when there weren't any before, and wants 11366 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11367 // efficient in lieu of being smart in that rather obscure case. 11368 11369 auto *GuardDecl = F.getParent()->getFunction( 11370 Intrinsic::getName(Intrinsic::experimental_guard)); 11371 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11372 } 11373 11374 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11375 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11376 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11377 ValueExprMap(std::move(Arg.ValueExprMap)), 11378 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11379 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11380 PendingMerges(std::move(Arg.PendingMerges)), 11381 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11382 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11383 PredicatedBackedgeTakenCounts( 11384 std::move(Arg.PredicatedBackedgeTakenCounts)), 11385 ConstantEvolutionLoopExitValue( 11386 std::move(Arg.ConstantEvolutionLoopExitValue)), 11387 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11388 LoopDispositions(std::move(Arg.LoopDispositions)), 11389 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11390 BlockDispositions(std::move(Arg.BlockDispositions)), 11391 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11392 SignedRanges(std::move(Arg.SignedRanges)), 11393 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11394 UniquePreds(std::move(Arg.UniquePreds)), 11395 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11396 LoopUsers(std::move(Arg.LoopUsers)), 11397 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11398 FirstUnknown(Arg.FirstUnknown) { 11399 Arg.FirstUnknown = nullptr; 11400 } 11401 11402 ScalarEvolution::~ScalarEvolution() { 11403 // Iterate through all the SCEVUnknown instances and call their 11404 // destructors, so that they release their references to their values. 11405 for (SCEVUnknown *U = FirstUnknown; U;) { 11406 SCEVUnknown *Tmp = U; 11407 U = U->Next; 11408 Tmp->~SCEVUnknown(); 11409 } 11410 FirstUnknown = nullptr; 11411 11412 ExprValueMap.clear(); 11413 ValueExprMap.clear(); 11414 HasRecMap.clear(); 11415 11416 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11417 // that a loop had multiple computable exits. 11418 for (auto &BTCI : BackedgeTakenCounts) 11419 BTCI.second.clear(); 11420 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11421 BTCI.second.clear(); 11422 11423 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11424 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11425 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11426 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11427 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11428 } 11429 11430 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11431 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11432 } 11433 11434 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11435 const Loop *L) { 11436 // Print all inner loops first 11437 for (Loop *I : *L) 11438 PrintLoopInfo(OS, SE, I); 11439 11440 OS << "Loop "; 11441 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11442 OS << ": "; 11443 11444 SmallVector<BasicBlock *, 8> ExitBlocks; 11445 L->getExitBlocks(ExitBlocks); 11446 if (ExitBlocks.size() != 1) 11447 OS << "<multiple exits> "; 11448 11449 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11450 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 11451 } else { 11452 OS << "Unpredictable backedge-taken count. "; 11453 } 11454 11455 OS << "\n" 11456 "Loop "; 11457 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11458 OS << ": "; 11459 11460 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 11461 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 11462 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11463 OS << ", actual taken count either this or zero."; 11464 } else { 11465 OS << "Unpredictable max backedge-taken count. "; 11466 } 11467 11468 OS << "\n" 11469 "Loop "; 11470 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11471 OS << ": "; 11472 11473 SCEVUnionPredicate Pred; 11474 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11475 if (!isa<SCEVCouldNotCompute>(PBT)) { 11476 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11477 OS << " Predicates:\n"; 11478 Pred.print(OS, 4); 11479 } else { 11480 OS << "Unpredictable predicated backedge-taken count. "; 11481 } 11482 OS << "\n"; 11483 11484 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11485 OS << "Loop "; 11486 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11487 OS << ": "; 11488 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11489 } 11490 } 11491 11492 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11493 switch (LD) { 11494 case ScalarEvolution::LoopVariant: 11495 return "Variant"; 11496 case ScalarEvolution::LoopInvariant: 11497 return "Invariant"; 11498 case ScalarEvolution::LoopComputable: 11499 return "Computable"; 11500 } 11501 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11502 } 11503 11504 void ScalarEvolution::print(raw_ostream &OS) const { 11505 // ScalarEvolution's implementation of the print method is to print 11506 // out SCEV values of all instructions that are interesting. Doing 11507 // this potentially causes it to create new SCEV objects though, 11508 // which technically conflicts with the const qualifier. This isn't 11509 // observable from outside the class though, so casting away the 11510 // const isn't dangerous. 11511 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11512 11513 OS << "Classifying expressions for: "; 11514 F.printAsOperand(OS, /*PrintType=*/false); 11515 OS << "\n"; 11516 for (Instruction &I : instructions(F)) 11517 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11518 OS << I << '\n'; 11519 OS << " --> "; 11520 const SCEV *SV = SE.getSCEV(&I); 11521 SV->print(OS); 11522 if (!isa<SCEVCouldNotCompute>(SV)) { 11523 OS << " U: "; 11524 SE.getUnsignedRange(SV).print(OS); 11525 OS << " S: "; 11526 SE.getSignedRange(SV).print(OS); 11527 } 11528 11529 const Loop *L = LI.getLoopFor(I.getParent()); 11530 11531 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11532 if (AtUse != SV) { 11533 OS << " --> "; 11534 AtUse->print(OS); 11535 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11536 OS << " U: "; 11537 SE.getUnsignedRange(AtUse).print(OS); 11538 OS << " S: "; 11539 SE.getSignedRange(AtUse).print(OS); 11540 } 11541 } 11542 11543 if (L) { 11544 OS << "\t\t" "Exits: "; 11545 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11546 if (!SE.isLoopInvariant(ExitValue, L)) { 11547 OS << "<<Unknown>>"; 11548 } else { 11549 OS << *ExitValue; 11550 } 11551 11552 bool First = true; 11553 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11554 if (First) { 11555 OS << "\t\t" "LoopDispositions: { "; 11556 First = false; 11557 } else { 11558 OS << ", "; 11559 } 11560 11561 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11562 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11563 } 11564 11565 for (auto *InnerL : depth_first(L)) { 11566 if (InnerL == L) 11567 continue; 11568 if (First) { 11569 OS << "\t\t" "LoopDispositions: { "; 11570 First = false; 11571 } else { 11572 OS << ", "; 11573 } 11574 11575 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11576 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11577 } 11578 11579 OS << " }"; 11580 } 11581 11582 OS << "\n"; 11583 } 11584 11585 OS << "Determining loop execution counts for: "; 11586 F.printAsOperand(OS, /*PrintType=*/false); 11587 OS << "\n"; 11588 for (Loop *I : LI) 11589 PrintLoopInfo(OS, &SE, I); 11590 } 11591 11592 ScalarEvolution::LoopDisposition 11593 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11594 auto &Values = LoopDispositions[S]; 11595 for (auto &V : Values) { 11596 if (V.getPointer() == L) 11597 return V.getInt(); 11598 } 11599 Values.emplace_back(L, LoopVariant); 11600 LoopDisposition D = computeLoopDisposition(S, L); 11601 auto &Values2 = LoopDispositions[S]; 11602 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11603 if (V.getPointer() == L) { 11604 V.setInt(D); 11605 break; 11606 } 11607 } 11608 return D; 11609 } 11610 11611 ScalarEvolution::LoopDisposition 11612 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11613 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11614 case scConstant: 11615 return LoopInvariant; 11616 case scTruncate: 11617 case scZeroExtend: 11618 case scSignExtend: 11619 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11620 case scAddRecExpr: { 11621 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11622 11623 // If L is the addrec's loop, it's computable. 11624 if (AR->getLoop() == L) 11625 return LoopComputable; 11626 11627 // Add recurrences are never invariant in the function-body (null loop). 11628 if (!L) 11629 return LoopVariant; 11630 11631 // Everything that is not defined at loop entry is variant. 11632 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11633 return LoopVariant; 11634 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11635 " dominate the contained loop's header?"); 11636 11637 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11638 if (AR->getLoop()->contains(L)) 11639 return LoopInvariant; 11640 11641 // This recurrence is variant w.r.t. L if any of its operands 11642 // are variant. 11643 for (auto *Op : AR->operands()) 11644 if (!isLoopInvariant(Op, L)) 11645 return LoopVariant; 11646 11647 // Otherwise it's loop-invariant. 11648 return LoopInvariant; 11649 } 11650 case scAddExpr: 11651 case scMulExpr: 11652 case scUMaxExpr: 11653 case scSMaxExpr: { 11654 bool HasVarying = false; 11655 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11656 LoopDisposition D = getLoopDisposition(Op, L); 11657 if (D == LoopVariant) 11658 return LoopVariant; 11659 if (D == LoopComputable) 11660 HasVarying = true; 11661 } 11662 return HasVarying ? LoopComputable : LoopInvariant; 11663 } 11664 case scUDivExpr: { 11665 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11666 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11667 if (LD == LoopVariant) 11668 return LoopVariant; 11669 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11670 if (RD == LoopVariant) 11671 return LoopVariant; 11672 return (LD == LoopInvariant && RD == LoopInvariant) ? 11673 LoopInvariant : LoopComputable; 11674 } 11675 case scUnknown: 11676 // All non-instruction values are loop invariant. All instructions are loop 11677 // invariant if they are not contained in the specified loop. 11678 // Instructions are never considered invariant in the function body 11679 // (null loop) because they are defined within the "loop". 11680 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11681 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11682 return LoopInvariant; 11683 case scCouldNotCompute: 11684 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11685 } 11686 llvm_unreachable("Unknown SCEV kind!"); 11687 } 11688 11689 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11690 return getLoopDisposition(S, L) == LoopInvariant; 11691 } 11692 11693 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11694 return getLoopDisposition(S, L) == LoopComputable; 11695 } 11696 11697 ScalarEvolution::BlockDisposition 11698 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11699 auto &Values = BlockDispositions[S]; 11700 for (auto &V : Values) { 11701 if (V.getPointer() == BB) 11702 return V.getInt(); 11703 } 11704 Values.emplace_back(BB, DoesNotDominateBlock); 11705 BlockDisposition D = computeBlockDisposition(S, BB); 11706 auto &Values2 = BlockDispositions[S]; 11707 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11708 if (V.getPointer() == BB) { 11709 V.setInt(D); 11710 break; 11711 } 11712 } 11713 return D; 11714 } 11715 11716 ScalarEvolution::BlockDisposition 11717 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11718 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11719 case scConstant: 11720 return ProperlyDominatesBlock; 11721 case scTruncate: 11722 case scZeroExtend: 11723 case scSignExtend: 11724 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11725 case scAddRecExpr: { 11726 // This uses a "dominates" query instead of "properly dominates" query 11727 // to test for proper dominance too, because the instruction which 11728 // produces the addrec's value is a PHI, and a PHI effectively properly 11729 // dominates its entire containing block. 11730 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11731 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11732 return DoesNotDominateBlock; 11733 11734 // Fall through into SCEVNAryExpr handling. 11735 LLVM_FALLTHROUGH; 11736 } 11737 case scAddExpr: 11738 case scMulExpr: 11739 case scUMaxExpr: 11740 case scSMaxExpr: { 11741 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11742 bool Proper = true; 11743 for (const SCEV *NAryOp : NAry->operands()) { 11744 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11745 if (D == DoesNotDominateBlock) 11746 return DoesNotDominateBlock; 11747 if (D == DominatesBlock) 11748 Proper = false; 11749 } 11750 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11751 } 11752 case scUDivExpr: { 11753 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11754 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11755 BlockDisposition LD = getBlockDisposition(LHS, BB); 11756 if (LD == DoesNotDominateBlock) 11757 return DoesNotDominateBlock; 11758 BlockDisposition RD = getBlockDisposition(RHS, BB); 11759 if (RD == DoesNotDominateBlock) 11760 return DoesNotDominateBlock; 11761 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11762 ProperlyDominatesBlock : DominatesBlock; 11763 } 11764 case scUnknown: 11765 if (Instruction *I = 11766 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11767 if (I->getParent() == BB) 11768 return DominatesBlock; 11769 if (DT.properlyDominates(I->getParent(), BB)) 11770 return ProperlyDominatesBlock; 11771 return DoesNotDominateBlock; 11772 } 11773 return ProperlyDominatesBlock; 11774 case scCouldNotCompute: 11775 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11776 } 11777 llvm_unreachable("Unknown SCEV kind!"); 11778 } 11779 11780 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11781 return getBlockDisposition(S, BB) >= DominatesBlock; 11782 } 11783 11784 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11785 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11786 } 11787 11788 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11789 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11790 } 11791 11792 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11793 auto IsS = [&](const SCEV *X) { return S == X; }; 11794 auto ContainsS = [&](const SCEV *X) { 11795 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11796 }; 11797 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11798 } 11799 11800 void 11801 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11802 ValuesAtScopes.erase(S); 11803 LoopDispositions.erase(S); 11804 BlockDispositions.erase(S); 11805 UnsignedRanges.erase(S); 11806 SignedRanges.erase(S); 11807 ExprValueMap.erase(S); 11808 HasRecMap.erase(S); 11809 MinTrailingZerosCache.erase(S); 11810 11811 for (auto I = PredicatedSCEVRewrites.begin(); 11812 I != PredicatedSCEVRewrites.end();) { 11813 std::pair<const SCEV *, const Loop *> Entry = I->first; 11814 if (Entry.first == S) 11815 PredicatedSCEVRewrites.erase(I++); 11816 else 11817 ++I; 11818 } 11819 11820 auto RemoveSCEVFromBackedgeMap = 11821 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11822 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11823 BackedgeTakenInfo &BEInfo = I->second; 11824 if (BEInfo.hasOperand(S, this)) { 11825 BEInfo.clear(); 11826 Map.erase(I++); 11827 } else 11828 ++I; 11829 } 11830 }; 11831 11832 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11833 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11834 } 11835 11836 void 11837 ScalarEvolution::getUsedLoops(const SCEV *S, 11838 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11839 struct FindUsedLoops { 11840 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11841 : LoopsUsed(LoopsUsed) {} 11842 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11843 bool follow(const SCEV *S) { 11844 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11845 LoopsUsed.insert(AR->getLoop()); 11846 return true; 11847 } 11848 11849 bool isDone() const { return false; } 11850 }; 11851 11852 FindUsedLoops F(LoopsUsed); 11853 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11854 } 11855 11856 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11857 SmallPtrSet<const Loop *, 8> LoopsUsed; 11858 getUsedLoops(S, LoopsUsed); 11859 for (auto *L : LoopsUsed) 11860 LoopUsers[L].push_back(S); 11861 } 11862 11863 void ScalarEvolution::verify() const { 11864 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11865 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11866 11867 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11868 11869 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11870 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11871 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11872 11873 const SCEV *visitConstant(const SCEVConstant *Constant) { 11874 return SE.getConstant(Constant->getAPInt()); 11875 } 11876 11877 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11878 return SE.getUnknown(Expr->getValue()); 11879 } 11880 11881 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11882 return SE.getCouldNotCompute(); 11883 } 11884 }; 11885 11886 SCEVMapper SCM(SE2); 11887 11888 while (!LoopStack.empty()) { 11889 auto *L = LoopStack.pop_back_val(); 11890 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11891 11892 auto *CurBECount = SCM.visit( 11893 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11894 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11895 11896 if (CurBECount == SE2.getCouldNotCompute() || 11897 NewBECount == SE2.getCouldNotCompute()) { 11898 // NB! This situation is legal, but is very suspicious -- whatever pass 11899 // change the loop to make a trip count go from could not compute to 11900 // computable or vice-versa *should have* invalidated SCEV. However, we 11901 // choose not to assert here (for now) since we don't want false 11902 // positives. 11903 continue; 11904 } 11905 11906 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11907 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11908 // not propagate undef aggressively). This means we can (and do) fail 11909 // verification in cases where a transform makes the trip count of a loop 11910 // go from "undef" to "undef+1" (say). The transform is fine, since in 11911 // both cases the loop iterates "undef" times, but SCEV thinks we 11912 // increased the trip count of the loop by 1 incorrectly. 11913 continue; 11914 } 11915 11916 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11917 SE.getTypeSizeInBits(NewBECount->getType())) 11918 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11919 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11920 SE.getTypeSizeInBits(NewBECount->getType())) 11921 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11922 11923 auto *ConstantDelta = 11924 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 11925 11926 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 11927 dbgs() << "Trip Count Changed!\n"; 11928 dbgs() << "Old: " << *CurBECount << "\n"; 11929 dbgs() << "New: " << *NewBECount << "\n"; 11930 dbgs() << "Delta: " << *ConstantDelta << "\n"; 11931 std::abort(); 11932 } 11933 } 11934 } 11935 11936 bool ScalarEvolution::invalidate( 11937 Function &F, const PreservedAnalyses &PA, 11938 FunctionAnalysisManager::Invalidator &Inv) { 11939 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11940 // of its dependencies is invalidated. 11941 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11942 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11943 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11944 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11945 Inv.invalidate<LoopAnalysis>(F, PA); 11946 } 11947 11948 AnalysisKey ScalarEvolutionAnalysis::Key; 11949 11950 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11951 FunctionAnalysisManager &AM) { 11952 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11953 AM.getResult<AssumptionAnalysis>(F), 11954 AM.getResult<DominatorTreeAnalysis>(F), 11955 AM.getResult<LoopAnalysis>(F)); 11956 } 11957 11958 PreservedAnalyses 11959 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11960 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11961 return PreservedAnalyses::all(); 11962 } 11963 11964 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 11965 "Scalar Evolution Analysis", false, true) 11966 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 11967 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 11968 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 11969 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 11970 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 11971 "Scalar Evolution Analysis", false, true) 11972 11973 char ScalarEvolutionWrapperPass::ID = 0; 11974 11975 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 11976 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 11977 } 11978 11979 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 11980 SE.reset(new ScalarEvolution( 11981 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 11982 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 11983 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 11984 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 11985 return false; 11986 } 11987 11988 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 11989 11990 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 11991 SE->print(OS); 11992 } 11993 11994 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 11995 if (!VerifySCEV) 11996 return; 11997 11998 SE->verify(); 11999 } 12000 12001 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12002 AU.setPreservesAll(); 12003 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12004 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12005 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12006 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12007 } 12008 12009 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12010 const SCEV *RHS) { 12011 FoldingSetNodeID ID; 12012 assert(LHS->getType() == RHS->getType() && 12013 "Type mismatch between LHS and RHS"); 12014 // Unique this node based on the arguments 12015 ID.AddInteger(SCEVPredicate::P_Equal); 12016 ID.AddPointer(LHS); 12017 ID.AddPointer(RHS); 12018 void *IP = nullptr; 12019 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12020 return S; 12021 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12022 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12023 UniquePreds.InsertNode(Eq, IP); 12024 return Eq; 12025 } 12026 12027 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12028 const SCEVAddRecExpr *AR, 12029 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12030 FoldingSetNodeID ID; 12031 // Unique this node based on the arguments 12032 ID.AddInteger(SCEVPredicate::P_Wrap); 12033 ID.AddPointer(AR); 12034 ID.AddInteger(AddedFlags); 12035 void *IP = nullptr; 12036 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12037 return S; 12038 auto *OF = new (SCEVAllocator) 12039 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12040 UniquePreds.InsertNode(OF, IP); 12041 return OF; 12042 } 12043 12044 namespace { 12045 12046 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12047 public: 12048 12049 /// Rewrites \p S in the context of a loop L and the SCEV predication 12050 /// infrastructure. 12051 /// 12052 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12053 /// equivalences present in \p Pred. 12054 /// 12055 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12056 /// \p NewPreds such that the result will be an AddRecExpr. 12057 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12058 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12059 SCEVUnionPredicate *Pred) { 12060 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12061 return Rewriter.visit(S); 12062 } 12063 12064 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12065 if (Pred) { 12066 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12067 for (auto *Pred : ExprPreds) 12068 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12069 if (IPred->getLHS() == Expr) 12070 return IPred->getRHS(); 12071 } 12072 return convertToAddRecWithPreds(Expr); 12073 } 12074 12075 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12076 const SCEV *Operand = visit(Expr->getOperand()); 12077 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12078 if (AR && AR->getLoop() == L && AR->isAffine()) { 12079 // This couldn't be folded because the operand didn't have the nuw 12080 // flag. Add the nusw flag as an assumption that we could make. 12081 const SCEV *Step = AR->getStepRecurrence(SE); 12082 Type *Ty = Expr->getType(); 12083 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12084 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12085 SE.getSignExtendExpr(Step, Ty), L, 12086 AR->getNoWrapFlags()); 12087 } 12088 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12089 } 12090 12091 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12092 const SCEV *Operand = visit(Expr->getOperand()); 12093 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12094 if (AR && AR->getLoop() == L && AR->isAffine()) { 12095 // This couldn't be folded because the operand didn't have the nsw 12096 // flag. Add the nssw flag as an assumption that we could make. 12097 const SCEV *Step = AR->getStepRecurrence(SE); 12098 Type *Ty = Expr->getType(); 12099 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12100 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12101 SE.getSignExtendExpr(Step, Ty), L, 12102 AR->getNoWrapFlags()); 12103 } 12104 return SE.getSignExtendExpr(Operand, Expr->getType()); 12105 } 12106 12107 private: 12108 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12109 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12110 SCEVUnionPredicate *Pred) 12111 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12112 12113 bool addOverflowAssumption(const SCEVPredicate *P) { 12114 if (!NewPreds) { 12115 // Check if we've already made this assumption. 12116 return Pred && Pred->implies(P); 12117 } 12118 NewPreds->insert(P); 12119 return true; 12120 } 12121 12122 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12123 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12124 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12125 return addOverflowAssumption(A); 12126 } 12127 12128 // If \p Expr represents a PHINode, we try to see if it can be represented 12129 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12130 // to add this predicate as a runtime overflow check, we return the AddRec. 12131 // If \p Expr does not meet these conditions (is not a PHI node, or we 12132 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12133 // return \p Expr. 12134 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12135 if (!isa<PHINode>(Expr->getValue())) 12136 return Expr; 12137 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12138 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12139 if (!PredicatedRewrite) 12140 return Expr; 12141 for (auto *P : PredicatedRewrite->second){ 12142 // Wrap predicates from outer loops are not supported. 12143 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12144 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12145 if (L != AR->getLoop()) 12146 return Expr; 12147 } 12148 if (!addOverflowAssumption(P)) 12149 return Expr; 12150 } 12151 return PredicatedRewrite->first; 12152 } 12153 12154 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12155 SCEVUnionPredicate *Pred; 12156 const Loop *L; 12157 }; 12158 12159 } // end anonymous namespace 12160 12161 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12162 SCEVUnionPredicate &Preds) { 12163 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12164 } 12165 12166 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12167 const SCEV *S, const Loop *L, 12168 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12169 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12170 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12171 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12172 12173 if (!AddRec) 12174 return nullptr; 12175 12176 // Since the transformation was successful, we can now transfer the SCEV 12177 // predicates. 12178 for (auto *P : TransformPreds) 12179 Preds.insert(P); 12180 12181 return AddRec; 12182 } 12183 12184 /// SCEV predicates 12185 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12186 SCEVPredicateKind Kind) 12187 : FastID(ID), Kind(Kind) {} 12188 12189 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12190 const SCEV *LHS, const SCEV *RHS) 12191 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12192 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12193 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12194 } 12195 12196 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12197 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12198 12199 if (!Op) 12200 return false; 12201 12202 return Op->LHS == LHS && Op->RHS == RHS; 12203 } 12204 12205 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12206 12207 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12208 12209 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12210 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12211 } 12212 12213 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12214 const SCEVAddRecExpr *AR, 12215 IncrementWrapFlags Flags) 12216 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12217 12218 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12219 12220 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12221 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12222 12223 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12224 } 12225 12226 bool SCEVWrapPredicate::isAlwaysTrue() const { 12227 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12228 IncrementWrapFlags IFlags = Flags; 12229 12230 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12231 IFlags = clearFlags(IFlags, IncrementNSSW); 12232 12233 return IFlags == IncrementAnyWrap; 12234 } 12235 12236 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12237 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12238 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12239 OS << "<nusw>"; 12240 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12241 OS << "<nssw>"; 12242 OS << "\n"; 12243 } 12244 12245 SCEVWrapPredicate::IncrementWrapFlags 12246 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12247 ScalarEvolution &SE) { 12248 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12249 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12250 12251 // We can safely transfer the NSW flag as NSSW. 12252 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12253 ImpliedFlags = IncrementNSSW; 12254 12255 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12256 // If the increment is positive, the SCEV NUW flag will also imply the 12257 // WrapPredicate NUSW flag. 12258 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12259 if (Step->getValue()->getValue().isNonNegative()) 12260 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12261 } 12262 12263 return ImpliedFlags; 12264 } 12265 12266 /// Union predicates don't get cached so create a dummy set ID for it. 12267 SCEVUnionPredicate::SCEVUnionPredicate() 12268 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12269 12270 bool SCEVUnionPredicate::isAlwaysTrue() const { 12271 return all_of(Preds, 12272 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12273 } 12274 12275 ArrayRef<const SCEVPredicate *> 12276 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12277 auto I = SCEVToPreds.find(Expr); 12278 if (I == SCEVToPreds.end()) 12279 return ArrayRef<const SCEVPredicate *>(); 12280 return I->second; 12281 } 12282 12283 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12284 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12285 return all_of(Set->Preds, 12286 [this](const SCEVPredicate *I) { return this->implies(I); }); 12287 12288 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12289 if (ScevPredsIt == SCEVToPreds.end()) 12290 return false; 12291 auto &SCEVPreds = ScevPredsIt->second; 12292 12293 return any_of(SCEVPreds, 12294 [N](const SCEVPredicate *I) { return I->implies(N); }); 12295 } 12296 12297 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12298 12299 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12300 for (auto Pred : Preds) 12301 Pred->print(OS, Depth); 12302 } 12303 12304 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12305 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12306 for (auto Pred : Set->Preds) 12307 add(Pred); 12308 return; 12309 } 12310 12311 if (implies(N)) 12312 return; 12313 12314 const SCEV *Key = N->getExpr(); 12315 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12316 " associated expression!"); 12317 12318 SCEVToPreds[Key].push_back(N); 12319 Preds.push_back(N); 12320 } 12321 12322 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12323 Loop &L) 12324 : SE(SE), L(L) {} 12325 12326 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12327 const SCEV *Expr = SE.getSCEV(V); 12328 RewriteEntry &Entry = RewriteMap[Expr]; 12329 12330 // If we already have an entry and the version matches, return it. 12331 if (Entry.second && Generation == Entry.first) 12332 return Entry.second; 12333 12334 // We found an entry but it's stale. Rewrite the stale entry 12335 // according to the current predicate. 12336 if (Entry.second) 12337 Expr = Entry.second; 12338 12339 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12340 Entry = {Generation, NewSCEV}; 12341 12342 return NewSCEV; 12343 } 12344 12345 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12346 if (!BackedgeCount) { 12347 SCEVUnionPredicate BackedgePred; 12348 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12349 addPredicate(BackedgePred); 12350 } 12351 return BackedgeCount; 12352 } 12353 12354 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12355 if (Preds.implies(&Pred)) 12356 return; 12357 Preds.add(&Pred); 12358 updateGeneration(); 12359 } 12360 12361 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12362 return Preds; 12363 } 12364 12365 void PredicatedScalarEvolution::updateGeneration() { 12366 // If the generation number wrapped recompute everything. 12367 if (++Generation == 0) { 12368 for (auto &II : RewriteMap) { 12369 const SCEV *Rewritten = II.second.second; 12370 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12371 } 12372 } 12373 } 12374 12375 void PredicatedScalarEvolution::setNoOverflow( 12376 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12377 const SCEV *Expr = getSCEV(V); 12378 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12379 12380 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12381 12382 // Clear the statically implied flags. 12383 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12384 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12385 12386 auto II = FlagsMap.insert({V, Flags}); 12387 if (!II.second) 12388 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12389 } 12390 12391 bool PredicatedScalarEvolution::hasNoOverflow( 12392 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12393 const SCEV *Expr = getSCEV(V); 12394 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12395 12396 Flags = SCEVWrapPredicate::clearFlags( 12397 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12398 12399 auto II = FlagsMap.find(V); 12400 12401 if (II != FlagsMap.end()) 12402 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12403 12404 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12405 } 12406 12407 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12408 const SCEV *Expr = this->getSCEV(V); 12409 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12410 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12411 12412 if (!New) 12413 return nullptr; 12414 12415 for (auto *P : NewPreds) 12416 Preds.add(P); 12417 12418 updateGeneration(); 12419 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12420 return New; 12421 } 12422 12423 PredicatedScalarEvolution::PredicatedScalarEvolution( 12424 const PredicatedScalarEvolution &Init) 12425 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12426 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12427 for (const auto &I : Init.FlagsMap) 12428 FlagsMap.insert(I); 12429 } 12430 12431 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12432 // For each block. 12433 for (auto *BB : L.getBlocks()) 12434 for (auto &I : *BB) { 12435 if (!SE.isSCEVable(I.getType())) 12436 continue; 12437 12438 auto *Expr = SE.getSCEV(&I); 12439 auto II = RewriteMap.find(Expr); 12440 12441 if (II == RewriteMap.end()) 12442 continue; 12443 12444 // Don't print things that are not interesting. 12445 if (II->second.second == Expr) 12446 continue; 12447 12448 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12449 OS.indent(Depth + 2) << *Expr << "\n"; 12450 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12451 } 12452 } 12453 12454 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12455 // arbitrary expressions. 12456 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12457 // 4, A / B becomes X / 8). 12458 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12459 const SCEV *&RHS) { 12460 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12461 if (Add == nullptr || Add->getNumOperands() != 2) 12462 return false; 12463 12464 const SCEV *A = Add->getOperand(1); 12465 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12466 12467 if (Mul == nullptr) 12468 return false; 12469 12470 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12471 // (SomeExpr + (-(SomeExpr / B) * B)). 12472 if (Expr == getURemExpr(A, B)) { 12473 LHS = A; 12474 RHS = B; 12475 return true; 12476 } 12477 return false; 12478 }; 12479 12480 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12481 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12482 return MatchURemWithDivisor(Mul->getOperand(1)) || 12483 MatchURemWithDivisor(Mul->getOperand(2)); 12484 12485 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12486 if (Mul->getNumOperands() == 2) 12487 return MatchURemWithDivisor(Mul->getOperand(1)) || 12488 MatchURemWithDivisor(Mul->getOperand(0)) || 12489 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12490 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12491 return false; 12492 } 12493