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 MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden, 206 cl::desc("Maximum depth of recursive SExt/ZExt"), 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 //===----------------------------------------------------------------------===// 215 // SCEV class definitions 216 //===----------------------------------------------------------------------===// 217 218 //===----------------------------------------------------------------------===// 219 // Implementation of the SCEV class. 220 // 221 222 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 223 LLVM_DUMP_METHOD void SCEV::dump() const { 224 print(dbgs()); 225 dbgs() << '\n'; 226 } 227 #endif 228 229 void SCEV::print(raw_ostream &OS) const { 230 switch (static_cast<SCEVTypes>(getSCEVType())) { 231 case scConstant: 232 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 233 return; 234 case scTruncate: { 235 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 236 const SCEV *Op = Trunc->getOperand(); 237 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 238 << *Trunc->getType() << ")"; 239 return; 240 } 241 case scZeroExtend: { 242 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 243 const SCEV *Op = ZExt->getOperand(); 244 OS << "(zext " << *Op->getType() << " " << *Op << " to " 245 << *ZExt->getType() << ")"; 246 return; 247 } 248 case scSignExtend: { 249 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 250 const SCEV *Op = SExt->getOperand(); 251 OS << "(sext " << *Op->getType() << " " << *Op << " to " 252 << *SExt->getType() << ")"; 253 return; 254 } 255 case scAddRecExpr: { 256 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 257 OS << "{" << *AR->getOperand(0); 258 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 259 OS << ",+," << *AR->getOperand(i); 260 OS << "}<"; 261 if (AR->hasNoUnsignedWrap()) 262 OS << "nuw><"; 263 if (AR->hasNoSignedWrap()) 264 OS << "nsw><"; 265 if (AR->hasNoSelfWrap() && 266 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 267 OS << "nw><"; 268 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 269 OS << ">"; 270 return; 271 } 272 case scAddExpr: 273 case scMulExpr: 274 case scUMaxExpr: 275 case scSMaxExpr: { 276 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 277 const char *OpStr = nullptr; 278 switch (NAry->getSCEVType()) { 279 case scAddExpr: OpStr = " + "; break; 280 case scMulExpr: OpStr = " * "; break; 281 case scUMaxExpr: OpStr = " umax "; break; 282 case scSMaxExpr: OpStr = " smax "; break; 283 } 284 OS << "("; 285 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 286 I != E; ++I) { 287 OS << **I; 288 if (std::next(I) != E) 289 OS << OpStr; 290 } 291 OS << ")"; 292 switch (NAry->getSCEVType()) { 293 case scAddExpr: 294 case scMulExpr: 295 if (NAry->hasNoUnsignedWrap()) 296 OS << "<nuw>"; 297 if (NAry->hasNoSignedWrap()) 298 OS << "<nsw>"; 299 } 300 return; 301 } 302 case scUDivExpr: { 303 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 304 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 305 return; 306 } 307 case scUnknown: { 308 const SCEVUnknown *U = cast<SCEVUnknown>(this); 309 Type *AllocTy; 310 if (U->isSizeOf(AllocTy)) { 311 OS << "sizeof(" << *AllocTy << ")"; 312 return; 313 } 314 if (U->isAlignOf(AllocTy)) { 315 OS << "alignof(" << *AllocTy << ")"; 316 return; 317 } 318 319 Type *CTy; 320 Constant *FieldNo; 321 if (U->isOffsetOf(CTy, FieldNo)) { 322 OS << "offsetof(" << *CTy << ", "; 323 FieldNo->printAsOperand(OS, false); 324 OS << ")"; 325 return; 326 } 327 328 // Otherwise just print it normally. 329 U->getValue()->printAsOperand(OS, false); 330 return; 331 } 332 case scCouldNotCompute: 333 OS << "***COULDNOTCOMPUTE***"; 334 return; 335 } 336 llvm_unreachable("Unknown SCEV kind!"); 337 } 338 339 Type *SCEV::getType() const { 340 switch (static_cast<SCEVTypes>(getSCEVType())) { 341 case scConstant: 342 return cast<SCEVConstant>(this)->getType(); 343 case scTruncate: 344 case scZeroExtend: 345 case scSignExtend: 346 return cast<SCEVCastExpr>(this)->getType(); 347 case scAddRecExpr: 348 case scMulExpr: 349 case scUMaxExpr: 350 case scSMaxExpr: 351 return cast<SCEVNAryExpr>(this)->getType(); 352 case scAddExpr: 353 return cast<SCEVAddExpr>(this)->getType(); 354 case scUDivExpr: 355 return cast<SCEVUDivExpr>(this)->getType(); 356 case scUnknown: 357 return cast<SCEVUnknown>(this)->getType(); 358 case scCouldNotCompute: 359 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 360 } 361 llvm_unreachable("Unknown SCEV kind!"); 362 } 363 364 bool SCEV::isZero() const { 365 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 366 return SC->getValue()->isZero(); 367 return false; 368 } 369 370 bool SCEV::isOne() const { 371 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 372 return SC->getValue()->isOne(); 373 return false; 374 } 375 376 bool SCEV::isAllOnesValue() const { 377 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 378 return SC->getValue()->isMinusOne(); 379 return false; 380 } 381 382 bool SCEV::isNonConstantNegative() const { 383 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 384 if (!Mul) return false; 385 386 // If there is a constant factor, it will be first. 387 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 388 if (!SC) return false; 389 390 // Return true if the value is negative, this matches things like (-42 * V). 391 return SC->getAPInt().isNegative(); 392 } 393 394 SCEVCouldNotCompute::SCEVCouldNotCompute() : 395 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 396 397 bool SCEVCouldNotCompute::classof(const SCEV *S) { 398 return S->getSCEVType() == scCouldNotCompute; 399 } 400 401 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 402 FoldingSetNodeID ID; 403 ID.AddInteger(scConstant); 404 ID.AddPointer(V); 405 void *IP = nullptr; 406 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 407 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 408 UniqueSCEVs.InsertNode(S, IP); 409 return S; 410 } 411 412 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 413 return getConstant(ConstantInt::get(getContext(), Val)); 414 } 415 416 const SCEV * 417 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 418 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 419 return getConstant(ConstantInt::get(ITy, V, isSigned)); 420 } 421 422 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 423 unsigned SCEVTy, const SCEV *op, Type *ty) 424 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {} 425 426 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 427 const SCEV *op, Type *ty) 428 : SCEVCastExpr(ID, scTruncate, op, ty) { 429 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 430 "Cannot truncate non-integer value!"); 431 } 432 433 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 434 const SCEV *op, Type *ty) 435 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 436 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 437 "Cannot zero extend non-integer value!"); 438 } 439 440 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 441 const SCEV *op, Type *ty) 442 : SCEVCastExpr(ID, scSignExtend, op, ty) { 443 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 444 "Cannot sign extend non-integer value!"); 445 } 446 447 void SCEVUnknown::deleted() { 448 // Clear this SCEVUnknown from various maps. 449 SE->forgetMemoizedResults(this); 450 451 // Remove this SCEVUnknown from the uniquing map. 452 SE->UniqueSCEVs.RemoveNode(this); 453 454 // Release the value. 455 setValPtr(nullptr); 456 } 457 458 void SCEVUnknown::allUsesReplacedWith(Value *New) { 459 // Remove this SCEVUnknown from the uniquing map. 460 SE->UniqueSCEVs.RemoveNode(this); 461 462 // Update this SCEVUnknown to point to the new value. This is needed 463 // because there may still be outstanding SCEVs which still point to 464 // this SCEVUnknown. 465 setValPtr(New); 466 } 467 468 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 469 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 470 if (VCE->getOpcode() == Instruction::PtrToInt) 471 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 472 if (CE->getOpcode() == Instruction::GetElementPtr && 473 CE->getOperand(0)->isNullValue() && 474 CE->getNumOperands() == 2) 475 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 476 if (CI->isOne()) { 477 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 478 ->getElementType(); 479 return true; 480 } 481 482 return false; 483 } 484 485 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 486 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 487 if (VCE->getOpcode() == Instruction::PtrToInt) 488 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 489 if (CE->getOpcode() == Instruction::GetElementPtr && 490 CE->getOperand(0)->isNullValue()) { 491 Type *Ty = 492 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 493 if (StructType *STy = dyn_cast<StructType>(Ty)) 494 if (!STy->isPacked() && 495 CE->getNumOperands() == 3 && 496 CE->getOperand(1)->isNullValue()) { 497 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 498 if (CI->isOne() && 499 STy->getNumElements() == 2 && 500 STy->getElementType(0)->isIntegerTy(1)) { 501 AllocTy = STy->getElementType(1); 502 return true; 503 } 504 } 505 } 506 507 return false; 508 } 509 510 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 511 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 512 if (VCE->getOpcode() == Instruction::PtrToInt) 513 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 514 if (CE->getOpcode() == Instruction::GetElementPtr && 515 CE->getNumOperands() == 3 && 516 CE->getOperand(0)->isNullValue() && 517 CE->getOperand(1)->isNullValue()) { 518 Type *Ty = 519 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 520 // Ignore vector types here so that ScalarEvolutionExpander doesn't 521 // emit getelementptrs that index into vectors. 522 if (Ty->isStructTy() || Ty->isArrayTy()) { 523 CTy = Ty; 524 FieldNo = CE->getOperand(2); 525 return true; 526 } 527 } 528 529 return false; 530 } 531 532 //===----------------------------------------------------------------------===// 533 // SCEV Utilities 534 //===----------------------------------------------------------------------===// 535 536 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 537 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 538 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 539 /// have been previously deemed to be "equally complex" by this routine. It is 540 /// intended to avoid exponential time complexity in cases like: 541 /// 542 /// %a = f(%x, %y) 543 /// %b = f(%a, %a) 544 /// %c = f(%b, %b) 545 /// 546 /// %d = f(%x, %y) 547 /// %e = f(%d, %d) 548 /// %f = f(%e, %e) 549 /// 550 /// CompareValueComplexity(%f, %c) 551 /// 552 /// Since we do not continue running this routine on expression trees once we 553 /// have seen unequal values, there is no need to track them in the cache. 554 static int 555 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 556 const LoopInfo *const LI, Value *LV, Value *RV, 557 unsigned Depth) { 558 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 559 return 0; 560 561 // Order pointer values after integer values. This helps SCEVExpander form 562 // GEPs. 563 bool LIsPointer = LV->getType()->isPointerTy(), 564 RIsPointer = RV->getType()->isPointerTy(); 565 if (LIsPointer != RIsPointer) 566 return (int)LIsPointer - (int)RIsPointer; 567 568 // Compare getValueID values. 569 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 570 if (LID != RID) 571 return (int)LID - (int)RID; 572 573 // Sort arguments by their position. 574 if (const auto *LA = dyn_cast<Argument>(LV)) { 575 const auto *RA = cast<Argument>(RV); 576 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 577 return (int)LArgNo - (int)RArgNo; 578 } 579 580 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 581 const auto *RGV = cast<GlobalValue>(RV); 582 583 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 584 auto LT = GV->getLinkage(); 585 return !(GlobalValue::isPrivateLinkage(LT) || 586 GlobalValue::isInternalLinkage(LT)); 587 }; 588 589 // Use the names to distinguish the two values, but only if the 590 // names are semantically important. 591 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 592 return LGV->getName().compare(RGV->getName()); 593 } 594 595 // For instructions, compare their loop depth, and their operand count. This 596 // is pretty loose. 597 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 598 const auto *RInst = cast<Instruction>(RV); 599 600 // Compare loop depths. 601 const BasicBlock *LParent = LInst->getParent(), 602 *RParent = RInst->getParent(); 603 if (LParent != RParent) { 604 unsigned LDepth = LI->getLoopDepth(LParent), 605 RDepth = LI->getLoopDepth(RParent); 606 if (LDepth != RDepth) 607 return (int)LDepth - (int)RDepth; 608 } 609 610 // Compare the number of operands. 611 unsigned LNumOps = LInst->getNumOperands(), 612 RNumOps = RInst->getNumOperands(); 613 if (LNumOps != RNumOps) 614 return (int)LNumOps - (int)RNumOps; 615 616 for (unsigned Idx : seq(0u, LNumOps)) { 617 int Result = 618 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 619 RInst->getOperand(Idx), Depth + 1); 620 if (Result != 0) 621 return Result; 622 } 623 } 624 625 EqCacheValue.unionSets(LV, RV); 626 return 0; 627 } 628 629 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 630 // than RHS, respectively. A three-way result allows recursive comparisons to be 631 // more efficient. 632 static int CompareSCEVComplexity( 633 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 634 EquivalenceClasses<const Value *> &EqCacheValue, 635 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 636 DominatorTree &DT, unsigned Depth = 0) { 637 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 638 if (LHS == RHS) 639 return 0; 640 641 // Primarily, sort the SCEVs by their getSCEVType(). 642 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 643 if (LType != RType) 644 return (int)LType - (int)RType; 645 646 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 647 return 0; 648 // Aside from the getSCEVType() ordering, the particular ordering 649 // isn't very important except that it's beneficial to be consistent, 650 // so that (a + b) and (b + a) don't end up as different expressions. 651 switch (static_cast<SCEVTypes>(LType)) { 652 case scUnknown: { 653 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 654 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 655 656 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 657 RU->getValue(), Depth + 1); 658 if (X == 0) 659 EqCacheSCEV.unionSets(LHS, RHS); 660 return X; 661 } 662 663 case scConstant: { 664 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 665 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 666 667 // Compare constant values. 668 const APInt &LA = LC->getAPInt(); 669 const APInt &RA = RC->getAPInt(); 670 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 671 if (LBitWidth != RBitWidth) 672 return (int)LBitWidth - (int)RBitWidth; 673 return LA.ult(RA) ? -1 : 1; 674 } 675 676 case scAddRecExpr: { 677 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 678 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 679 680 // There is always a dominance between two recs that are used by one SCEV, 681 // so we can safely sort recs by loop header dominance. We require such 682 // order in getAddExpr. 683 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 684 if (LLoop != RLoop) { 685 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 686 assert(LHead != RHead && "Two loops share the same header?"); 687 if (DT.dominates(LHead, RHead)) 688 return 1; 689 else 690 assert(DT.dominates(RHead, LHead) && 691 "No dominance between recurrences used by one SCEV?"); 692 return -1; 693 } 694 695 // Addrec complexity grows with operand count. 696 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 697 if (LNumOps != RNumOps) 698 return (int)LNumOps - (int)RNumOps; 699 700 // Lexicographically compare. 701 for (unsigned i = 0; i != LNumOps; ++i) { 702 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 703 LA->getOperand(i), RA->getOperand(i), DT, 704 Depth + 1); 705 if (X != 0) 706 return X; 707 } 708 EqCacheSCEV.unionSets(LHS, RHS); 709 return 0; 710 } 711 712 case scAddExpr: 713 case scMulExpr: 714 case scSMaxExpr: 715 case scUMaxExpr: { 716 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 717 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 718 719 // Lexicographically compare n-ary expressions. 720 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 721 if (LNumOps != RNumOps) 722 return (int)LNumOps - (int)RNumOps; 723 724 for (unsigned i = 0; i != LNumOps; ++i) { 725 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 726 LC->getOperand(i), RC->getOperand(i), DT, 727 Depth + 1); 728 if (X != 0) 729 return X; 730 } 731 EqCacheSCEV.unionSets(LHS, RHS); 732 return 0; 733 } 734 735 case scUDivExpr: { 736 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 737 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 738 739 // Lexicographically compare udiv expressions. 740 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 741 RC->getLHS(), DT, Depth + 1); 742 if (X != 0) 743 return X; 744 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 745 RC->getRHS(), DT, Depth + 1); 746 if (X == 0) 747 EqCacheSCEV.unionSets(LHS, RHS); 748 return X; 749 } 750 751 case scTruncate: 752 case scZeroExtend: 753 case scSignExtend: { 754 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 755 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 756 757 // Compare cast expressions by operand. 758 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 759 LC->getOperand(), RC->getOperand(), DT, 760 Depth + 1); 761 if (X == 0) 762 EqCacheSCEV.unionSets(LHS, RHS); 763 return X; 764 } 765 766 case scCouldNotCompute: 767 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 768 } 769 llvm_unreachable("Unknown SCEV kind!"); 770 } 771 772 /// Given a list of SCEV objects, order them by their complexity, and group 773 /// objects of the same complexity together by value. When this routine is 774 /// finished, we know that any duplicates in the vector are consecutive and that 775 /// complexity is monotonically increasing. 776 /// 777 /// Note that we go take special precautions to ensure that we get deterministic 778 /// results from this routine. In other words, we don't want the results of 779 /// this to depend on where the addresses of various SCEV objects happened to 780 /// land in memory. 781 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 782 LoopInfo *LI, DominatorTree &DT) { 783 if (Ops.size() < 2) return; // Noop 784 785 EquivalenceClasses<const SCEV *> EqCacheSCEV; 786 EquivalenceClasses<const Value *> EqCacheValue; 787 if (Ops.size() == 2) { 788 // This is the common case, which also happens to be trivially simple. 789 // Special case it. 790 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 791 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 792 std::swap(LHS, RHS); 793 return; 794 } 795 796 // Do the rough sort by complexity. 797 std::stable_sort(Ops.begin(), Ops.end(), 798 [&](const SCEV *LHS, const SCEV *RHS) { 799 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 800 LHS, RHS, DT) < 0; 801 }); 802 803 // Now that we are sorted by complexity, group elements of the same 804 // complexity. Note that this is, at worst, N^2, but the vector is likely to 805 // be extremely short in practice. Note that we take this approach because we 806 // do not want to depend on the addresses of the objects we are grouping. 807 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 808 const SCEV *S = Ops[i]; 809 unsigned Complexity = S->getSCEVType(); 810 811 // If there are any objects of the same complexity and same value as this 812 // one, group them. 813 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 814 if (Ops[j] == S) { // Found a duplicate. 815 // Move it to immediately after i'th element. 816 std::swap(Ops[i+1], Ops[j]); 817 ++i; // no need to rescan it. 818 if (i == e-2) return; // Done! 819 } 820 } 821 } 822 } 823 824 // Returns the size of the SCEV S. 825 static inline int sizeOfSCEV(const SCEV *S) { 826 struct FindSCEVSize { 827 int Size = 0; 828 829 FindSCEVSize() = default; 830 831 bool follow(const SCEV *S) { 832 ++Size; 833 // Keep looking at all operands of S. 834 return true; 835 } 836 837 bool isDone() const { 838 return false; 839 } 840 }; 841 842 FindSCEVSize F; 843 SCEVTraversal<FindSCEVSize> ST(F); 844 ST.visitAll(S); 845 return F.Size; 846 } 847 848 namespace { 849 850 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 851 public: 852 // Computes the Quotient and Remainder of the division of Numerator by 853 // Denominator. 854 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 855 const SCEV *Denominator, const SCEV **Quotient, 856 const SCEV **Remainder) { 857 assert(Numerator && Denominator && "Uninitialized SCEV"); 858 859 SCEVDivision D(SE, Numerator, Denominator); 860 861 // Check for the trivial case here to avoid having to check for it in the 862 // rest of the code. 863 if (Numerator == Denominator) { 864 *Quotient = D.One; 865 *Remainder = D.Zero; 866 return; 867 } 868 869 if (Numerator->isZero()) { 870 *Quotient = D.Zero; 871 *Remainder = D.Zero; 872 return; 873 } 874 875 // A simple case when N/1. The quotient is N. 876 if (Denominator->isOne()) { 877 *Quotient = Numerator; 878 *Remainder = D.Zero; 879 return; 880 } 881 882 // Split the Denominator when it is a product. 883 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 884 const SCEV *Q, *R; 885 *Quotient = Numerator; 886 for (const SCEV *Op : T->operands()) { 887 divide(SE, *Quotient, Op, &Q, &R); 888 *Quotient = Q; 889 890 // Bail out when the Numerator is not divisible by one of the terms of 891 // the Denominator. 892 if (!R->isZero()) { 893 *Quotient = D.Zero; 894 *Remainder = Numerator; 895 return; 896 } 897 } 898 *Remainder = D.Zero; 899 return; 900 } 901 902 D.visit(Numerator); 903 *Quotient = D.Quotient; 904 *Remainder = D.Remainder; 905 } 906 907 // Except in the trivial case described above, we do not know how to divide 908 // Expr by Denominator for the following functions with empty implementation. 909 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 910 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 911 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 912 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 913 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 914 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 915 void visitUnknown(const SCEVUnknown *Numerator) {} 916 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 917 918 void visitConstant(const SCEVConstant *Numerator) { 919 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 920 APInt NumeratorVal = Numerator->getAPInt(); 921 APInt DenominatorVal = D->getAPInt(); 922 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 923 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 924 925 if (NumeratorBW > DenominatorBW) 926 DenominatorVal = DenominatorVal.sext(NumeratorBW); 927 else if (NumeratorBW < DenominatorBW) 928 NumeratorVal = NumeratorVal.sext(DenominatorBW); 929 930 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 931 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 932 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 933 Quotient = SE.getConstant(QuotientVal); 934 Remainder = SE.getConstant(RemainderVal); 935 return; 936 } 937 } 938 939 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 940 const SCEV *StartQ, *StartR, *StepQ, *StepR; 941 if (!Numerator->isAffine()) 942 return cannotDivide(Numerator); 943 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 944 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 945 // Bail out if the types do not match. 946 Type *Ty = Denominator->getType(); 947 if (Ty != StartQ->getType() || Ty != StartR->getType() || 948 Ty != StepQ->getType() || Ty != StepR->getType()) 949 return cannotDivide(Numerator); 950 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 951 Numerator->getNoWrapFlags()); 952 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 953 Numerator->getNoWrapFlags()); 954 } 955 956 void visitAddExpr(const SCEVAddExpr *Numerator) { 957 SmallVector<const SCEV *, 2> Qs, Rs; 958 Type *Ty = Denominator->getType(); 959 960 for (const SCEV *Op : Numerator->operands()) { 961 const SCEV *Q, *R; 962 divide(SE, Op, Denominator, &Q, &R); 963 964 // Bail out if types do not match. 965 if (Ty != Q->getType() || Ty != R->getType()) 966 return cannotDivide(Numerator); 967 968 Qs.push_back(Q); 969 Rs.push_back(R); 970 } 971 972 if (Qs.size() == 1) { 973 Quotient = Qs[0]; 974 Remainder = Rs[0]; 975 return; 976 } 977 978 Quotient = SE.getAddExpr(Qs); 979 Remainder = SE.getAddExpr(Rs); 980 } 981 982 void visitMulExpr(const SCEVMulExpr *Numerator) { 983 SmallVector<const SCEV *, 2> Qs; 984 Type *Ty = Denominator->getType(); 985 986 bool FoundDenominatorTerm = false; 987 for (const SCEV *Op : Numerator->operands()) { 988 // Bail out if types do not match. 989 if (Ty != Op->getType()) 990 return cannotDivide(Numerator); 991 992 if (FoundDenominatorTerm) { 993 Qs.push_back(Op); 994 continue; 995 } 996 997 // Check whether Denominator divides one of the product operands. 998 const SCEV *Q, *R; 999 divide(SE, Op, Denominator, &Q, &R); 1000 if (!R->isZero()) { 1001 Qs.push_back(Op); 1002 continue; 1003 } 1004 1005 // Bail out if types do not match. 1006 if (Ty != Q->getType()) 1007 return cannotDivide(Numerator); 1008 1009 FoundDenominatorTerm = true; 1010 Qs.push_back(Q); 1011 } 1012 1013 if (FoundDenominatorTerm) { 1014 Remainder = Zero; 1015 if (Qs.size() == 1) 1016 Quotient = Qs[0]; 1017 else 1018 Quotient = SE.getMulExpr(Qs); 1019 return; 1020 } 1021 1022 if (!isa<SCEVUnknown>(Denominator)) 1023 return cannotDivide(Numerator); 1024 1025 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1026 ValueToValueMap RewriteMap; 1027 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1028 cast<SCEVConstant>(Zero)->getValue(); 1029 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1030 1031 if (Remainder->isZero()) { 1032 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1033 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1034 cast<SCEVConstant>(One)->getValue(); 1035 Quotient = 1036 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1037 return; 1038 } 1039 1040 // Quotient is (Numerator - Remainder) divided by Denominator. 1041 const SCEV *Q, *R; 1042 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1043 // This SCEV does not seem to simplify: fail the division here. 1044 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1045 return cannotDivide(Numerator); 1046 divide(SE, Diff, Denominator, &Q, &R); 1047 if (R != Zero) 1048 return cannotDivide(Numerator); 1049 Quotient = Q; 1050 } 1051 1052 private: 1053 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1054 const SCEV *Denominator) 1055 : SE(S), Denominator(Denominator) { 1056 Zero = SE.getZero(Denominator->getType()); 1057 One = SE.getOne(Denominator->getType()); 1058 1059 // We generally do not know how to divide Expr by Denominator. We 1060 // initialize the division to a "cannot divide" state to simplify the rest 1061 // of the code. 1062 cannotDivide(Numerator); 1063 } 1064 1065 // Convenience function for giving up on the division. We set the quotient to 1066 // be equal to zero and the remainder to be equal to the numerator. 1067 void cannotDivide(const SCEV *Numerator) { 1068 Quotient = Zero; 1069 Remainder = Numerator; 1070 } 1071 1072 ScalarEvolution &SE; 1073 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1074 }; 1075 1076 } // end anonymous namespace 1077 1078 //===----------------------------------------------------------------------===// 1079 // Simple SCEV method implementations 1080 //===----------------------------------------------------------------------===// 1081 1082 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1083 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1084 ScalarEvolution &SE, 1085 Type *ResultTy) { 1086 // Handle the simplest case efficiently. 1087 if (K == 1) 1088 return SE.getTruncateOrZeroExtend(It, ResultTy); 1089 1090 // We are using the following formula for BC(It, K): 1091 // 1092 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1093 // 1094 // Suppose, W is the bitwidth of the return value. We must be prepared for 1095 // overflow. Hence, we must assure that the result of our computation is 1096 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1097 // safe in modular arithmetic. 1098 // 1099 // However, this code doesn't use exactly that formula; the formula it uses 1100 // is something like the following, where T is the number of factors of 2 in 1101 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1102 // exponentiation: 1103 // 1104 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1105 // 1106 // This formula is trivially equivalent to the previous formula. However, 1107 // this formula can be implemented much more efficiently. The trick is that 1108 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1109 // arithmetic. To do exact division in modular arithmetic, all we have 1110 // to do is multiply by the inverse. Therefore, this step can be done at 1111 // width W. 1112 // 1113 // The next issue is how to safely do the division by 2^T. The way this 1114 // is done is by doing the multiplication step at a width of at least W + T 1115 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1116 // when we perform the division by 2^T (which is equivalent to a right shift 1117 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1118 // truncated out after the division by 2^T. 1119 // 1120 // In comparison to just directly using the first formula, this technique 1121 // is much more efficient; using the first formula requires W * K bits, 1122 // but this formula less than W + K bits. Also, the first formula requires 1123 // a division step, whereas this formula only requires multiplies and shifts. 1124 // 1125 // It doesn't matter whether the subtraction step is done in the calculation 1126 // width or the input iteration count's width; if the subtraction overflows, 1127 // the result must be zero anyway. We prefer here to do it in the width of 1128 // the induction variable because it helps a lot for certain cases; CodeGen 1129 // isn't smart enough to ignore the overflow, which leads to much less 1130 // efficient code if the width of the subtraction is wider than the native 1131 // register width. 1132 // 1133 // (It's possible to not widen at all by pulling out factors of 2 before 1134 // the multiplication; for example, K=2 can be calculated as 1135 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1136 // extra arithmetic, so it's not an obvious win, and it gets 1137 // much more complicated for K > 3.) 1138 1139 // Protection from insane SCEVs; this bound is conservative, 1140 // but it probably doesn't matter. 1141 if (K > 1000) 1142 return SE.getCouldNotCompute(); 1143 1144 unsigned W = SE.getTypeSizeInBits(ResultTy); 1145 1146 // Calculate K! / 2^T and T; we divide out the factors of two before 1147 // multiplying for calculating K! / 2^T to avoid overflow. 1148 // Other overflow doesn't matter because we only care about the bottom 1149 // W bits of the result. 1150 APInt OddFactorial(W, 1); 1151 unsigned T = 1; 1152 for (unsigned i = 3; i <= K; ++i) { 1153 APInt Mult(W, i); 1154 unsigned TwoFactors = Mult.countTrailingZeros(); 1155 T += TwoFactors; 1156 Mult.lshrInPlace(TwoFactors); 1157 OddFactorial *= Mult; 1158 } 1159 1160 // We need at least W + T bits for the multiplication step 1161 unsigned CalculationBits = W + T; 1162 1163 // Calculate 2^T, at width T+W. 1164 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1165 1166 // Calculate the multiplicative inverse of K! / 2^T; 1167 // this multiplication factor will perform the exact division by 1168 // K! / 2^T. 1169 APInt Mod = APInt::getSignedMinValue(W+1); 1170 APInt MultiplyFactor = OddFactorial.zext(W+1); 1171 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1172 MultiplyFactor = MultiplyFactor.trunc(W); 1173 1174 // Calculate the product, at width T+W 1175 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1176 CalculationBits); 1177 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1178 for (unsigned i = 1; i != K; ++i) { 1179 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1180 Dividend = SE.getMulExpr(Dividend, 1181 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1182 } 1183 1184 // Divide by 2^T 1185 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1186 1187 // Truncate the result, and divide by K! / 2^T. 1188 1189 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1190 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1191 } 1192 1193 /// Return the value of this chain of recurrences at the specified iteration 1194 /// number. We can evaluate this recurrence by multiplying each element in the 1195 /// chain by the binomial coefficient corresponding to it. In other words, we 1196 /// can evaluate {A,+,B,+,C,+,D} as: 1197 /// 1198 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1199 /// 1200 /// where BC(It, k) stands for binomial coefficient. 1201 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1202 ScalarEvolution &SE) const { 1203 const SCEV *Result = getStart(); 1204 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1205 // The computation is correct in the face of overflow provided that the 1206 // multiplication is performed _after_ the evaluation of the binomial 1207 // coefficient. 1208 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1209 if (isa<SCEVCouldNotCompute>(Coeff)) 1210 return Coeff; 1211 1212 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1213 } 1214 return Result; 1215 } 1216 1217 //===----------------------------------------------------------------------===// 1218 // SCEV Expression folder implementations 1219 //===----------------------------------------------------------------------===// 1220 1221 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1222 Type *Ty) { 1223 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1224 "This is not a truncating conversion!"); 1225 assert(isSCEVable(Ty) && 1226 "This is not a conversion to a SCEVable type!"); 1227 Ty = getEffectiveSCEVType(Ty); 1228 1229 FoldingSetNodeID ID; 1230 ID.AddInteger(scTruncate); 1231 ID.AddPointer(Op); 1232 ID.AddPointer(Ty); 1233 void *IP = nullptr; 1234 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1235 1236 // Fold if the operand is constant. 1237 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1238 return getConstant( 1239 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1240 1241 // trunc(trunc(x)) --> trunc(x) 1242 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1243 return getTruncateExpr(ST->getOperand(), Ty); 1244 1245 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1246 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1247 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1248 1249 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1250 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1251 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1252 1253 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1254 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1255 // if after transforming we have at most one truncate, not counting truncates 1256 // that replace other casts. 1257 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1258 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1259 SmallVector<const SCEV *, 4> Operands; 1260 unsigned numTruncs = 0; 1261 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1262 ++i) { 1263 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty); 1264 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1265 numTruncs++; 1266 Operands.push_back(S); 1267 } 1268 if (numTruncs < 2) { 1269 if (isa<SCEVAddExpr>(Op)) 1270 return getAddExpr(Operands); 1271 else if (isa<SCEVMulExpr>(Op)) 1272 return getMulExpr(Operands); 1273 else 1274 llvm_unreachable("Unexpected SCEV type for Op."); 1275 } 1276 // Although we checked in the beginning that ID is not in the cache, it is 1277 // possible that during recursion and different modification ID was inserted 1278 // into the cache. So if we find it, just return it. 1279 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1280 return S; 1281 } 1282 1283 // If the input value is a chrec scev, truncate the chrec's operands. 1284 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1285 SmallVector<const SCEV *, 4> Operands; 1286 for (const SCEV *Op : AddRec->operands()) 1287 Operands.push_back(getTruncateExpr(Op, Ty)); 1288 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1289 } 1290 1291 // The cast wasn't folded; create an explicit cast node. We can reuse 1292 // the existing insert position since if we get here, we won't have 1293 // made any changes which would invalidate it. 1294 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1295 Op, Ty); 1296 UniqueSCEVs.InsertNode(S, IP); 1297 addToLoopUseLists(S); 1298 return S; 1299 } 1300 1301 // Get the limit of a recurrence such that incrementing by Step cannot cause 1302 // signed overflow as long as the value of the recurrence within the 1303 // loop does not exceed this limit before incrementing. 1304 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1305 ICmpInst::Predicate *Pred, 1306 ScalarEvolution *SE) { 1307 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1308 if (SE->isKnownPositive(Step)) { 1309 *Pred = ICmpInst::ICMP_SLT; 1310 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1311 SE->getSignedRangeMax(Step)); 1312 } 1313 if (SE->isKnownNegative(Step)) { 1314 *Pred = ICmpInst::ICMP_SGT; 1315 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1316 SE->getSignedRangeMin(Step)); 1317 } 1318 return nullptr; 1319 } 1320 1321 // Get the limit of a recurrence such that incrementing by Step cannot cause 1322 // unsigned overflow as long as the value of the recurrence within the loop does 1323 // not exceed this limit before incrementing. 1324 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1325 ICmpInst::Predicate *Pred, 1326 ScalarEvolution *SE) { 1327 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1328 *Pred = ICmpInst::ICMP_ULT; 1329 1330 return SE->getConstant(APInt::getMinValue(BitWidth) - 1331 SE->getUnsignedRangeMax(Step)); 1332 } 1333 1334 namespace { 1335 1336 struct ExtendOpTraitsBase { 1337 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1338 unsigned); 1339 }; 1340 1341 // Used to make code generic over signed and unsigned overflow. 1342 template <typename ExtendOp> struct ExtendOpTraits { 1343 // Members present: 1344 // 1345 // static const SCEV::NoWrapFlags WrapType; 1346 // 1347 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1348 // 1349 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1350 // ICmpInst::Predicate *Pred, 1351 // ScalarEvolution *SE); 1352 }; 1353 1354 template <> 1355 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1356 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1357 1358 static const GetExtendExprTy GetExtendExpr; 1359 1360 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1361 ICmpInst::Predicate *Pred, 1362 ScalarEvolution *SE) { 1363 return getSignedOverflowLimitForStep(Step, Pred, SE); 1364 } 1365 }; 1366 1367 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1368 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1369 1370 template <> 1371 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1372 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1373 1374 static const GetExtendExprTy GetExtendExpr; 1375 1376 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1377 ICmpInst::Predicate *Pred, 1378 ScalarEvolution *SE) { 1379 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1380 } 1381 }; 1382 1383 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1384 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1385 1386 } // end anonymous namespace 1387 1388 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1389 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1390 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1391 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1392 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1393 // expression "Step + sext/zext(PreIncAR)" is congruent with 1394 // "sext/zext(PostIncAR)" 1395 template <typename ExtendOpTy> 1396 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1397 ScalarEvolution *SE, unsigned Depth) { 1398 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1399 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1400 1401 const Loop *L = AR->getLoop(); 1402 const SCEV *Start = AR->getStart(); 1403 const SCEV *Step = AR->getStepRecurrence(*SE); 1404 1405 // Check for a simple looking step prior to loop entry. 1406 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1407 if (!SA) 1408 return nullptr; 1409 1410 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1411 // subtraction is expensive. For this purpose, perform a quick and dirty 1412 // difference, by checking for Step in the operand list. 1413 SmallVector<const SCEV *, 4> DiffOps; 1414 for (const SCEV *Op : SA->operands()) 1415 if (Op != Step) 1416 DiffOps.push_back(Op); 1417 1418 if (DiffOps.size() == SA->getNumOperands()) 1419 return nullptr; 1420 1421 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1422 // `Step`: 1423 1424 // 1. NSW/NUW flags on the step increment. 1425 auto PreStartFlags = 1426 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1427 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1428 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1429 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1430 1431 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1432 // "S+X does not sign/unsign-overflow". 1433 // 1434 1435 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1436 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1437 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1438 return PreStart; 1439 1440 // 2. Direct overflow check on the step operation's expression. 1441 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1442 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1443 const SCEV *OperandExtendedStart = 1444 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1445 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1446 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1447 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1448 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1449 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1450 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1451 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1452 } 1453 return PreStart; 1454 } 1455 1456 // 3. Loop precondition. 1457 ICmpInst::Predicate Pred; 1458 const SCEV *OverflowLimit = 1459 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1460 1461 if (OverflowLimit && 1462 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1463 return PreStart; 1464 1465 return nullptr; 1466 } 1467 1468 // Get the normalized zero or sign extended expression for this AddRec's Start. 1469 template <typename ExtendOpTy> 1470 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1471 ScalarEvolution *SE, 1472 unsigned Depth) { 1473 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1474 1475 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1476 if (!PreStart) 1477 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1478 1479 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1480 Depth), 1481 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1482 } 1483 1484 // Try to prove away overflow by looking at "nearby" add recurrences. A 1485 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1486 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1487 // 1488 // Formally: 1489 // 1490 // {S,+,X} == {S-T,+,X} + T 1491 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1492 // 1493 // If ({S-T,+,X} + T) does not overflow ... (1) 1494 // 1495 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1496 // 1497 // If {S-T,+,X} does not overflow ... (2) 1498 // 1499 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1500 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1501 // 1502 // If (S-T)+T does not overflow ... (3) 1503 // 1504 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1505 // == {Ext(S),+,Ext(X)} == LHS 1506 // 1507 // Thus, if (1), (2) and (3) are true for some T, then 1508 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1509 // 1510 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1511 // does not overflow" restricted to the 0th iteration. Therefore we only need 1512 // to check for (1) and (2). 1513 // 1514 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1515 // is `Delta` (defined below). 1516 template <typename ExtendOpTy> 1517 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1518 const SCEV *Step, 1519 const Loop *L) { 1520 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1521 1522 // We restrict `Start` to a constant to prevent SCEV from spending too much 1523 // time here. It is correct (but more expensive) to continue with a 1524 // non-constant `Start` and do a general SCEV subtraction to compute 1525 // `PreStart` below. 1526 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1527 if (!StartC) 1528 return false; 1529 1530 APInt StartAI = StartC->getAPInt(); 1531 1532 for (unsigned Delta : {-2, -1, 1, 2}) { 1533 const SCEV *PreStart = getConstant(StartAI - Delta); 1534 1535 FoldingSetNodeID ID; 1536 ID.AddInteger(scAddRecExpr); 1537 ID.AddPointer(PreStart); 1538 ID.AddPointer(Step); 1539 ID.AddPointer(L); 1540 void *IP = nullptr; 1541 const auto *PreAR = 1542 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1543 1544 // Give up if we don't already have the add recurrence we need because 1545 // actually constructing an add recurrence is relatively expensive. 1546 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1547 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1548 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1549 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1550 DeltaS, &Pred, this); 1551 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1552 return true; 1553 } 1554 } 1555 1556 return false; 1557 } 1558 1559 // Finds an integer D for an expression (C + x + y + ...) such that the top 1560 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1561 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1562 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1563 // the (C + x + y + ...) expression is \p WholeAddExpr. 1564 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1565 const SCEVConstant *ConstantTerm, 1566 const SCEVAddExpr *WholeAddExpr) { 1567 const APInt C = ConstantTerm->getAPInt(); 1568 const unsigned BitWidth = C.getBitWidth(); 1569 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1570 uint32_t TZ = BitWidth; 1571 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1572 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1573 if (TZ) { 1574 // Set D to be as many least significant bits of C as possible while still 1575 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1576 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1577 } 1578 return APInt(BitWidth, 0); 1579 } 1580 1581 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1582 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1583 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1584 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1585 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1586 const APInt &ConstantStart, 1587 const SCEV *Step) { 1588 const unsigned BitWidth = ConstantStart.getBitWidth(); 1589 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1590 if (TZ) 1591 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1592 : ConstantStart; 1593 return APInt(BitWidth, 0); 1594 } 1595 1596 const SCEV * 1597 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1598 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1599 "This is not an extending conversion!"); 1600 assert(isSCEVable(Ty) && 1601 "This is not a conversion to a SCEVable type!"); 1602 Ty = getEffectiveSCEVType(Ty); 1603 1604 // Fold if the operand is constant. 1605 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1606 return getConstant( 1607 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1608 1609 // zext(zext(x)) --> zext(x) 1610 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1611 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1612 1613 // Before doing any expensive analysis, check to see if we've already 1614 // computed a SCEV for this Op and Ty. 1615 FoldingSetNodeID ID; 1616 ID.AddInteger(scZeroExtend); 1617 ID.AddPointer(Op); 1618 ID.AddPointer(Ty); 1619 void *IP = nullptr; 1620 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1621 if (Depth > MaxExtDepth) { 1622 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1623 Op, Ty); 1624 UniqueSCEVs.InsertNode(S, IP); 1625 addToLoopUseLists(S); 1626 return S; 1627 } 1628 1629 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1630 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1631 // It's possible the bits taken off by the truncate were all zero bits. If 1632 // so, we should be able to simplify this further. 1633 const SCEV *X = ST->getOperand(); 1634 ConstantRange CR = getUnsignedRange(X); 1635 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1636 unsigned NewBits = getTypeSizeInBits(Ty); 1637 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1638 CR.zextOrTrunc(NewBits))) 1639 return getTruncateOrZeroExtend(X, Ty); 1640 } 1641 1642 // If the input value is a chrec scev, and we can prove that the value 1643 // did not overflow the old, smaller, value, we can zero extend all of the 1644 // operands (often constants). This allows analysis of something like 1645 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1646 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1647 if (AR->isAffine()) { 1648 const SCEV *Start = AR->getStart(); 1649 const SCEV *Step = AR->getStepRecurrence(*this); 1650 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1651 const Loop *L = AR->getLoop(); 1652 1653 if (!AR->hasNoUnsignedWrap()) { 1654 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1655 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1656 } 1657 1658 // If we have special knowledge that this addrec won't overflow, 1659 // we don't need to do any further analysis. 1660 if (AR->hasNoUnsignedWrap()) 1661 return getAddRecExpr( 1662 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1663 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1664 1665 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1666 // Note that this serves two purposes: It filters out loops that are 1667 // simply not analyzable, and it covers the case where this code is 1668 // being called from within backedge-taken count analysis, such that 1669 // attempting to ask for the backedge-taken count would likely result 1670 // in infinite recursion. In the later case, the analysis code will 1671 // cope with a conservative value, and it will take care to purge 1672 // that value once it has finished. 1673 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1674 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1675 // Manually compute the final value for AR, checking for 1676 // overflow. 1677 1678 // Check whether the backedge-taken count can be losslessly casted to 1679 // the addrec's type. The count is always unsigned. 1680 const SCEV *CastedMaxBECount = 1681 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1682 const SCEV *RecastedMaxBECount = 1683 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1684 if (MaxBECount == RecastedMaxBECount) { 1685 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1686 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1687 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1688 SCEV::FlagAnyWrap, Depth + 1); 1689 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1690 SCEV::FlagAnyWrap, 1691 Depth + 1), 1692 WideTy, Depth + 1); 1693 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1694 const SCEV *WideMaxBECount = 1695 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1696 const SCEV *OperandExtendedAdd = 1697 getAddExpr(WideStart, 1698 getMulExpr(WideMaxBECount, 1699 getZeroExtendExpr(Step, WideTy, Depth + 1), 1700 SCEV::FlagAnyWrap, Depth + 1), 1701 SCEV::FlagAnyWrap, Depth + 1); 1702 if (ZAdd == OperandExtendedAdd) { 1703 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1704 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1705 // Return the expression with the addrec on the outside. 1706 return getAddRecExpr( 1707 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1708 Depth + 1), 1709 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1710 AR->getNoWrapFlags()); 1711 } 1712 // Similar to above, only this time treat the step value as signed. 1713 // This covers loops that count down. 1714 OperandExtendedAdd = 1715 getAddExpr(WideStart, 1716 getMulExpr(WideMaxBECount, 1717 getSignExtendExpr(Step, WideTy, Depth + 1), 1718 SCEV::FlagAnyWrap, Depth + 1), 1719 SCEV::FlagAnyWrap, Depth + 1); 1720 if (ZAdd == OperandExtendedAdd) { 1721 // Cache knowledge of AR NW, which is propagated to this AddRec. 1722 // Negative step causes unsigned wrap, but it still can't self-wrap. 1723 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1724 // Return the expression with the addrec on the outside. 1725 return getAddRecExpr( 1726 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1727 Depth + 1), 1728 getSignExtendExpr(Step, Ty, Depth + 1), L, 1729 AR->getNoWrapFlags()); 1730 } 1731 } 1732 } 1733 1734 // Normally, in the cases we can prove no-overflow via a 1735 // backedge guarding condition, we can also compute a backedge 1736 // taken count for the loop. The exceptions are assumptions and 1737 // guards present in the loop -- SCEV is not great at exploiting 1738 // these to compute max backedge taken counts, but can still use 1739 // these to prove lack of overflow. Use this fact to avoid 1740 // doing extra work that may not pay off. 1741 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1742 !AC.assumptions().empty()) { 1743 // If the backedge is guarded by a comparison with the pre-inc 1744 // value the addrec is safe. Also, if the entry is guarded by 1745 // a comparison with the start value and the backedge is 1746 // guarded by a comparison with the post-inc value, the addrec 1747 // is safe. 1748 if (isKnownPositive(Step)) { 1749 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1750 getUnsignedRangeMax(Step)); 1751 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1752 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1753 // Cache knowledge of AR NUW, which is propagated to this 1754 // AddRec. 1755 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1756 // Return the expression with the addrec on the outside. 1757 return getAddRecExpr( 1758 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1759 Depth + 1), 1760 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1761 AR->getNoWrapFlags()); 1762 } 1763 } else if (isKnownNegative(Step)) { 1764 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1765 getSignedRangeMin(Step)); 1766 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1767 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1768 // Cache knowledge of AR NW, which is propagated to this 1769 // AddRec. Negative step causes unsigned wrap, but it 1770 // still can't self-wrap. 1771 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1772 // Return the expression with the addrec on the outside. 1773 return getAddRecExpr( 1774 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1775 Depth + 1), 1776 getSignExtendExpr(Step, Ty, Depth + 1), L, 1777 AR->getNoWrapFlags()); 1778 } 1779 } 1780 } 1781 1782 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1783 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1784 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1785 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1786 const APInt &C = SC->getAPInt(); 1787 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1788 if (D != 0) { 1789 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1790 const SCEV *SResidual = 1791 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1792 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1793 return getAddExpr(SZExtD, SZExtR, 1794 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1795 Depth + 1); 1796 } 1797 } 1798 1799 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1800 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1801 return getAddRecExpr( 1802 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1803 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1804 } 1805 } 1806 1807 // zext(A % B) --> zext(A) % zext(B) 1808 { 1809 const SCEV *LHS; 1810 const SCEV *RHS; 1811 if (matchURem(Op, LHS, RHS)) 1812 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1813 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1814 } 1815 1816 // zext(A / B) --> zext(A) / zext(B). 1817 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1818 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1819 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1820 1821 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1822 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1823 if (SA->hasNoUnsignedWrap()) { 1824 // If the addition does not unsign overflow then we can, by definition, 1825 // commute the zero extension with the addition operation. 1826 SmallVector<const SCEV *, 4> Ops; 1827 for (const auto *Op : SA->operands()) 1828 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1829 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1830 } 1831 1832 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1833 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1834 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1835 // 1836 // Often address arithmetics contain expressions like 1837 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1838 // This transformation is useful while proving that such expressions are 1839 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1840 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1841 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1842 if (D != 0) { 1843 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1844 const SCEV *SResidual = 1845 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1846 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1847 return getAddExpr(SZExtD, SZExtR, 1848 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1849 Depth + 1); 1850 } 1851 } 1852 } 1853 1854 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1855 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1856 if (SM->hasNoUnsignedWrap()) { 1857 // If the multiply does not unsign overflow then we can, by definition, 1858 // commute the zero extension with the multiply operation. 1859 SmallVector<const SCEV *, 4> Ops; 1860 for (const auto *Op : SM->operands()) 1861 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1862 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1863 } 1864 1865 // zext(2^K * (trunc X to iN)) to iM -> 1866 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1867 // 1868 // Proof: 1869 // 1870 // zext(2^K * (trunc X to iN)) to iM 1871 // = zext((trunc X to iN) << K) to iM 1872 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1873 // (because shl removes the top K bits) 1874 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1875 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1876 // 1877 if (SM->getNumOperands() == 2) 1878 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1879 if (MulLHS->getAPInt().isPowerOf2()) 1880 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1881 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1882 MulLHS->getAPInt().logBase2(); 1883 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1884 return getMulExpr( 1885 getZeroExtendExpr(MulLHS, Ty), 1886 getZeroExtendExpr( 1887 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1888 SCEV::FlagNUW, Depth + 1); 1889 } 1890 } 1891 1892 // The cast wasn't folded; create an explicit cast node. 1893 // Recompute the insert position, as it may have been invalidated. 1894 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1895 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1896 Op, Ty); 1897 UniqueSCEVs.InsertNode(S, IP); 1898 addToLoopUseLists(S); 1899 return S; 1900 } 1901 1902 const SCEV * 1903 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1904 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1905 "This is not an extending conversion!"); 1906 assert(isSCEVable(Ty) && 1907 "This is not a conversion to a SCEVable type!"); 1908 Ty = getEffectiveSCEVType(Ty); 1909 1910 // Fold if the operand is constant. 1911 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1912 return getConstant( 1913 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1914 1915 // sext(sext(x)) --> sext(x) 1916 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1917 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1918 1919 // sext(zext(x)) --> zext(x) 1920 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1921 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1922 1923 // Before doing any expensive analysis, check to see if we've already 1924 // computed a SCEV for this Op and Ty. 1925 FoldingSetNodeID ID; 1926 ID.AddInteger(scSignExtend); 1927 ID.AddPointer(Op); 1928 ID.AddPointer(Ty); 1929 void *IP = nullptr; 1930 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1931 // Limit recursion depth. 1932 if (Depth > MaxExtDepth) { 1933 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1934 Op, Ty); 1935 UniqueSCEVs.InsertNode(S, IP); 1936 addToLoopUseLists(S); 1937 return S; 1938 } 1939 1940 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1941 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1942 // It's possible the bits taken off by the truncate were all sign bits. If 1943 // so, we should be able to simplify this further. 1944 const SCEV *X = ST->getOperand(); 1945 ConstantRange CR = getSignedRange(X); 1946 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1947 unsigned NewBits = getTypeSizeInBits(Ty); 1948 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1949 CR.sextOrTrunc(NewBits))) 1950 return getTruncateOrSignExtend(X, Ty); 1951 } 1952 1953 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1954 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1955 if (SA->hasNoSignedWrap()) { 1956 // If the addition does not sign overflow then we can, by definition, 1957 // commute the sign extension with the addition operation. 1958 SmallVector<const SCEV *, 4> Ops; 1959 for (const auto *Op : SA->operands()) 1960 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1961 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1962 } 1963 1964 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1965 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1966 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1967 // 1968 // For instance, this will bring two seemingly different expressions: 1969 // 1 + sext(5 + 20 * %x + 24 * %y) and 1970 // sext(6 + 20 * %x + 24 * %y) 1971 // to the same form: 1972 // 2 + sext(4 + 20 * %x + 24 * %y) 1973 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1974 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1975 if (D != 0) { 1976 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1977 const SCEV *SResidual = 1978 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1979 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1980 return getAddExpr(SSExtD, SSExtR, 1981 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1982 Depth + 1); 1983 } 1984 } 1985 } 1986 // If the input value is a chrec scev, and we can prove that the value 1987 // did not overflow the old, smaller, value, we can sign extend all of the 1988 // operands (often constants). This allows analysis of something like 1989 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1990 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1991 if (AR->isAffine()) { 1992 const SCEV *Start = AR->getStart(); 1993 const SCEV *Step = AR->getStepRecurrence(*this); 1994 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1995 const Loop *L = AR->getLoop(); 1996 1997 if (!AR->hasNoSignedWrap()) { 1998 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1999 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 2000 } 2001 2002 // If we have special knowledge that this addrec won't overflow, 2003 // we don't need to do any further analysis. 2004 if (AR->hasNoSignedWrap()) 2005 return getAddRecExpr( 2006 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2007 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 2008 2009 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2010 // Note that this serves two purposes: It filters out loops that are 2011 // simply not analyzable, and it covers the case where this code is 2012 // being called from within backedge-taken count analysis, such that 2013 // attempting to ask for the backedge-taken count would likely result 2014 // in infinite recursion. In the later case, the analysis code will 2015 // cope with a conservative value, and it will take care to purge 2016 // that value once it has finished. 2017 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 2018 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2019 // Manually compute the final value for AR, checking for 2020 // overflow. 2021 2022 // Check whether the backedge-taken count can be losslessly casted to 2023 // the addrec's type. The count is always unsigned. 2024 const SCEV *CastedMaxBECount = 2025 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 2026 const SCEV *RecastedMaxBECount = 2027 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 2028 if (MaxBECount == RecastedMaxBECount) { 2029 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2030 // Check whether Start+Step*MaxBECount has no signed overflow. 2031 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2032 SCEV::FlagAnyWrap, Depth + 1); 2033 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2034 SCEV::FlagAnyWrap, 2035 Depth + 1), 2036 WideTy, Depth + 1); 2037 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2038 const SCEV *WideMaxBECount = 2039 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2040 const SCEV *OperandExtendedAdd = 2041 getAddExpr(WideStart, 2042 getMulExpr(WideMaxBECount, 2043 getSignExtendExpr(Step, WideTy, Depth + 1), 2044 SCEV::FlagAnyWrap, Depth + 1), 2045 SCEV::FlagAnyWrap, Depth + 1); 2046 if (SAdd == OperandExtendedAdd) { 2047 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2048 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2049 // Return the expression with the addrec on the outside. 2050 return getAddRecExpr( 2051 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2052 Depth + 1), 2053 getSignExtendExpr(Step, Ty, Depth + 1), L, 2054 AR->getNoWrapFlags()); 2055 } 2056 // Similar to above, only this time treat the step value as unsigned. 2057 // This covers loops that count up with an unsigned step. 2058 OperandExtendedAdd = 2059 getAddExpr(WideStart, 2060 getMulExpr(WideMaxBECount, 2061 getZeroExtendExpr(Step, WideTy, Depth + 1), 2062 SCEV::FlagAnyWrap, Depth + 1), 2063 SCEV::FlagAnyWrap, Depth + 1); 2064 if (SAdd == OperandExtendedAdd) { 2065 // If AR wraps around then 2066 // 2067 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2068 // => SAdd != OperandExtendedAdd 2069 // 2070 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2071 // (SAdd == OperandExtendedAdd => AR is NW) 2072 2073 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2074 2075 // Return the expression with the addrec on the outside. 2076 return getAddRecExpr( 2077 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2078 Depth + 1), 2079 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2080 AR->getNoWrapFlags()); 2081 } 2082 } 2083 } 2084 2085 // Normally, in the cases we can prove no-overflow via a 2086 // backedge guarding condition, we can also compute a backedge 2087 // taken count for the loop. The exceptions are assumptions and 2088 // guards present in the loop -- SCEV is not great at exploiting 2089 // these to compute max backedge taken counts, but can still use 2090 // these to prove lack of overflow. Use this fact to avoid 2091 // doing extra work that may not pay off. 2092 2093 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2094 !AC.assumptions().empty()) { 2095 // If the backedge is guarded by a comparison with the pre-inc 2096 // value the addrec is safe. Also, if the entry is guarded by 2097 // a comparison with the start value and the backedge is 2098 // guarded by a comparison with the post-inc value, the addrec 2099 // is safe. 2100 ICmpInst::Predicate Pred; 2101 const SCEV *OverflowLimit = 2102 getSignedOverflowLimitForStep(Step, &Pred, this); 2103 if (OverflowLimit && 2104 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2105 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2106 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2107 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2108 return getAddRecExpr( 2109 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2110 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2111 } 2112 } 2113 2114 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2115 // if D + (C - D + Step * n) could be proven to not signed wrap 2116 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2117 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2118 const APInt &C = SC->getAPInt(); 2119 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2120 if (D != 0) { 2121 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2122 const SCEV *SResidual = 2123 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2124 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2125 return getAddExpr(SSExtD, SSExtR, 2126 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2127 Depth + 1); 2128 } 2129 } 2130 2131 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2132 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2133 return getAddRecExpr( 2134 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2135 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2136 } 2137 } 2138 2139 // If the input value is provably positive and we could not simplify 2140 // away the sext build a zext instead. 2141 if (isKnownNonNegative(Op)) 2142 return getZeroExtendExpr(Op, Ty, Depth + 1); 2143 2144 // The cast wasn't folded; create an explicit cast node. 2145 // Recompute the insert position, as it may have been invalidated. 2146 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2147 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2148 Op, Ty); 2149 UniqueSCEVs.InsertNode(S, IP); 2150 addToLoopUseLists(S); 2151 return S; 2152 } 2153 2154 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2155 /// unspecified bits out to the given type. 2156 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2157 Type *Ty) { 2158 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2159 "This is not an extending conversion!"); 2160 assert(isSCEVable(Ty) && 2161 "This is not a conversion to a SCEVable type!"); 2162 Ty = getEffectiveSCEVType(Ty); 2163 2164 // Sign-extend negative constants. 2165 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2166 if (SC->getAPInt().isNegative()) 2167 return getSignExtendExpr(Op, Ty); 2168 2169 // Peel off a truncate cast. 2170 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2171 const SCEV *NewOp = T->getOperand(); 2172 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2173 return getAnyExtendExpr(NewOp, Ty); 2174 return getTruncateOrNoop(NewOp, Ty); 2175 } 2176 2177 // Next try a zext cast. If the cast is folded, use it. 2178 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2179 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2180 return ZExt; 2181 2182 // Next try a sext cast. If the cast is folded, use it. 2183 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2184 if (!isa<SCEVSignExtendExpr>(SExt)) 2185 return SExt; 2186 2187 // Force the cast to be folded into the operands of an addrec. 2188 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2189 SmallVector<const SCEV *, 4> Ops; 2190 for (const SCEV *Op : AR->operands()) 2191 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2192 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2193 } 2194 2195 // If the expression is obviously signed, use the sext cast value. 2196 if (isa<SCEVSMaxExpr>(Op)) 2197 return SExt; 2198 2199 // Absent any other information, use the zext cast value. 2200 return ZExt; 2201 } 2202 2203 /// Process the given Ops list, which is a list of operands to be added under 2204 /// the given scale, update the given map. This is a helper function for 2205 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2206 /// that would form an add expression like this: 2207 /// 2208 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2209 /// 2210 /// where A and B are constants, update the map with these values: 2211 /// 2212 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2213 /// 2214 /// and add 13 + A*B*29 to AccumulatedConstant. 2215 /// This will allow getAddRecExpr to produce this: 2216 /// 2217 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2218 /// 2219 /// This form often exposes folding opportunities that are hidden in 2220 /// the original operand list. 2221 /// 2222 /// Return true iff it appears that any interesting folding opportunities 2223 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2224 /// the common case where no interesting opportunities are present, and 2225 /// is also used as a check to avoid infinite recursion. 2226 static bool 2227 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2228 SmallVectorImpl<const SCEV *> &NewOps, 2229 APInt &AccumulatedConstant, 2230 const SCEV *const *Ops, size_t NumOperands, 2231 const APInt &Scale, 2232 ScalarEvolution &SE) { 2233 bool Interesting = false; 2234 2235 // Iterate over the add operands. They are sorted, with constants first. 2236 unsigned i = 0; 2237 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2238 ++i; 2239 // Pull a buried constant out to the outside. 2240 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2241 Interesting = true; 2242 AccumulatedConstant += Scale * C->getAPInt(); 2243 } 2244 2245 // Next comes everything else. We're especially interested in multiplies 2246 // here, but they're in the middle, so just visit the rest with one loop. 2247 for (; i != NumOperands; ++i) { 2248 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2249 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2250 APInt NewScale = 2251 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2252 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2253 // A multiplication of a constant with another add; recurse. 2254 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2255 Interesting |= 2256 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2257 Add->op_begin(), Add->getNumOperands(), 2258 NewScale, SE); 2259 } else { 2260 // A multiplication of a constant with some other value. Update 2261 // the map. 2262 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2263 const SCEV *Key = SE.getMulExpr(MulOps); 2264 auto Pair = M.insert({Key, NewScale}); 2265 if (Pair.second) { 2266 NewOps.push_back(Pair.first->first); 2267 } else { 2268 Pair.first->second += NewScale; 2269 // The map already had an entry for this value, which may indicate 2270 // a folding opportunity. 2271 Interesting = true; 2272 } 2273 } 2274 } else { 2275 // An ordinary operand. Update the map. 2276 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2277 M.insert({Ops[i], Scale}); 2278 if (Pair.second) { 2279 NewOps.push_back(Pair.first->first); 2280 } else { 2281 Pair.first->second += Scale; 2282 // The map already had an entry for this value, which may indicate 2283 // a folding opportunity. 2284 Interesting = true; 2285 } 2286 } 2287 } 2288 2289 return Interesting; 2290 } 2291 2292 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2293 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2294 // can't-overflow flags for the operation if possible. 2295 static SCEV::NoWrapFlags 2296 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2297 const SmallVectorImpl<const SCEV *> &Ops, 2298 SCEV::NoWrapFlags Flags) { 2299 using namespace std::placeholders; 2300 2301 using OBO = OverflowingBinaryOperator; 2302 2303 bool CanAnalyze = 2304 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2305 (void)CanAnalyze; 2306 assert(CanAnalyze && "don't call from other places!"); 2307 2308 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2309 SCEV::NoWrapFlags SignOrUnsignWrap = 2310 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2311 2312 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2313 auto IsKnownNonNegative = [&](const SCEV *S) { 2314 return SE->isKnownNonNegative(S); 2315 }; 2316 2317 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2318 Flags = 2319 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2320 2321 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2322 2323 if (SignOrUnsignWrap != SignOrUnsignMask && 2324 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2325 isa<SCEVConstant>(Ops[0])) { 2326 2327 auto Opcode = [&] { 2328 switch (Type) { 2329 case scAddExpr: 2330 return Instruction::Add; 2331 case scMulExpr: 2332 return Instruction::Mul; 2333 default: 2334 llvm_unreachable("Unexpected SCEV op."); 2335 } 2336 }(); 2337 2338 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2339 2340 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2341 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2342 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2343 Opcode, C, OBO::NoSignedWrap); 2344 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2345 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2346 } 2347 2348 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2349 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2350 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2351 Opcode, C, OBO::NoUnsignedWrap); 2352 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2353 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2354 } 2355 } 2356 2357 return Flags; 2358 } 2359 2360 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2361 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2362 } 2363 2364 /// Get a canonical add expression, or something simpler if possible. 2365 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2366 SCEV::NoWrapFlags Flags, 2367 unsigned Depth) { 2368 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2369 "only nuw or nsw allowed"); 2370 assert(!Ops.empty() && "Cannot get empty add!"); 2371 if (Ops.size() == 1) return Ops[0]; 2372 #ifndef NDEBUG 2373 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2374 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2375 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2376 "SCEVAddExpr operand types don't match!"); 2377 #endif 2378 2379 // Sort by complexity, this groups all similar expression types together. 2380 GroupByComplexity(Ops, &LI, DT); 2381 2382 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2383 2384 // If there are any constants, fold them together. 2385 unsigned Idx = 0; 2386 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2387 ++Idx; 2388 assert(Idx < Ops.size()); 2389 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2390 // We found two constants, fold them together! 2391 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2392 if (Ops.size() == 2) return Ops[0]; 2393 Ops.erase(Ops.begin()+1); // Erase the folded element 2394 LHSC = cast<SCEVConstant>(Ops[0]); 2395 } 2396 2397 // If we are left with a constant zero being added, strip it off. 2398 if (LHSC->getValue()->isZero()) { 2399 Ops.erase(Ops.begin()); 2400 --Idx; 2401 } 2402 2403 if (Ops.size() == 1) return Ops[0]; 2404 } 2405 2406 // Limit recursion calls depth. 2407 if (Depth > MaxArithDepth) 2408 return getOrCreateAddExpr(Ops, Flags); 2409 2410 // Okay, check to see if the same value occurs in the operand list more than 2411 // once. If so, merge them together into an multiply expression. Since we 2412 // sorted the list, these values are required to be adjacent. 2413 Type *Ty = Ops[0]->getType(); 2414 bool FoundMatch = false; 2415 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2416 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2417 // Scan ahead to count how many equal operands there are. 2418 unsigned Count = 2; 2419 while (i+Count != e && Ops[i+Count] == Ops[i]) 2420 ++Count; 2421 // Merge the values into a multiply. 2422 const SCEV *Scale = getConstant(Ty, Count); 2423 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2424 if (Ops.size() == Count) 2425 return Mul; 2426 Ops[i] = Mul; 2427 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2428 --i; e -= Count - 1; 2429 FoundMatch = true; 2430 } 2431 if (FoundMatch) 2432 return getAddExpr(Ops, Flags, Depth + 1); 2433 2434 // Check for truncates. If all the operands are truncated from the same 2435 // type, see if factoring out the truncate would permit the result to be 2436 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2437 // if the contents of the resulting outer trunc fold to something simple. 2438 auto FindTruncSrcType = [&]() -> Type * { 2439 // We're ultimately looking to fold an addrec of truncs and muls of only 2440 // constants and truncs, so if we find any other types of SCEV 2441 // as operands of the addrec then we bail and return nullptr here. 2442 // Otherwise, we return the type of the operand of a trunc that we find. 2443 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2444 return T->getOperand()->getType(); 2445 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2446 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2447 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2448 return T->getOperand()->getType(); 2449 } 2450 return nullptr; 2451 }; 2452 if (auto *SrcType = FindTruncSrcType()) { 2453 SmallVector<const SCEV *, 8> LargeOps; 2454 bool Ok = true; 2455 // Check all the operands to see if they can be represented in the 2456 // source type of the truncate. 2457 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2458 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2459 if (T->getOperand()->getType() != SrcType) { 2460 Ok = false; 2461 break; 2462 } 2463 LargeOps.push_back(T->getOperand()); 2464 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2465 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2466 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2467 SmallVector<const SCEV *, 8> LargeMulOps; 2468 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2469 if (const SCEVTruncateExpr *T = 2470 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2471 if (T->getOperand()->getType() != SrcType) { 2472 Ok = false; 2473 break; 2474 } 2475 LargeMulOps.push_back(T->getOperand()); 2476 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2477 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2478 } else { 2479 Ok = false; 2480 break; 2481 } 2482 } 2483 if (Ok) 2484 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2485 } else { 2486 Ok = false; 2487 break; 2488 } 2489 } 2490 if (Ok) { 2491 // Evaluate the expression in the larger type. 2492 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2493 // If it folds to something simple, use it. Otherwise, don't. 2494 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2495 return getTruncateExpr(Fold, Ty); 2496 } 2497 } 2498 2499 // Skip past any other cast SCEVs. 2500 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2501 ++Idx; 2502 2503 // If there are add operands they would be next. 2504 if (Idx < Ops.size()) { 2505 bool DeletedAdd = false; 2506 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2507 if (Ops.size() > AddOpsInlineThreshold || 2508 Add->getNumOperands() > AddOpsInlineThreshold) 2509 break; 2510 // If we have an add, expand the add operands onto the end of the operands 2511 // list. 2512 Ops.erase(Ops.begin()+Idx); 2513 Ops.append(Add->op_begin(), Add->op_end()); 2514 DeletedAdd = true; 2515 } 2516 2517 // If we deleted at least one add, we added operands to the end of the list, 2518 // and they are not necessarily sorted. Recurse to resort and resimplify 2519 // any operands we just acquired. 2520 if (DeletedAdd) 2521 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2522 } 2523 2524 // Skip over the add expression until we get to a multiply. 2525 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2526 ++Idx; 2527 2528 // Check to see if there are any folding opportunities present with 2529 // operands multiplied by constant values. 2530 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2531 uint64_t BitWidth = getTypeSizeInBits(Ty); 2532 DenseMap<const SCEV *, APInt> M; 2533 SmallVector<const SCEV *, 8> NewOps; 2534 APInt AccumulatedConstant(BitWidth, 0); 2535 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2536 Ops.data(), Ops.size(), 2537 APInt(BitWidth, 1), *this)) { 2538 struct APIntCompare { 2539 bool operator()(const APInt &LHS, const APInt &RHS) const { 2540 return LHS.ult(RHS); 2541 } 2542 }; 2543 2544 // Some interesting folding opportunity is present, so its worthwhile to 2545 // re-generate the operands list. Group the operands by constant scale, 2546 // to avoid multiplying by the same constant scale multiple times. 2547 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2548 for (const SCEV *NewOp : NewOps) 2549 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2550 // Re-generate the operands list. 2551 Ops.clear(); 2552 if (AccumulatedConstant != 0) 2553 Ops.push_back(getConstant(AccumulatedConstant)); 2554 for (auto &MulOp : MulOpLists) 2555 if (MulOp.first != 0) 2556 Ops.push_back(getMulExpr( 2557 getConstant(MulOp.first), 2558 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2559 SCEV::FlagAnyWrap, Depth + 1)); 2560 if (Ops.empty()) 2561 return getZero(Ty); 2562 if (Ops.size() == 1) 2563 return Ops[0]; 2564 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2565 } 2566 } 2567 2568 // If we are adding something to a multiply expression, make sure the 2569 // something is not already an operand of the multiply. If so, merge it into 2570 // the multiply. 2571 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2572 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2573 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2574 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2575 if (isa<SCEVConstant>(MulOpSCEV)) 2576 continue; 2577 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2578 if (MulOpSCEV == Ops[AddOp]) { 2579 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2580 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2581 if (Mul->getNumOperands() != 2) { 2582 // If the multiply has more than two operands, we must get the 2583 // Y*Z term. 2584 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2585 Mul->op_begin()+MulOp); 2586 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2587 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2588 } 2589 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2590 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2591 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2592 SCEV::FlagAnyWrap, Depth + 1); 2593 if (Ops.size() == 2) return OuterMul; 2594 if (AddOp < Idx) { 2595 Ops.erase(Ops.begin()+AddOp); 2596 Ops.erase(Ops.begin()+Idx-1); 2597 } else { 2598 Ops.erase(Ops.begin()+Idx); 2599 Ops.erase(Ops.begin()+AddOp-1); 2600 } 2601 Ops.push_back(OuterMul); 2602 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2603 } 2604 2605 // Check this multiply against other multiplies being added together. 2606 for (unsigned OtherMulIdx = Idx+1; 2607 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2608 ++OtherMulIdx) { 2609 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2610 // If MulOp occurs in OtherMul, we can fold the two multiplies 2611 // together. 2612 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2613 OMulOp != e; ++OMulOp) 2614 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2615 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2616 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2617 if (Mul->getNumOperands() != 2) { 2618 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2619 Mul->op_begin()+MulOp); 2620 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2621 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2622 } 2623 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2624 if (OtherMul->getNumOperands() != 2) { 2625 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2626 OtherMul->op_begin()+OMulOp); 2627 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2628 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2629 } 2630 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2631 const SCEV *InnerMulSum = 2632 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2633 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2634 SCEV::FlagAnyWrap, Depth + 1); 2635 if (Ops.size() == 2) return OuterMul; 2636 Ops.erase(Ops.begin()+Idx); 2637 Ops.erase(Ops.begin()+OtherMulIdx-1); 2638 Ops.push_back(OuterMul); 2639 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2640 } 2641 } 2642 } 2643 } 2644 2645 // If there are any add recurrences in the operands list, see if any other 2646 // added values are loop invariant. If so, we can fold them into the 2647 // recurrence. 2648 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2649 ++Idx; 2650 2651 // Scan over all recurrences, trying to fold loop invariants into them. 2652 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2653 // Scan all of the other operands to this add and add them to the vector if 2654 // they are loop invariant w.r.t. the recurrence. 2655 SmallVector<const SCEV *, 8> LIOps; 2656 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2657 const Loop *AddRecLoop = AddRec->getLoop(); 2658 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2659 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2660 LIOps.push_back(Ops[i]); 2661 Ops.erase(Ops.begin()+i); 2662 --i; --e; 2663 } 2664 2665 // If we found some loop invariants, fold them into the recurrence. 2666 if (!LIOps.empty()) { 2667 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2668 LIOps.push_back(AddRec->getStart()); 2669 2670 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2671 AddRec->op_end()); 2672 // This follows from the fact that the no-wrap flags on the outer add 2673 // expression are applicable on the 0th iteration, when the add recurrence 2674 // will be equal to its start value. 2675 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2676 2677 // Build the new addrec. Propagate the NUW and NSW flags if both the 2678 // outer add and the inner addrec are guaranteed to have no overflow. 2679 // Always propagate NW. 2680 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2681 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2682 2683 // If all of the other operands were loop invariant, we are done. 2684 if (Ops.size() == 1) return NewRec; 2685 2686 // Otherwise, add the folded AddRec by the non-invariant parts. 2687 for (unsigned i = 0;; ++i) 2688 if (Ops[i] == AddRec) { 2689 Ops[i] = NewRec; 2690 break; 2691 } 2692 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2693 } 2694 2695 // Okay, if there weren't any loop invariants to be folded, check to see if 2696 // there are multiple AddRec's with the same loop induction variable being 2697 // added together. If so, we can fold them. 2698 for (unsigned OtherIdx = Idx+1; 2699 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2700 ++OtherIdx) { 2701 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2702 // so that the 1st found AddRecExpr is dominated by all others. 2703 assert(DT.dominates( 2704 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2705 AddRec->getLoop()->getHeader()) && 2706 "AddRecExprs are not sorted in reverse dominance order?"); 2707 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2708 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2709 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2710 AddRec->op_end()); 2711 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2712 ++OtherIdx) { 2713 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2714 if (OtherAddRec->getLoop() == AddRecLoop) { 2715 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2716 i != e; ++i) { 2717 if (i >= AddRecOps.size()) { 2718 AddRecOps.append(OtherAddRec->op_begin()+i, 2719 OtherAddRec->op_end()); 2720 break; 2721 } 2722 SmallVector<const SCEV *, 2> TwoOps = { 2723 AddRecOps[i], OtherAddRec->getOperand(i)}; 2724 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2725 } 2726 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2727 } 2728 } 2729 // Step size has changed, so we cannot guarantee no self-wraparound. 2730 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2731 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2732 } 2733 } 2734 2735 // Otherwise couldn't fold anything into this recurrence. Move onto the 2736 // next one. 2737 } 2738 2739 // Okay, it looks like we really DO need an add expr. Check to see if we 2740 // already have one, otherwise create a new one. 2741 return getOrCreateAddExpr(Ops, Flags); 2742 } 2743 2744 const SCEV * 2745 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2746 SCEV::NoWrapFlags Flags) { 2747 FoldingSetNodeID ID; 2748 ID.AddInteger(scAddExpr); 2749 for (const SCEV *Op : Ops) 2750 ID.AddPointer(Op); 2751 void *IP = nullptr; 2752 SCEVAddExpr *S = 2753 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2754 if (!S) { 2755 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2756 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2757 S = new (SCEVAllocator) 2758 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2759 UniqueSCEVs.InsertNode(S, IP); 2760 addToLoopUseLists(S); 2761 } 2762 S->setNoWrapFlags(Flags); 2763 return S; 2764 } 2765 2766 const SCEV * 2767 ScalarEvolution::getOrCreateAddRecExpr(SmallVectorImpl<const SCEV *> &Ops, 2768 const Loop *L, SCEV::NoWrapFlags Flags) { 2769 FoldingSetNodeID ID; 2770 ID.AddInteger(scAddRecExpr); 2771 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2772 ID.AddPointer(Ops[i]); 2773 ID.AddPointer(L); 2774 void *IP = nullptr; 2775 SCEVAddRecExpr *S = 2776 static_cast<SCEVAddRecExpr *>(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 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2782 UniqueSCEVs.InsertNode(S, IP); 2783 addToLoopUseLists(S); 2784 } 2785 S->setNoWrapFlags(Flags); 2786 return S; 2787 } 2788 2789 const SCEV * 2790 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2791 SCEV::NoWrapFlags Flags) { 2792 FoldingSetNodeID ID; 2793 ID.AddInteger(scMulExpr); 2794 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2795 ID.AddPointer(Ops[i]); 2796 void *IP = nullptr; 2797 SCEVMulExpr *S = 2798 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2799 if (!S) { 2800 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2801 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2802 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2803 O, Ops.size()); 2804 UniqueSCEVs.InsertNode(S, IP); 2805 addToLoopUseLists(S); 2806 } 2807 S->setNoWrapFlags(Flags); 2808 return S; 2809 } 2810 2811 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2812 uint64_t k = i*j; 2813 if (j > 1 && k / j != i) Overflow = true; 2814 return k; 2815 } 2816 2817 /// Compute the result of "n choose k", the binomial coefficient. If an 2818 /// intermediate computation overflows, Overflow will be set and the return will 2819 /// be garbage. Overflow is not cleared on absence of overflow. 2820 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2821 // We use the multiplicative formula: 2822 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2823 // At each iteration, we take the n-th term of the numeral and divide by the 2824 // (k-n)th term of the denominator. This division will always produce an 2825 // integral result, and helps reduce the chance of overflow in the 2826 // intermediate computations. However, we can still overflow even when the 2827 // final result would fit. 2828 2829 if (n == 0 || n == k) return 1; 2830 if (k > n) return 0; 2831 2832 if (k > n/2) 2833 k = n-k; 2834 2835 uint64_t r = 1; 2836 for (uint64_t i = 1; i <= k; ++i) { 2837 r = umul_ov(r, n-(i-1), Overflow); 2838 r /= i; 2839 } 2840 return r; 2841 } 2842 2843 /// Determine if any of the operands in this SCEV are a constant or if 2844 /// any of the add or multiply expressions in this SCEV contain a constant. 2845 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2846 struct FindConstantInAddMulChain { 2847 bool FoundConstant = false; 2848 2849 bool follow(const SCEV *S) { 2850 FoundConstant |= isa<SCEVConstant>(S); 2851 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2852 } 2853 2854 bool isDone() const { 2855 return FoundConstant; 2856 } 2857 }; 2858 2859 FindConstantInAddMulChain F; 2860 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2861 ST.visitAll(StartExpr); 2862 return F.FoundConstant; 2863 } 2864 2865 /// Get a canonical multiply expression, or something simpler if possible. 2866 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2867 SCEV::NoWrapFlags Flags, 2868 unsigned Depth) { 2869 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2870 "only nuw or nsw allowed"); 2871 assert(!Ops.empty() && "Cannot get empty mul!"); 2872 if (Ops.size() == 1) return Ops[0]; 2873 #ifndef NDEBUG 2874 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2875 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2876 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2877 "SCEVMulExpr operand types don't match!"); 2878 #endif 2879 2880 // Sort by complexity, this groups all similar expression types together. 2881 GroupByComplexity(Ops, &LI, DT); 2882 2883 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2884 2885 // Limit recursion calls depth. 2886 if (Depth > MaxArithDepth) 2887 return getOrCreateMulExpr(Ops, Flags); 2888 2889 // If there are any constants, fold them together. 2890 unsigned Idx = 0; 2891 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2892 2893 if (Ops.size() == 2) 2894 // C1*(C2+V) -> C1*C2 + C1*V 2895 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2896 // If any of Add's ops are Adds or Muls with a constant, apply this 2897 // transformation as well. 2898 // 2899 // TODO: There are some cases where this transformation is not 2900 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2901 // this transformation should be narrowed down. 2902 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2903 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2904 SCEV::FlagAnyWrap, Depth + 1), 2905 getMulExpr(LHSC, Add->getOperand(1), 2906 SCEV::FlagAnyWrap, Depth + 1), 2907 SCEV::FlagAnyWrap, Depth + 1); 2908 2909 ++Idx; 2910 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2911 // We found two constants, fold them together! 2912 ConstantInt *Fold = 2913 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2914 Ops[0] = getConstant(Fold); 2915 Ops.erase(Ops.begin()+1); // Erase the folded element 2916 if (Ops.size() == 1) return Ops[0]; 2917 LHSC = cast<SCEVConstant>(Ops[0]); 2918 } 2919 2920 // If we are left with a constant one being multiplied, strip it off. 2921 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2922 Ops.erase(Ops.begin()); 2923 --Idx; 2924 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2925 // If we have a multiply of zero, it will always be zero. 2926 return Ops[0]; 2927 } else if (Ops[0]->isAllOnesValue()) { 2928 // If we have a mul by -1 of an add, try distributing the -1 among the 2929 // add operands. 2930 if (Ops.size() == 2) { 2931 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2932 SmallVector<const SCEV *, 4> NewOps; 2933 bool AnyFolded = false; 2934 for (const SCEV *AddOp : Add->operands()) { 2935 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2936 Depth + 1); 2937 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2938 NewOps.push_back(Mul); 2939 } 2940 if (AnyFolded) 2941 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2942 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2943 // Negation preserves a recurrence's no self-wrap property. 2944 SmallVector<const SCEV *, 4> Operands; 2945 for (const SCEV *AddRecOp : AddRec->operands()) 2946 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2947 Depth + 1)); 2948 2949 return getAddRecExpr(Operands, AddRec->getLoop(), 2950 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2951 } 2952 } 2953 } 2954 2955 if (Ops.size() == 1) 2956 return Ops[0]; 2957 } 2958 2959 // Skip over the add expression until we get to a multiply. 2960 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2961 ++Idx; 2962 2963 // If there are mul operands inline them all into this expression. 2964 if (Idx < Ops.size()) { 2965 bool DeletedMul = false; 2966 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2967 if (Ops.size() > MulOpsInlineThreshold) 2968 break; 2969 // If we have an mul, expand the mul operands onto the end of the 2970 // operands list. 2971 Ops.erase(Ops.begin()+Idx); 2972 Ops.append(Mul->op_begin(), Mul->op_end()); 2973 DeletedMul = true; 2974 } 2975 2976 // If we deleted at least one mul, we added operands to the end of the 2977 // list, and they are not necessarily sorted. Recurse to resort and 2978 // resimplify any operands we just acquired. 2979 if (DeletedMul) 2980 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2981 } 2982 2983 // If there are any add recurrences in the operands list, see if any other 2984 // added values are loop invariant. If so, we can fold them into the 2985 // recurrence. 2986 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2987 ++Idx; 2988 2989 // Scan over all recurrences, trying to fold loop invariants into them. 2990 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2991 // Scan all of the other operands to this mul and add them to the vector 2992 // if they are loop invariant w.r.t. the recurrence. 2993 SmallVector<const SCEV *, 8> LIOps; 2994 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2995 const Loop *AddRecLoop = AddRec->getLoop(); 2996 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2997 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2998 LIOps.push_back(Ops[i]); 2999 Ops.erase(Ops.begin()+i); 3000 --i; --e; 3001 } 3002 3003 // If we found some loop invariants, fold them into the recurrence. 3004 if (!LIOps.empty()) { 3005 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3006 SmallVector<const SCEV *, 4> NewOps; 3007 NewOps.reserve(AddRec->getNumOperands()); 3008 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3009 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3010 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3011 SCEV::FlagAnyWrap, Depth + 1)); 3012 3013 // Build the new addrec. Propagate the NUW and NSW flags if both the 3014 // outer mul and the inner addrec are guaranteed to have no overflow. 3015 // 3016 // No self-wrap cannot be guaranteed after changing the step size, but 3017 // will be inferred if either NUW or NSW is true. 3018 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 3019 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 3020 3021 // If all of the other operands were loop invariant, we are done. 3022 if (Ops.size() == 1) return NewRec; 3023 3024 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3025 for (unsigned i = 0;; ++i) 3026 if (Ops[i] == AddRec) { 3027 Ops[i] = NewRec; 3028 break; 3029 } 3030 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3031 } 3032 3033 // Okay, if there weren't any loop invariants to be folded, check to see 3034 // if there are multiple AddRec's with the same loop induction variable 3035 // being multiplied together. If so, we can fold them. 3036 3037 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3038 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3039 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3040 // ]]],+,...up to x=2n}. 3041 // Note that the arguments to choose() are always integers with values 3042 // known at compile time, never SCEV objects. 3043 // 3044 // The implementation avoids pointless extra computations when the two 3045 // addrec's are of different length (mathematically, it's equivalent to 3046 // an infinite stream of zeros on the right). 3047 bool OpsModified = false; 3048 for (unsigned OtherIdx = Idx+1; 3049 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3050 ++OtherIdx) { 3051 const SCEVAddRecExpr *OtherAddRec = 3052 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3053 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3054 continue; 3055 3056 // Limit max number of arguments to avoid creation of unreasonably big 3057 // SCEVAddRecs with very complex operands. 3058 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3059 MaxAddRecSize) 3060 continue; 3061 3062 bool Overflow = false; 3063 Type *Ty = AddRec->getType(); 3064 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3065 SmallVector<const SCEV*, 7> AddRecOps; 3066 for (int x = 0, xe = AddRec->getNumOperands() + 3067 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3068 SmallVector <const SCEV *, 7> SumOps; 3069 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3070 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3071 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3072 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3073 z < ze && !Overflow; ++z) { 3074 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3075 uint64_t Coeff; 3076 if (LargerThan64Bits) 3077 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3078 else 3079 Coeff = Coeff1*Coeff2; 3080 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3081 const SCEV *Term1 = AddRec->getOperand(y-z); 3082 const SCEV *Term2 = OtherAddRec->getOperand(z); 3083 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3084 SCEV::FlagAnyWrap, Depth + 1)); 3085 } 3086 } 3087 if (SumOps.empty()) 3088 SumOps.push_back(getZero(Ty)); 3089 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3090 } 3091 if (!Overflow) { 3092 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 3093 SCEV::FlagAnyWrap); 3094 if (Ops.size() == 2) return NewAddRec; 3095 Ops[Idx] = NewAddRec; 3096 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3097 OpsModified = true; 3098 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3099 if (!AddRec) 3100 break; 3101 } 3102 } 3103 if (OpsModified) 3104 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3105 3106 // Otherwise couldn't fold anything into this recurrence. Move onto the 3107 // next one. 3108 } 3109 3110 // Okay, it looks like we really DO need an mul expr. Check to see if we 3111 // already have one, otherwise create a new one. 3112 return getOrCreateMulExpr(Ops, Flags); 3113 } 3114 3115 /// Represents an unsigned remainder expression based on unsigned division. 3116 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3117 const SCEV *RHS) { 3118 assert(getEffectiveSCEVType(LHS->getType()) == 3119 getEffectiveSCEVType(RHS->getType()) && 3120 "SCEVURemExpr operand types don't match!"); 3121 3122 // Short-circuit easy cases 3123 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3124 // If constant is one, the result is trivial 3125 if (RHSC->getValue()->isOne()) 3126 return getZero(LHS->getType()); // X urem 1 --> 0 3127 3128 // If constant is a power of two, fold into a zext(trunc(LHS)). 3129 if (RHSC->getAPInt().isPowerOf2()) { 3130 Type *FullTy = LHS->getType(); 3131 Type *TruncTy = 3132 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3133 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3134 } 3135 } 3136 3137 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3138 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3139 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3140 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3141 } 3142 3143 /// Get a canonical unsigned division expression, or something simpler if 3144 /// possible. 3145 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3146 const SCEV *RHS) { 3147 assert(getEffectiveSCEVType(LHS->getType()) == 3148 getEffectiveSCEVType(RHS->getType()) && 3149 "SCEVUDivExpr operand types don't match!"); 3150 3151 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3152 if (RHSC->getValue()->isOne()) 3153 return LHS; // X udiv 1 --> x 3154 // If the denominator is zero, the result of the udiv is undefined. Don't 3155 // try to analyze it, because the resolution chosen here may differ from 3156 // the resolution chosen in other parts of the compiler. 3157 if (!RHSC->getValue()->isZero()) { 3158 // Determine if the division can be folded into the operands of 3159 // its operands. 3160 // TODO: Generalize this to non-constants by using known-bits information. 3161 Type *Ty = LHS->getType(); 3162 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3163 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3164 // For non-power-of-two values, effectively round the value up to the 3165 // nearest power of two. 3166 if (!RHSC->getAPInt().isPowerOf2()) 3167 ++MaxShiftAmt; 3168 IntegerType *ExtTy = 3169 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3170 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3171 if (const SCEVConstant *Step = 3172 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3173 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3174 const APInt &StepInt = Step->getAPInt(); 3175 const APInt &DivInt = RHSC->getAPInt(); 3176 if (!StepInt.urem(DivInt) && 3177 getZeroExtendExpr(AR, ExtTy) == 3178 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3179 getZeroExtendExpr(Step, ExtTy), 3180 AR->getLoop(), SCEV::FlagAnyWrap)) { 3181 SmallVector<const SCEV *, 4> Operands; 3182 for (const SCEV *Op : AR->operands()) 3183 Operands.push_back(getUDivExpr(Op, RHS)); 3184 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3185 } 3186 /// Get a canonical UDivExpr for a recurrence. 3187 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3188 // We can currently only fold X%N if X is constant. 3189 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3190 if (StartC && !DivInt.urem(StepInt) && 3191 getZeroExtendExpr(AR, ExtTy) == 3192 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3193 getZeroExtendExpr(Step, ExtTy), 3194 AR->getLoop(), SCEV::FlagAnyWrap)) { 3195 const APInt &StartInt = StartC->getAPInt(); 3196 const APInt &StartRem = StartInt.urem(StepInt); 3197 if (StartRem != 0) 3198 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3199 AR->getLoop(), SCEV::FlagNW); 3200 } 3201 } 3202 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3203 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3204 SmallVector<const SCEV *, 4> Operands; 3205 for (const SCEV *Op : M->operands()) 3206 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3207 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3208 // Find an operand that's safely divisible. 3209 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3210 const SCEV *Op = M->getOperand(i); 3211 const SCEV *Div = getUDivExpr(Op, RHSC); 3212 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3213 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3214 M->op_end()); 3215 Operands[i] = Div; 3216 return getMulExpr(Operands); 3217 } 3218 } 3219 } 3220 3221 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3222 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3223 if (auto *DivisorConstant = 3224 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3225 bool Overflow = false; 3226 APInt NewRHS = 3227 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3228 if (Overflow) { 3229 return getConstant(RHSC->getType(), 0, false); 3230 } 3231 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3232 } 3233 } 3234 3235 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3236 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3237 SmallVector<const SCEV *, 4> Operands; 3238 for (const SCEV *Op : A->operands()) 3239 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3240 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3241 Operands.clear(); 3242 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3243 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3244 if (isa<SCEVUDivExpr>(Op) || 3245 getMulExpr(Op, RHS) != A->getOperand(i)) 3246 break; 3247 Operands.push_back(Op); 3248 } 3249 if (Operands.size() == A->getNumOperands()) 3250 return getAddExpr(Operands); 3251 } 3252 } 3253 3254 // Fold if both operands are constant. 3255 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3256 Constant *LHSCV = LHSC->getValue(); 3257 Constant *RHSCV = RHSC->getValue(); 3258 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3259 RHSCV))); 3260 } 3261 } 3262 } 3263 3264 FoldingSetNodeID ID; 3265 ID.AddInteger(scUDivExpr); 3266 ID.AddPointer(LHS); 3267 ID.AddPointer(RHS); 3268 void *IP = nullptr; 3269 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3270 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3271 LHS, RHS); 3272 UniqueSCEVs.InsertNode(S, IP); 3273 addToLoopUseLists(S); 3274 return S; 3275 } 3276 3277 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3278 APInt A = C1->getAPInt().abs(); 3279 APInt B = C2->getAPInt().abs(); 3280 uint32_t ABW = A.getBitWidth(); 3281 uint32_t BBW = B.getBitWidth(); 3282 3283 if (ABW > BBW) 3284 B = B.zext(ABW); 3285 else if (ABW < BBW) 3286 A = A.zext(BBW); 3287 3288 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3289 } 3290 3291 /// Get a canonical unsigned division expression, or something simpler if 3292 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3293 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3294 /// it's not exact because the udiv may be clearing bits. 3295 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3296 const SCEV *RHS) { 3297 // TODO: we could try to find factors in all sorts of things, but for now we 3298 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3299 // end of this file for inspiration. 3300 3301 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3302 if (!Mul || !Mul->hasNoUnsignedWrap()) 3303 return getUDivExpr(LHS, RHS); 3304 3305 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3306 // If the mulexpr multiplies by a constant, then that constant must be the 3307 // first element of the mulexpr. 3308 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3309 if (LHSCst == RHSCst) { 3310 SmallVector<const SCEV *, 2> Operands; 3311 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3312 return getMulExpr(Operands); 3313 } 3314 3315 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3316 // that there's a factor provided by one of the other terms. We need to 3317 // check. 3318 APInt Factor = gcd(LHSCst, RHSCst); 3319 if (!Factor.isIntN(1)) { 3320 LHSCst = 3321 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3322 RHSCst = 3323 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3324 SmallVector<const SCEV *, 2> Operands; 3325 Operands.push_back(LHSCst); 3326 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3327 LHS = getMulExpr(Operands); 3328 RHS = RHSCst; 3329 Mul = dyn_cast<SCEVMulExpr>(LHS); 3330 if (!Mul) 3331 return getUDivExactExpr(LHS, RHS); 3332 } 3333 } 3334 } 3335 3336 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3337 if (Mul->getOperand(i) == RHS) { 3338 SmallVector<const SCEV *, 2> Operands; 3339 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3340 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3341 return getMulExpr(Operands); 3342 } 3343 } 3344 3345 return getUDivExpr(LHS, RHS); 3346 } 3347 3348 /// Get an add recurrence expression for the specified loop. Simplify the 3349 /// expression as much as possible. 3350 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3351 const Loop *L, 3352 SCEV::NoWrapFlags Flags) { 3353 SmallVector<const SCEV *, 4> Operands; 3354 Operands.push_back(Start); 3355 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3356 if (StepChrec->getLoop() == L) { 3357 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3358 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3359 } 3360 3361 Operands.push_back(Step); 3362 return getAddRecExpr(Operands, L, Flags); 3363 } 3364 3365 /// Get an add recurrence expression for the specified loop. Simplify the 3366 /// expression as much as possible. 3367 const SCEV * 3368 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3369 const Loop *L, SCEV::NoWrapFlags Flags) { 3370 if (Operands.size() == 1) return Operands[0]; 3371 #ifndef NDEBUG 3372 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3373 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3374 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3375 "SCEVAddRecExpr operand types don't match!"); 3376 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3377 assert(isLoopInvariant(Operands[i], L) && 3378 "SCEVAddRecExpr operand is not loop-invariant!"); 3379 #endif 3380 3381 if (Operands.back()->isZero()) { 3382 Operands.pop_back(); 3383 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3384 } 3385 3386 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3387 // use that information to infer NUW and NSW flags. However, computing a 3388 // BE count requires calling getAddRecExpr, so we may not yet have a 3389 // meaningful BE count at this point (and if we don't, we'd be stuck 3390 // with a SCEVCouldNotCompute as the cached BE count). 3391 3392 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3393 3394 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3395 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3396 const Loop *NestedLoop = NestedAR->getLoop(); 3397 if (L->contains(NestedLoop) 3398 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3399 : (!NestedLoop->contains(L) && 3400 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3401 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3402 NestedAR->op_end()); 3403 Operands[0] = NestedAR->getStart(); 3404 // AddRecs require their operands be loop-invariant with respect to their 3405 // loops. Don't perform this transformation if it would break this 3406 // requirement. 3407 bool AllInvariant = all_of( 3408 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3409 3410 if (AllInvariant) { 3411 // Create a recurrence for the outer loop with the same step size. 3412 // 3413 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3414 // inner recurrence has the same property. 3415 SCEV::NoWrapFlags OuterFlags = 3416 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3417 3418 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3419 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3420 return isLoopInvariant(Op, NestedLoop); 3421 }); 3422 3423 if (AllInvariant) { 3424 // Ok, both add recurrences are valid after the transformation. 3425 // 3426 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3427 // the outer recurrence has the same property. 3428 SCEV::NoWrapFlags InnerFlags = 3429 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3430 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3431 } 3432 } 3433 // Reset Operands to its original state. 3434 Operands[0] = NestedAR; 3435 } 3436 } 3437 3438 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3439 // already have one, otherwise create a new one. 3440 return getOrCreateAddRecExpr(Operands, L, Flags); 3441 } 3442 3443 const SCEV * 3444 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3445 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3446 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3447 // getSCEV(Base)->getType() has the same address space as Base->getType() 3448 // because SCEV::getType() preserves the address space. 3449 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3450 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3451 // instruction to its SCEV, because the Instruction may be guarded by control 3452 // flow and the no-overflow bits may not be valid for the expression in any 3453 // context. This can be fixed similarly to how these flags are handled for 3454 // adds. 3455 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3456 : SCEV::FlagAnyWrap; 3457 3458 const SCEV *TotalOffset = getZero(IntPtrTy); 3459 // The array size is unimportant. The first thing we do on CurTy is getting 3460 // its element type. 3461 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3462 for (const SCEV *IndexExpr : IndexExprs) { 3463 // Compute the (potentially symbolic) offset in bytes for this index. 3464 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3465 // For a struct, add the member offset. 3466 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3467 unsigned FieldNo = Index->getZExtValue(); 3468 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3469 3470 // Add the field offset to the running total offset. 3471 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3472 3473 // Update CurTy to the type of the field at Index. 3474 CurTy = STy->getTypeAtIndex(Index); 3475 } else { 3476 // Update CurTy to its element type. 3477 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3478 // For an array, add the element offset, explicitly scaled. 3479 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3480 // Getelementptr indices are signed. 3481 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3482 3483 // Multiply the index by the element size to compute the element offset. 3484 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3485 3486 // Add the element offset to the running total offset. 3487 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3488 } 3489 } 3490 3491 // Add the total offset from all the GEP indices to the base. 3492 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3493 } 3494 3495 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3496 const SCEV *RHS) { 3497 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3498 return getSMaxExpr(Ops); 3499 } 3500 3501 const SCEV * 3502 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3503 assert(!Ops.empty() && "Cannot get empty smax!"); 3504 if (Ops.size() == 1) return Ops[0]; 3505 #ifndef NDEBUG 3506 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3507 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3508 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3509 "SCEVSMaxExpr operand types don't match!"); 3510 #endif 3511 3512 // Sort by complexity, this groups all similar expression types together. 3513 GroupByComplexity(Ops, &LI, DT); 3514 3515 // If there are any constants, fold them together. 3516 unsigned Idx = 0; 3517 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3518 ++Idx; 3519 assert(Idx < Ops.size()); 3520 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3521 // We found two constants, fold them together! 3522 ConstantInt *Fold = ConstantInt::get( 3523 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3524 Ops[0] = getConstant(Fold); 3525 Ops.erase(Ops.begin()+1); // Erase the folded element 3526 if (Ops.size() == 1) return Ops[0]; 3527 LHSC = cast<SCEVConstant>(Ops[0]); 3528 } 3529 3530 // If we are left with a constant minimum-int, strip it off. 3531 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3532 Ops.erase(Ops.begin()); 3533 --Idx; 3534 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3535 // If we have an smax with a constant maximum-int, it will always be 3536 // maximum-int. 3537 return Ops[0]; 3538 } 3539 3540 if (Ops.size() == 1) return Ops[0]; 3541 } 3542 3543 // Find the first SMax 3544 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3545 ++Idx; 3546 3547 // Check to see if one of the operands is an SMax. If so, expand its operands 3548 // onto our operand list, and recurse to simplify. 3549 if (Idx < Ops.size()) { 3550 bool DeletedSMax = false; 3551 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3552 Ops.erase(Ops.begin()+Idx); 3553 Ops.append(SMax->op_begin(), SMax->op_end()); 3554 DeletedSMax = true; 3555 } 3556 3557 if (DeletedSMax) 3558 return getSMaxExpr(Ops); 3559 } 3560 3561 // Okay, check to see if the same value occurs in the operand list twice. If 3562 // so, delete one. Since we sorted the list, these values are required to 3563 // be adjacent. 3564 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3565 // X smax Y smax Y --> X smax Y 3566 // X smax Y --> X, if X is always greater than Y 3567 if (Ops[i] == Ops[i+1] || 3568 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3569 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3570 --i; --e; 3571 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3572 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3573 --i; --e; 3574 } 3575 3576 if (Ops.size() == 1) return Ops[0]; 3577 3578 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3579 3580 // Okay, it looks like we really DO need an smax expr. Check to see if we 3581 // already have one, otherwise create a new one. 3582 FoldingSetNodeID ID; 3583 ID.AddInteger(scSMaxExpr); 3584 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3585 ID.AddPointer(Ops[i]); 3586 void *IP = nullptr; 3587 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3588 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3589 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3590 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3591 O, Ops.size()); 3592 UniqueSCEVs.InsertNode(S, IP); 3593 addToLoopUseLists(S); 3594 return S; 3595 } 3596 3597 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3598 const SCEV *RHS) { 3599 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3600 return getUMaxExpr(Ops); 3601 } 3602 3603 const SCEV * 3604 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3605 assert(!Ops.empty() && "Cannot get empty umax!"); 3606 if (Ops.size() == 1) return Ops[0]; 3607 #ifndef NDEBUG 3608 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3609 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3610 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3611 "SCEVUMaxExpr operand types don't match!"); 3612 #endif 3613 3614 // Sort by complexity, this groups all similar expression types together. 3615 GroupByComplexity(Ops, &LI, DT); 3616 3617 // If there are any constants, fold them together. 3618 unsigned Idx = 0; 3619 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3620 ++Idx; 3621 assert(Idx < Ops.size()); 3622 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3623 // We found two constants, fold them together! 3624 ConstantInt *Fold = ConstantInt::get( 3625 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3626 Ops[0] = getConstant(Fold); 3627 Ops.erase(Ops.begin()+1); // Erase the folded element 3628 if (Ops.size() == 1) return Ops[0]; 3629 LHSC = cast<SCEVConstant>(Ops[0]); 3630 } 3631 3632 // If we are left with a constant minimum-int, strip it off. 3633 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3634 Ops.erase(Ops.begin()); 3635 --Idx; 3636 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3637 // If we have an umax with a constant maximum-int, it will always be 3638 // maximum-int. 3639 return Ops[0]; 3640 } 3641 3642 if (Ops.size() == 1) return Ops[0]; 3643 } 3644 3645 // Find the first UMax 3646 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3647 ++Idx; 3648 3649 // Check to see if one of the operands is a UMax. If so, expand its operands 3650 // onto our operand list, and recurse to simplify. 3651 if (Idx < Ops.size()) { 3652 bool DeletedUMax = false; 3653 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3654 Ops.erase(Ops.begin()+Idx); 3655 Ops.append(UMax->op_begin(), UMax->op_end()); 3656 DeletedUMax = true; 3657 } 3658 3659 if (DeletedUMax) 3660 return getUMaxExpr(Ops); 3661 } 3662 3663 // Okay, check to see if the same value occurs in the operand list twice. If 3664 // so, delete one. Since we sorted the list, these values are required to 3665 // be adjacent. 3666 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3667 // X umax Y umax Y --> X umax Y 3668 // X umax Y --> X, if X is always greater than Y 3669 if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning( 3670 ICmpInst::ICMP_UGE, Ops[i], Ops[i + 1])) { 3671 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3672 --i; --e; 3673 } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, Ops[i], 3674 Ops[i + 1])) { 3675 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3676 --i; --e; 3677 } 3678 3679 if (Ops.size() == 1) return Ops[0]; 3680 3681 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3682 3683 // Okay, it looks like we really DO need a umax expr. Check to see if we 3684 // already have one, otherwise create a new one. 3685 FoldingSetNodeID ID; 3686 ID.AddInteger(scUMaxExpr); 3687 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3688 ID.AddPointer(Ops[i]); 3689 void *IP = nullptr; 3690 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3691 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3692 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3693 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3694 O, Ops.size()); 3695 UniqueSCEVs.InsertNode(S, IP); 3696 addToLoopUseLists(S); 3697 return S; 3698 } 3699 3700 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3701 const SCEV *RHS) { 3702 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3703 return getSMinExpr(Ops); 3704 } 3705 3706 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3707 // ~smax(~x, ~y, ~z) == smin(x, y, z). 3708 SmallVector<const SCEV *, 2> NotOps; 3709 for (auto *S : Ops) 3710 NotOps.push_back(getNotSCEV(S)); 3711 return getNotSCEV(getSMaxExpr(NotOps)); 3712 } 3713 3714 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3715 const SCEV *RHS) { 3716 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3717 return getUMinExpr(Ops); 3718 } 3719 3720 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3721 assert(!Ops.empty() && "At least one operand must be!"); 3722 // Trivial case. 3723 if (Ops.size() == 1) 3724 return Ops[0]; 3725 3726 // ~umax(~x, ~y, ~z) == umin(x, y, z). 3727 SmallVector<const SCEV *, 2> NotOps; 3728 for (auto *S : Ops) 3729 NotOps.push_back(getNotSCEV(S)); 3730 return getNotSCEV(getUMaxExpr(NotOps)); 3731 } 3732 3733 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3734 // We can bypass creating a target-independent 3735 // constant expression and then folding it back into a ConstantInt. 3736 // This is just a compile-time optimization. 3737 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3738 } 3739 3740 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3741 StructType *STy, 3742 unsigned FieldNo) { 3743 // We can bypass creating a target-independent 3744 // constant expression and then folding it back into a ConstantInt. 3745 // This is just a compile-time optimization. 3746 return getConstant( 3747 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3748 } 3749 3750 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3751 // Don't attempt to do anything other than create a SCEVUnknown object 3752 // here. createSCEV only calls getUnknown after checking for all other 3753 // interesting possibilities, and any other code that calls getUnknown 3754 // is doing so in order to hide a value from SCEV canonicalization. 3755 3756 FoldingSetNodeID ID; 3757 ID.AddInteger(scUnknown); 3758 ID.AddPointer(V); 3759 void *IP = nullptr; 3760 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3761 assert(cast<SCEVUnknown>(S)->getValue() == V && 3762 "Stale SCEVUnknown in uniquing map!"); 3763 return S; 3764 } 3765 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3766 FirstUnknown); 3767 FirstUnknown = cast<SCEVUnknown>(S); 3768 UniqueSCEVs.InsertNode(S, IP); 3769 return S; 3770 } 3771 3772 //===----------------------------------------------------------------------===// 3773 // Basic SCEV Analysis and PHI Idiom Recognition Code 3774 // 3775 3776 /// Test if values of the given type are analyzable within the SCEV 3777 /// framework. This primarily includes integer types, and it can optionally 3778 /// include pointer types if the ScalarEvolution class has access to 3779 /// target-specific information. 3780 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3781 // Integers and pointers are always SCEVable. 3782 return Ty->isIntOrPtrTy(); 3783 } 3784 3785 /// Return the size in bits of the specified type, for which isSCEVable must 3786 /// return true. 3787 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3788 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3789 if (Ty->isPointerTy()) 3790 return getDataLayout().getIndexTypeSizeInBits(Ty); 3791 return getDataLayout().getTypeSizeInBits(Ty); 3792 } 3793 3794 /// Return a type with the same bitwidth as the given type and which represents 3795 /// how SCEV will treat the given type, for which isSCEVable must return 3796 /// true. For pointer types, this is the pointer-sized integer type. 3797 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3798 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3799 3800 if (Ty->isIntegerTy()) 3801 return Ty; 3802 3803 // The only other support type is pointer. 3804 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3805 return getDataLayout().getIntPtrType(Ty); 3806 } 3807 3808 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3809 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3810 } 3811 3812 const SCEV *ScalarEvolution::getCouldNotCompute() { 3813 return CouldNotCompute.get(); 3814 } 3815 3816 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3817 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3818 auto *SU = dyn_cast<SCEVUnknown>(S); 3819 return SU && SU->getValue() == nullptr; 3820 }); 3821 3822 return !ContainsNulls; 3823 } 3824 3825 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3826 HasRecMapType::iterator I = HasRecMap.find(S); 3827 if (I != HasRecMap.end()) 3828 return I->second; 3829 3830 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3831 HasRecMap.insert({S, FoundAddRec}); 3832 return FoundAddRec; 3833 } 3834 3835 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3836 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3837 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3838 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3839 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3840 if (!Add) 3841 return {S, nullptr}; 3842 3843 if (Add->getNumOperands() != 2) 3844 return {S, nullptr}; 3845 3846 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3847 if (!ConstOp) 3848 return {S, nullptr}; 3849 3850 return {Add->getOperand(1), ConstOp->getValue()}; 3851 } 3852 3853 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3854 /// by the value and offset from any ValueOffsetPair in the set. 3855 SetVector<ScalarEvolution::ValueOffsetPair> * 3856 ScalarEvolution::getSCEVValues(const SCEV *S) { 3857 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3858 if (SI == ExprValueMap.end()) 3859 return nullptr; 3860 #ifndef NDEBUG 3861 if (VerifySCEVMap) { 3862 // Check there is no dangling Value in the set returned. 3863 for (const auto &VE : SI->second) 3864 assert(ValueExprMap.count(VE.first)); 3865 } 3866 #endif 3867 return &SI->second; 3868 } 3869 3870 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3871 /// cannot be used separately. eraseValueFromMap should be used to remove 3872 /// V from ValueExprMap and ExprValueMap at the same time. 3873 void ScalarEvolution::eraseValueFromMap(Value *V) { 3874 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3875 if (I != ValueExprMap.end()) { 3876 const SCEV *S = I->second; 3877 // Remove {V, 0} from the set of ExprValueMap[S] 3878 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3879 SV->remove({V, nullptr}); 3880 3881 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3882 const SCEV *Stripped; 3883 ConstantInt *Offset; 3884 std::tie(Stripped, Offset) = splitAddExpr(S); 3885 if (Offset != nullptr) { 3886 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3887 SV->remove({V, Offset}); 3888 } 3889 ValueExprMap.erase(V); 3890 } 3891 } 3892 3893 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3894 /// TODO: In reality it is better to check the poison recursevely 3895 /// but this is better than nothing. 3896 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3897 if (auto *I = dyn_cast<Instruction>(V)) { 3898 if (isa<OverflowingBinaryOperator>(I)) { 3899 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3900 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3901 return true; 3902 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3903 return true; 3904 } 3905 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3906 return true; 3907 } 3908 return false; 3909 } 3910 3911 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3912 /// create a new one. 3913 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3914 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3915 3916 const SCEV *S = getExistingSCEV(V); 3917 if (S == nullptr) { 3918 S = createSCEV(V); 3919 // During PHI resolution, it is possible to create two SCEVs for the same 3920 // V, so it is needed to double check whether V->S is inserted into 3921 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3922 std::pair<ValueExprMapType::iterator, bool> Pair = 3923 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3924 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3925 ExprValueMap[S].insert({V, nullptr}); 3926 3927 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3928 // ExprValueMap. 3929 const SCEV *Stripped = S; 3930 ConstantInt *Offset = nullptr; 3931 std::tie(Stripped, Offset) = splitAddExpr(S); 3932 // If stripped is SCEVUnknown, don't bother to save 3933 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3934 // increase the complexity of the expansion code. 3935 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3936 // because it may generate add/sub instead of GEP in SCEV expansion. 3937 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3938 !isa<GetElementPtrInst>(V)) 3939 ExprValueMap[Stripped].insert({V, Offset}); 3940 } 3941 } 3942 return S; 3943 } 3944 3945 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3946 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3947 3948 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3949 if (I != ValueExprMap.end()) { 3950 const SCEV *S = I->second; 3951 if (checkValidity(S)) 3952 return S; 3953 eraseValueFromMap(V); 3954 forgetMemoizedResults(S); 3955 } 3956 return nullptr; 3957 } 3958 3959 /// Return a SCEV corresponding to -V = -1*V 3960 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3961 SCEV::NoWrapFlags Flags) { 3962 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3963 return getConstant( 3964 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3965 3966 Type *Ty = V->getType(); 3967 Ty = getEffectiveSCEVType(Ty); 3968 return getMulExpr( 3969 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3970 } 3971 3972 /// Return a SCEV corresponding to ~V = -1-V 3973 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3974 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3975 return getConstant( 3976 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3977 3978 Type *Ty = V->getType(); 3979 Ty = getEffectiveSCEVType(Ty); 3980 const SCEV *AllOnes = 3981 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3982 return getMinusSCEV(AllOnes, V); 3983 } 3984 3985 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3986 SCEV::NoWrapFlags Flags, 3987 unsigned Depth) { 3988 // Fast path: X - X --> 0. 3989 if (LHS == RHS) 3990 return getZero(LHS->getType()); 3991 3992 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3993 // makes it so that we cannot make much use of NUW. 3994 auto AddFlags = SCEV::FlagAnyWrap; 3995 const bool RHSIsNotMinSigned = 3996 !getSignedRangeMin(RHS).isMinSignedValue(); 3997 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3998 // Let M be the minimum representable signed value. Then (-1)*RHS 3999 // signed-wraps if and only if RHS is M. That can happen even for 4000 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4001 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4002 // (-1)*RHS, we need to prove that RHS != M. 4003 // 4004 // If LHS is non-negative and we know that LHS - RHS does not 4005 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4006 // either by proving that RHS > M or that LHS >= 0. 4007 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4008 AddFlags = SCEV::FlagNSW; 4009 } 4010 } 4011 4012 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4013 // RHS is NSW and LHS >= 0. 4014 // 4015 // The difficulty here is that the NSW flag may have been proven 4016 // relative to a loop that is to be found in a recurrence in LHS and 4017 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4018 // larger scope than intended. 4019 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4020 4021 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4022 } 4023 4024 const SCEV * 4025 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 4026 Type *SrcTy = V->getType(); 4027 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4028 "Cannot truncate or zero extend with non-integer arguments!"); 4029 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4030 return V; // No conversion 4031 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4032 return getTruncateExpr(V, Ty); 4033 return getZeroExtendExpr(V, Ty); 4034 } 4035 4036 const SCEV * 4037 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 4038 Type *Ty) { 4039 Type *SrcTy = V->getType(); 4040 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4041 "Cannot truncate or zero extend with non-integer arguments!"); 4042 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4043 return V; // No conversion 4044 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4045 return getTruncateExpr(V, Ty); 4046 return getSignExtendExpr(V, Ty); 4047 } 4048 4049 const SCEV * 4050 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4051 Type *SrcTy = V->getType(); 4052 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4053 "Cannot noop or zero extend with non-integer arguments!"); 4054 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4055 "getNoopOrZeroExtend cannot truncate!"); 4056 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4057 return V; // No conversion 4058 return getZeroExtendExpr(V, Ty); 4059 } 4060 4061 const SCEV * 4062 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4063 Type *SrcTy = V->getType(); 4064 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4065 "Cannot noop or sign extend with non-integer arguments!"); 4066 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4067 "getNoopOrSignExtend cannot truncate!"); 4068 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4069 return V; // No conversion 4070 return getSignExtendExpr(V, Ty); 4071 } 4072 4073 const SCEV * 4074 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4075 Type *SrcTy = V->getType(); 4076 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4077 "Cannot noop or any extend with non-integer arguments!"); 4078 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4079 "getNoopOrAnyExtend cannot truncate!"); 4080 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4081 return V; // No conversion 4082 return getAnyExtendExpr(V, Ty); 4083 } 4084 4085 const SCEV * 4086 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4087 Type *SrcTy = V->getType(); 4088 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4089 "Cannot truncate or noop with non-integer arguments!"); 4090 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4091 "getTruncateOrNoop cannot extend!"); 4092 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4093 return V; // No conversion 4094 return getTruncateExpr(V, Ty); 4095 } 4096 4097 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4098 const SCEV *RHS) { 4099 const SCEV *PromotedLHS = LHS; 4100 const SCEV *PromotedRHS = RHS; 4101 4102 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4103 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4104 else 4105 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4106 4107 return getUMaxExpr(PromotedLHS, PromotedRHS); 4108 } 4109 4110 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4111 const SCEV *RHS) { 4112 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4113 return getUMinFromMismatchedTypes(Ops); 4114 } 4115 4116 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4117 SmallVectorImpl<const SCEV *> &Ops) { 4118 assert(!Ops.empty() && "At least one operand must be!"); 4119 // Trivial case. 4120 if (Ops.size() == 1) 4121 return Ops[0]; 4122 4123 // Find the max type first. 4124 Type *MaxType = nullptr; 4125 for (auto *S : Ops) 4126 if (MaxType) 4127 MaxType = getWiderType(MaxType, S->getType()); 4128 else 4129 MaxType = S->getType(); 4130 4131 // Extend all ops to max type. 4132 SmallVector<const SCEV *, 2> PromotedOps; 4133 for (auto *S : Ops) 4134 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4135 4136 // Generate umin. 4137 return getUMinExpr(PromotedOps); 4138 } 4139 4140 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4141 // A pointer operand may evaluate to a nonpointer expression, such as null. 4142 if (!V->getType()->isPointerTy()) 4143 return V; 4144 4145 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4146 return getPointerBase(Cast->getOperand()); 4147 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4148 const SCEV *PtrOp = nullptr; 4149 for (const SCEV *NAryOp : NAry->operands()) { 4150 if (NAryOp->getType()->isPointerTy()) { 4151 // Cannot find the base of an expression with multiple pointer operands. 4152 if (PtrOp) 4153 return V; 4154 PtrOp = NAryOp; 4155 } 4156 } 4157 if (!PtrOp) 4158 return V; 4159 return getPointerBase(PtrOp); 4160 } 4161 return V; 4162 } 4163 4164 /// Push users of the given Instruction onto the given Worklist. 4165 static void 4166 PushDefUseChildren(Instruction *I, 4167 SmallVectorImpl<Instruction *> &Worklist) { 4168 // Push the def-use children onto the Worklist stack. 4169 for (User *U : I->users()) 4170 Worklist.push_back(cast<Instruction>(U)); 4171 } 4172 4173 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4174 SmallVector<Instruction *, 16> Worklist; 4175 PushDefUseChildren(PN, Worklist); 4176 4177 SmallPtrSet<Instruction *, 8> Visited; 4178 Visited.insert(PN); 4179 while (!Worklist.empty()) { 4180 Instruction *I = Worklist.pop_back_val(); 4181 if (!Visited.insert(I).second) 4182 continue; 4183 4184 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4185 if (It != ValueExprMap.end()) { 4186 const SCEV *Old = It->second; 4187 4188 // Short-circuit the def-use traversal if the symbolic name 4189 // ceases to appear in expressions. 4190 if (Old != SymName && !hasOperand(Old, SymName)) 4191 continue; 4192 4193 // SCEVUnknown for a PHI either means that it has an unrecognized 4194 // structure, it's a PHI that's in the progress of being computed 4195 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4196 // additional loop trip count information isn't going to change anything. 4197 // In the second case, createNodeForPHI will perform the necessary 4198 // updates on its own when it gets to that point. In the third, we do 4199 // want to forget the SCEVUnknown. 4200 if (!isa<PHINode>(I) || 4201 !isa<SCEVUnknown>(Old) || 4202 (I != PN && Old == SymName)) { 4203 eraseValueFromMap(It->first); 4204 forgetMemoizedResults(Old); 4205 } 4206 } 4207 4208 PushDefUseChildren(I, Worklist); 4209 } 4210 } 4211 4212 namespace { 4213 4214 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4215 /// expression in case its Loop is L. If it is not L then 4216 /// if IgnoreOtherLoops is true then use AddRec itself 4217 /// otherwise rewrite cannot be done. 4218 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4219 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4220 public: 4221 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4222 bool IgnoreOtherLoops = true) { 4223 SCEVInitRewriter Rewriter(L, SE); 4224 const SCEV *Result = Rewriter.visit(S); 4225 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4226 return SE.getCouldNotCompute(); 4227 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4228 ? SE.getCouldNotCompute() 4229 : Result; 4230 } 4231 4232 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4233 if (!SE.isLoopInvariant(Expr, L)) 4234 SeenLoopVariantSCEVUnknown = true; 4235 return Expr; 4236 } 4237 4238 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4239 // Only re-write AddRecExprs for this loop. 4240 if (Expr->getLoop() == L) 4241 return Expr->getStart(); 4242 SeenOtherLoops = true; 4243 return Expr; 4244 } 4245 4246 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4247 4248 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4249 4250 private: 4251 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4252 : SCEVRewriteVisitor(SE), L(L) {} 4253 4254 const Loop *L; 4255 bool SeenLoopVariantSCEVUnknown = false; 4256 bool SeenOtherLoops = false; 4257 }; 4258 4259 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4260 /// increment expression in case its Loop is L. If it is not L then 4261 /// use AddRec itself. 4262 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4263 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4264 public: 4265 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4266 SCEVPostIncRewriter Rewriter(L, SE); 4267 const SCEV *Result = Rewriter.visit(S); 4268 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4269 ? SE.getCouldNotCompute() 4270 : Result; 4271 } 4272 4273 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4274 if (!SE.isLoopInvariant(Expr, L)) 4275 SeenLoopVariantSCEVUnknown = true; 4276 return Expr; 4277 } 4278 4279 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4280 // Only re-write AddRecExprs for this loop. 4281 if (Expr->getLoop() == L) 4282 return Expr->getPostIncExpr(SE); 4283 SeenOtherLoops = true; 4284 return Expr; 4285 } 4286 4287 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4288 4289 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4290 4291 private: 4292 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4293 : SCEVRewriteVisitor(SE), L(L) {} 4294 4295 const Loop *L; 4296 bool SeenLoopVariantSCEVUnknown = false; 4297 bool SeenOtherLoops = false; 4298 }; 4299 4300 /// This class evaluates the compare condition by matching it against the 4301 /// condition of loop latch. If there is a match we assume a true value 4302 /// for the condition while building SCEV nodes. 4303 class SCEVBackedgeConditionFolder 4304 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4305 public: 4306 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4307 ScalarEvolution &SE) { 4308 bool IsPosBECond = false; 4309 Value *BECond = nullptr; 4310 if (BasicBlock *Latch = L->getLoopLatch()) { 4311 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4312 if (BI && BI->isConditional()) { 4313 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4314 "Both outgoing branches should not target same header!"); 4315 BECond = BI->getCondition(); 4316 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4317 } else { 4318 return S; 4319 } 4320 } 4321 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4322 return Rewriter.visit(S); 4323 } 4324 4325 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4326 const SCEV *Result = Expr; 4327 bool InvariantF = SE.isLoopInvariant(Expr, L); 4328 4329 if (!InvariantF) { 4330 Instruction *I = cast<Instruction>(Expr->getValue()); 4331 switch (I->getOpcode()) { 4332 case Instruction::Select: { 4333 SelectInst *SI = cast<SelectInst>(I); 4334 Optional<const SCEV *> Res = 4335 compareWithBackedgeCondition(SI->getCondition()); 4336 if (Res.hasValue()) { 4337 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4338 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4339 } 4340 break; 4341 } 4342 default: { 4343 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4344 if (Res.hasValue()) 4345 Result = Res.getValue(); 4346 break; 4347 } 4348 } 4349 } 4350 return Result; 4351 } 4352 4353 private: 4354 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4355 bool IsPosBECond, ScalarEvolution &SE) 4356 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4357 IsPositiveBECond(IsPosBECond) {} 4358 4359 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4360 4361 const Loop *L; 4362 /// Loop back condition. 4363 Value *BackedgeCond = nullptr; 4364 /// Set to true if loop back is on positive branch condition. 4365 bool IsPositiveBECond; 4366 }; 4367 4368 Optional<const SCEV *> 4369 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4370 4371 // If value matches the backedge condition for loop latch, 4372 // then return a constant evolution node based on loopback 4373 // branch taken. 4374 if (BackedgeCond == IC) 4375 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4376 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4377 return None; 4378 } 4379 4380 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4381 public: 4382 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4383 ScalarEvolution &SE) { 4384 SCEVShiftRewriter Rewriter(L, SE); 4385 const SCEV *Result = Rewriter.visit(S); 4386 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4387 } 4388 4389 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4390 // Only allow AddRecExprs for this loop. 4391 if (!SE.isLoopInvariant(Expr, L)) 4392 Valid = false; 4393 return Expr; 4394 } 4395 4396 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4397 if (Expr->getLoop() == L && Expr->isAffine()) 4398 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4399 Valid = false; 4400 return Expr; 4401 } 4402 4403 bool isValid() { return Valid; } 4404 4405 private: 4406 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4407 : SCEVRewriteVisitor(SE), L(L) {} 4408 4409 const Loop *L; 4410 bool Valid = true; 4411 }; 4412 4413 } // end anonymous namespace 4414 4415 SCEV::NoWrapFlags 4416 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4417 if (!AR->isAffine()) 4418 return SCEV::FlagAnyWrap; 4419 4420 using OBO = OverflowingBinaryOperator; 4421 4422 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4423 4424 if (!AR->hasNoSignedWrap()) { 4425 ConstantRange AddRecRange = getSignedRange(AR); 4426 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4427 4428 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4429 Instruction::Add, IncRange, OBO::NoSignedWrap); 4430 if (NSWRegion.contains(AddRecRange)) 4431 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4432 } 4433 4434 if (!AR->hasNoUnsignedWrap()) { 4435 ConstantRange AddRecRange = getUnsignedRange(AR); 4436 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4437 4438 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4439 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4440 if (NUWRegion.contains(AddRecRange)) 4441 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4442 } 4443 4444 return Result; 4445 } 4446 4447 namespace { 4448 4449 /// Represents an abstract binary operation. This may exist as a 4450 /// normal instruction or constant expression, or may have been 4451 /// derived from an expression tree. 4452 struct BinaryOp { 4453 unsigned Opcode; 4454 Value *LHS; 4455 Value *RHS; 4456 bool IsNSW = false; 4457 bool IsNUW = false; 4458 4459 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4460 /// constant expression. 4461 Operator *Op = nullptr; 4462 4463 explicit BinaryOp(Operator *Op) 4464 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4465 Op(Op) { 4466 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4467 IsNSW = OBO->hasNoSignedWrap(); 4468 IsNUW = OBO->hasNoUnsignedWrap(); 4469 } 4470 } 4471 4472 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4473 bool IsNUW = false) 4474 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4475 }; 4476 4477 } // end anonymous namespace 4478 4479 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4480 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4481 auto *Op = dyn_cast<Operator>(V); 4482 if (!Op) 4483 return None; 4484 4485 // Implementation detail: all the cleverness here should happen without 4486 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4487 // SCEV expressions when possible, and we should not break that. 4488 4489 switch (Op->getOpcode()) { 4490 case Instruction::Add: 4491 case Instruction::Sub: 4492 case Instruction::Mul: 4493 case Instruction::UDiv: 4494 case Instruction::URem: 4495 case Instruction::And: 4496 case Instruction::Or: 4497 case Instruction::AShr: 4498 case Instruction::Shl: 4499 return BinaryOp(Op); 4500 4501 case Instruction::Xor: 4502 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4503 // If the RHS of the xor is a signmask, then this is just an add. 4504 // Instcombine turns add of signmask into xor as a strength reduction step. 4505 if (RHSC->getValue().isSignMask()) 4506 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4507 return BinaryOp(Op); 4508 4509 case Instruction::LShr: 4510 // Turn logical shift right of a constant into a unsigned divide. 4511 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4512 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4513 4514 // If the shift count is not less than the bitwidth, the result of 4515 // the shift is undefined. Don't try to analyze it, because the 4516 // resolution chosen here may differ from the resolution chosen in 4517 // other parts of the compiler. 4518 if (SA->getValue().ult(BitWidth)) { 4519 Constant *X = 4520 ConstantInt::get(SA->getContext(), 4521 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4522 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4523 } 4524 } 4525 return BinaryOp(Op); 4526 4527 case Instruction::ExtractValue: { 4528 auto *EVI = cast<ExtractValueInst>(Op); 4529 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4530 break; 4531 4532 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 4533 if (!CI) 4534 break; 4535 4536 if (auto *F = CI->getCalledFunction()) 4537 switch (F->getIntrinsicID()) { 4538 case Intrinsic::sadd_with_overflow: 4539 case Intrinsic::uadd_with_overflow: 4540 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4541 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4542 CI->getArgOperand(1)); 4543 4544 // Now that we know that all uses of the arithmetic-result component of 4545 // CI are guarded by the overflow check, we can go ahead and pretend 4546 // that the arithmetic is non-overflowing. 4547 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 4548 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4549 CI->getArgOperand(1), /* IsNSW = */ true, 4550 /* IsNUW = */ false); 4551 else 4552 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4553 CI->getArgOperand(1), /* IsNSW = */ false, 4554 /* IsNUW*/ true); 4555 case Intrinsic::ssub_with_overflow: 4556 case Intrinsic::usub_with_overflow: 4557 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4558 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4559 CI->getArgOperand(1)); 4560 4561 // The same reasoning as sadd/uadd above. 4562 if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow) 4563 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4564 CI->getArgOperand(1), /* IsNSW = */ true, 4565 /* IsNUW = */ false); 4566 else 4567 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4568 CI->getArgOperand(1), /* IsNSW = */ false, 4569 /* IsNUW = */ true); 4570 case Intrinsic::smul_with_overflow: 4571 case Intrinsic::umul_with_overflow: 4572 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4573 CI->getArgOperand(1)); 4574 default: 4575 break; 4576 } 4577 break; 4578 } 4579 4580 default: 4581 break; 4582 } 4583 4584 return None; 4585 } 4586 4587 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4588 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4589 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4590 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4591 /// follows one of the following patterns: 4592 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4593 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4594 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4595 /// we return the type of the truncation operation, and indicate whether the 4596 /// truncated type should be treated as signed/unsigned by setting 4597 /// \p Signed to true/false, respectively. 4598 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4599 bool &Signed, ScalarEvolution &SE) { 4600 // The case where Op == SymbolicPHI (that is, with no type conversions on 4601 // the way) is handled by the regular add recurrence creating logic and 4602 // would have already been triggered in createAddRecForPHI. Reaching it here 4603 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4604 // because one of the other operands of the SCEVAddExpr updating this PHI is 4605 // not invariant). 4606 // 4607 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4608 // this case predicates that allow us to prove that Op == SymbolicPHI will 4609 // be added. 4610 if (Op == SymbolicPHI) 4611 return nullptr; 4612 4613 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4614 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4615 if (SourceBits != NewBits) 4616 return nullptr; 4617 4618 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4619 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4620 if (!SExt && !ZExt) 4621 return nullptr; 4622 const SCEVTruncateExpr *Trunc = 4623 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4624 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4625 if (!Trunc) 4626 return nullptr; 4627 const SCEV *X = Trunc->getOperand(); 4628 if (X != SymbolicPHI) 4629 return nullptr; 4630 Signed = SExt != nullptr; 4631 return Trunc->getType(); 4632 } 4633 4634 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4635 if (!PN->getType()->isIntegerTy()) 4636 return nullptr; 4637 const Loop *L = LI.getLoopFor(PN->getParent()); 4638 if (!L || L->getHeader() != PN->getParent()) 4639 return nullptr; 4640 return L; 4641 } 4642 4643 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4644 // computation that updates the phi follows the following pattern: 4645 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4646 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4647 // If so, try to see if it can be rewritten as an AddRecExpr under some 4648 // Predicates. If successful, return them as a pair. Also cache the results 4649 // of the analysis. 4650 // 4651 // Example usage scenario: 4652 // Say the Rewriter is called for the following SCEV: 4653 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4654 // where: 4655 // %X = phi i64 (%Start, %BEValue) 4656 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4657 // and call this function with %SymbolicPHI = %X. 4658 // 4659 // The analysis will find that the value coming around the backedge has 4660 // the following SCEV: 4661 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4662 // Upon concluding that this matches the desired pattern, the function 4663 // will return the pair {NewAddRec, SmallPredsVec} where: 4664 // NewAddRec = {%Start,+,%Step} 4665 // SmallPredsVec = {P1, P2, P3} as follows: 4666 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4667 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4668 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4669 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4670 // under the predicates {P1,P2,P3}. 4671 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4672 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4673 // 4674 // TODO's: 4675 // 4676 // 1) Extend the Induction descriptor to also support inductions that involve 4677 // casts: When needed (namely, when we are called in the context of the 4678 // vectorizer induction analysis), a Set of cast instructions will be 4679 // populated by this method, and provided back to isInductionPHI. This is 4680 // needed to allow the vectorizer to properly record them to be ignored by 4681 // the cost model and to avoid vectorizing them (otherwise these casts, 4682 // which are redundant under the runtime overflow checks, will be 4683 // vectorized, which can be costly). 4684 // 4685 // 2) Support additional induction/PHISCEV patterns: We also want to support 4686 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4687 // after the induction update operation (the induction increment): 4688 // 4689 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4690 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4691 // 4692 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4693 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4694 // 4695 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4696 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4697 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4698 SmallVector<const SCEVPredicate *, 3> Predicates; 4699 4700 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4701 // return an AddRec expression under some predicate. 4702 4703 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4704 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4705 assert(L && "Expecting an integer loop header phi"); 4706 4707 // The loop may have multiple entrances or multiple exits; we can analyze 4708 // this phi as an addrec if it has a unique entry value and a unique 4709 // backedge value. 4710 Value *BEValueV = nullptr, *StartValueV = nullptr; 4711 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4712 Value *V = PN->getIncomingValue(i); 4713 if (L->contains(PN->getIncomingBlock(i))) { 4714 if (!BEValueV) { 4715 BEValueV = V; 4716 } else if (BEValueV != V) { 4717 BEValueV = nullptr; 4718 break; 4719 } 4720 } else if (!StartValueV) { 4721 StartValueV = V; 4722 } else if (StartValueV != V) { 4723 StartValueV = nullptr; 4724 break; 4725 } 4726 } 4727 if (!BEValueV || !StartValueV) 4728 return None; 4729 4730 const SCEV *BEValue = getSCEV(BEValueV); 4731 4732 // If the value coming around the backedge is an add with the symbolic 4733 // value we just inserted, possibly with casts that we can ignore under 4734 // an appropriate runtime guard, then we found a simple induction variable! 4735 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4736 if (!Add) 4737 return None; 4738 4739 // If there is a single occurrence of the symbolic value, possibly 4740 // casted, replace it with a recurrence. 4741 unsigned FoundIndex = Add->getNumOperands(); 4742 Type *TruncTy = nullptr; 4743 bool Signed; 4744 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4745 if ((TruncTy = 4746 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4747 if (FoundIndex == e) { 4748 FoundIndex = i; 4749 break; 4750 } 4751 4752 if (FoundIndex == Add->getNumOperands()) 4753 return None; 4754 4755 // Create an add with everything but the specified operand. 4756 SmallVector<const SCEV *, 8> Ops; 4757 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4758 if (i != FoundIndex) 4759 Ops.push_back(Add->getOperand(i)); 4760 const SCEV *Accum = getAddExpr(Ops); 4761 4762 // The runtime checks will not be valid if the step amount is 4763 // varying inside the loop. 4764 if (!isLoopInvariant(Accum, L)) 4765 return None; 4766 4767 // *** Part2: Create the predicates 4768 4769 // Analysis was successful: we have a phi-with-cast pattern for which we 4770 // can return an AddRec expression under the following predicates: 4771 // 4772 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4773 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4774 // P2: An Equal predicate that guarantees that 4775 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4776 // P3: An Equal predicate that guarantees that 4777 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4778 // 4779 // As we next prove, the above predicates guarantee that: 4780 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4781 // 4782 // 4783 // More formally, we want to prove that: 4784 // Expr(i+1) = Start + (i+1) * Accum 4785 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4786 // 4787 // Given that: 4788 // 1) Expr(0) = Start 4789 // 2) Expr(1) = Start + Accum 4790 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4791 // 3) Induction hypothesis (step i): 4792 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4793 // 4794 // Proof: 4795 // Expr(i+1) = 4796 // = Start + (i+1)*Accum 4797 // = (Start + i*Accum) + Accum 4798 // = Expr(i) + Accum 4799 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4800 // :: from step i 4801 // 4802 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4803 // 4804 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4805 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4806 // + Accum :: from P3 4807 // 4808 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4809 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4810 // 4811 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4812 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4813 // 4814 // By induction, the same applies to all iterations 1<=i<n: 4815 // 4816 4817 // Create a truncated addrec for which we will add a no overflow check (P1). 4818 const SCEV *StartVal = getSCEV(StartValueV); 4819 const SCEV *PHISCEV = 4820 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4821 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4822 4823 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4824 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4825 // will be constant. 4826 // 4827 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4828 // add P1. 4829 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4830 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4831 Signed ? SCEVWrapPredicate::IncrementNSSW 4832 : SCEVWrapPredicate::IncrementNUSW; 4833 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4834 Predicates.push_back(AddRecPred); 4835 } 4836 4837 // Create the Equal Predicates P2,P3: 4838 4839 // It is possible that the predicates P2 and/or P3 are computable at 4840 // compile time due to StartVal and/or Accum being constants. 4841 // If either one is, then we can check that now and escape if either P2 4842 // or P3 is false. 4843 4844 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4845 // for each of StartVal and Accum 4846 auto getExtendedExpr = [&](const SCEV *Expr, 4847 bool CreateSignExtend) -> const SCEV * { 4848 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4849 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4850 const SCEV *ExtendedExpr = 4851 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4852 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4853 return ExtendedExpr; 4854 }; 4855 4856 // Given: 4857 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4858 // = getExtendedExpr(Expr) 4859 // Determine whether the predicate P: Expr == ExtendedExpr 4860 // is known to be false at compile time 4861 auto PredIsKnownFalse = [&](const SCEV *Expr, 4862 const SCEV *ExtendedExpr) -> bool { 4863 return Expr != ExtendedExpr && 4864 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4865 }; 4866 4867 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4868 if (PredIsKnownFalse(StartVal, StartExtended)) { 4869 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4870 return None; 4871 } 4872 4873 // The Step is always Signed (because the overflow checks are either 4874 // NSSW or NUSW) 4875 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4876 if (PredIsKnownFalse(Accum, AccumExtended)) { 4877 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4878 return None; 4879 } 4880 4881 auto AppendPredicate = [&](const SCEV *Expr, 4882 const SCEV *ExtendedExpr) -> void { 4883 if (Expr != ExtendedExpr && 4884 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4885 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4886 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4887 Predicates.push_back(Pred); 4888 } 4889 }; 4890 4891 AppendPredicate(StartVal, StartExtended); 4892 AppendPredicate(Accum, AccumExtended); 4893 4894 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4895 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4896 // into NewAR if it will also add the runtime overflow checks specified in 4897 // Predicates. 4898 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4899 4900 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4901 std::make_pair(NewAR, Predicates); 4902 // Remember the result of the analysis for this SCEV at this locayyytion. 4903 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4904 return PredRewrite; 4905 } 4906 4907 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4908 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4909 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4910 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4911 if (!L) 4912 return None; 4913 4914 // Check to see if we already analyzed this PHI. 4915 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4916 if (I != PredicatedSCEVRewrites.end()) { 4917 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4918 I->second; 4919 // Analysis was done before and failed to create an AddRec: 4920 if (Rewrite.first == SymbolicPHI) 4921 return None; 4922 // Analysis was done before and succeeded to create an AddRec under 4923 // a predicate: 4924 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4925 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4926 return Rewrite; 4927 } 4928 4929 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4930 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4931 4932 // Record in the cache that the analysis failed 4933 if (!Rewrite) { 4934 SmallVector<const SCEVPredicate *, 3> Predicates; 4935 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4936 return None; 4937 } 4938 4939 return Rewrite; 4940 } 4941 4942 // FIXME: This utility is currently required because the Rewriter currently 4943 // does not rewrite this expression: 4944 // {0, +, (sext ix (trunc iy to ix) to iy)} 4945 // into {0, +, %step}, 4946 // even when the following Equal predicate exists: 4947 // "%step == (sext ix (trunc iy to ix) to iy)". 4948 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4949 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4950 if (AR1 == AR2) 4951 return true; 4952 4953 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4954 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4955 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4956 return false; 4957 return true; 4958 }; 4959 4960 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4961 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4962 return false; 4963 return true; 4964 } 4965 4966 /// A helper function for createAddRecFromPHI to handle simple cases. 4967 /// 4968 /// This function tries to find an AddRec expression for the simplest (yet most 4969 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4970 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4971 /// technique for finding the AddRec expression. 4972 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4973 Value *BEValueV, 4974 Value *StartValueV) { 4975 const Loop *L = LI.getLoopFor(PN->getParent()); 4976 assert(L && L->getHeader() == PN->getParent()); 4977 assert(BEValueV && StartValueV); 4978 4979 auto BO = MatchBinaryOp(BEValueV, DT); 4980 if (!BO) 4981 return nullptr; 4982 4983 if (BO->Opcode != Instruction::Add) 4984 return nullptr; 4985 4986 const SCEV *Accum = nullptr; 4987 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4988 Accum = getSCEV(BO->RHS); 4989 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4990 Accum = getSCEV(BO->LHS); 4991 4992 if (!Accum) 4993 return nullptr; 4994 4995 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4996 if (BO->IsNUW) 4997 Flags = setFlags(Flags, SCEV::FlagNUW); 4998 if (BO->IsNSW) 4999 Flags = setFlags(Flags, SCEV::FlagNSW); 5000 5001 const SCEV *StartVal = getSCEV(StartValueV); 5002 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5003 5004 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5005 5006 // We can add Flags to the post-inc expression only if we 5007 // know that it is *undefined behavior* for BEValueV to 5008 // overflow. 5009 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5010 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5011 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5012 5013 return PHISCEV; 5014 } 5015 5016 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5017 const Loop *L = LI.getLoopFor(PN->getParent()); 5018 if (!L || L->getHeader() != PN->getParent()) 5019 return nullptr; 5020 5021 // The loop may have multiple entrances or multiple exits; we can analyze 5022 // this phi as an addrec if it has a unique entry value and a unique 5023 // backedge value. 5024 Value *BEValueV = nullptr, *StartValueV = nullptr; 5025 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5026 Value *V = PN->getIncomingValue(i); 5027 if (L->contains(PN->getIncomingBlock(i))) { 5028 if (!BEValueV) { 5029 BEValueV = V; 5030 } else if (BEValueV != V) { 5031 BEValueV = nullptr; 5032 break; 5033 } 5034 } else if (!StartValueV) { 5035 StartValueV = V; 5036 } else if (StartValueV != V) { 5037 StartValueV = nullptr; 5038 break; 5039 } 5040 } 5041 if (!BEValueV || !StartValueV) 5042 return nullptr; 5043 5044 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5045 "PHI node already processed?"); 5046 5047 // First, try to find AddRec expression without creating a fictituos symbolic 5048 // value for PN. 5049 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5050 return S; 5051 5052 // Handle PHI node value symbolically. 5053 const SCEV *SymbolicName = getUnknown(PN); 5054 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5055 5056 // Using this symbolic name for the PHI, analyze the value coming around 5057 // the back-edge. 5058 const SCEV *BEValue = getSCEV(BEValueV); 5059 5060 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5061 // has a special value for the first iteration of the loop. 5062 5063 // If the value coming around the backedge is an add with the symbolic 5064 // value we just inserted, then we found a simple induction variable! 5065 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5066 // If there is a single occurrence of the symbolic value, replace it 5067 // with a recurrence. 5068 unsigned FoundIndex = Add->getNumOperands(); 5069 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5070 if (Add->getOperand(i) == SymbolicName) 5071 if (FoundIndex == e) { 5072 FoundIndex = i; 5073 break; 5074 } 5075 5076 if (FoundIndex != Add->getNumOperands()) { 5077 // Create an add with everything but the specified operand. 5078 SmallVector<const SCEV *, 8> Ops; 5079 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5080 if (i != FoundIndex) 5081 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5082 L, *this)); 5083 const SCEV *Accum = getAddExpr(Ops); 5084 5085 // This is not a valid addrec if the step amount is varying each 5086 // loop iteration, but is not itself an addrec in this loop. 5087 if (isLoopInvariant(Accum, L) || 5088 (isa<SCEVAddRecExpr>(Accum) && 5089 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5090 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5091 5092 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5093 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5094 if (BO->IsNUW) 5095 Flags = setFlags(Flags, SCEV::FlagNUW); 5096 if (BO->IsNSW) 5097 Flags = setFlags(Flags, SCEV::FlagNSW); 5098 } 5099 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5100 // If the increment is an inbounds GEP, then we know the address 5101 // space cannot be wrapped around. We cannot make any guarantee 5102 // about signed or unsigned overflow because pointers are 5103 // unsigned but we may have a negative index from the base 5104 // pointer. We can guarantee that no unsigned wrap occurs if the 5105 // indices form a positive value. 5106 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5107 Flags = setFlags(Flags, SCEV::FlagNW); 5108 5109 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5110 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5111 Flags = setFlags(Flags, SCEV::FlagNUW); 5112 } 5113 5114 // We cannot transfer nuw and nsw flags from subtraction 5115 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5116 // for instance. 5117 } 5118 5119 const SCEV *StartVal = getSCEV(StartValueV); 5120 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5121 5122 // Okay, for the entire analysis of this edge we assumed the PHI 5123 // to be symbolic. We now need to go back and purge all of the 5124 // entries for the scalars that use the symbolic expression. 5125 forgetSymbolicName(PN, SymbolicName); 5126 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5127 5128 // We can add Flags to the post-inc expression only if we 5129 // know that it is *undefined behavior* for BEValueV to 5130 // overflow. 5131 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5132 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5133 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5134 5135 return PHISCEV; 5136 } 5137 } 5138 } else { 5139 // Otherwise, this could be a loop like this: 5140 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5141 // In this case, j = {1,+,1} and BEValue is j. 5142 // Because the other in-value of i (0) fits the evolution of BEValue 5143 // i really is an addrec evolution. 5144 // 5145 // We can generalize this saying that i is the shifted value of BEValue 5146 // by one iteration: 5147 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5148 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5149 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5150 if (Shifted != getCouldNotCompute() && 5151 Start != getCouldNotCompute()) { 5152 const SCEV *StartVal = getSCEV(StartValueV); 5153 if (Start == StartVal) { 5154 // Okay, for the entire analysis of this edge we assumed the PHI 5155 // to be symbolic. We now need to go back and purge all of the 5156 // entries for the scalars that use the symbolic expression. 5157 forgetSymbolicName(PN, SymbolicName); 5158 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5159 return Shifted; 5160 } 5161 } 5162 } 5163 5164 // Remove the temporary PHI node SCEV that has been inserted while intending 5165 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5166 // as it will prevent later (possibly simpler) SCEV expressions to be added 5167 // to the ValueExprMap. 5168 eraseValueFromMap(PN); 5169 5170 return nullptr; 5171 } 5172 5173 // Checks if the SCEV S is available at BB. S is considered available at BB 5174 // if S can be materialized at BB without introducing a fault. 5175 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5176 BasicBlock *BB) { 5177 struct CheckAvailable { 5178 bool TraversalDone = false; 5179 bool Available = true; 5180 5181 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5182 BasicBlock *BB = nullptr; 5183 DominatorTree &DT; 5184 5185 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5186 : L(L), BB(BB), DT(DT) {} 5187 5188 bool setUnavailable() { 5189 TraversalDone = true; 5190 Available = false; 5191 return false; 5192 } 5193 5194 bool follow(const SCEV *S) { 5195 switch (S->getSCEVType()) { 5196 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5197 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5198 // These expressions are available if their operand(s) is/are. 5199 return true; 5200 5201 case scAddRecExpr: { 5202 // We allow add recurrences that are on the loop BB is in, or some 5203 // outer loop. This guarantees availability because the value of the 5204 // add recurrence at BB is simply the "current" value of the induction 5205 // variable. We can relax this in the future; for instance an add 5206 // recurrence on a sibling dominating loop is also available at BB. 5207 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5208 if (L && (ARLoop == L || ARLoop->contains(L))) 5209 return true; 5210 5211 return setUnavailable(); 5212 } 5213 5214 case scUnknown: { 5215 // For SCEVUnknown, we check for simple dominance. 5216 const auto *SU = cast<SCEVUnknown>(S); 5217 Value *V = SU->getValue(); 5218 5219 if (isa<Argument>(V)) 5220 return false; 5221 5222 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5223 return false; 5224 5225 return setUnavailable(); 5226 } 5227 5228 case scUDivExpr: 5229 case scCouldNotCompute: 5230 // We do not try to smart about these at all. 5231 return setUnavailable(); 5232 } 5233 llvm_unreachable("switch should be fully covered!"); 5234 } 5235 5236 bool isDone() { return TraversalDone; } 5237 }; 5238 5239 CheckAvailable CA(L, BB, DT); 5240 SCEVTraversal<CheckAvailable> ST(CA); 5241 5242 ST.visitAll(S); 5243 return CA.Available; 5244 } 5245 5246 // Try to match a control flow sequence that branches out at BI and merges back 5247 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5248 // match. 5249 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5250 Value *&C, Value *&LHS, Value *&RHS) { 5251 C = BI->getCondition(); 5252 5253 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5254 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5255 5256 if (!LeftEdge.isSingleEdge()) 5257 return false; 5258 5259 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5260 5261 Use &LeftUse = Merge->getOperandUse(0); 5262 Use &RightUse = Merge->getOperandUse(1); 5263 5264 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5265 LHS = LeftUse; 5266 RHS = RightUse; 5267 return true; 5268 } 5269 5270 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5271 LHS = RightUse; 5272 RHS = LeftUse; 5273 return true; 5274 } 5275 5276 return false; 5277 } 5278 5279 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5280 auto IsReachable = 5281 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5282 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5283 const Loop *L = LI.getLoopFor(PN->getParent()); 5284 5285 // We don't want to break LCSSA, even in a SCEV expression tree. 5286 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5287 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5288 return nullptr; 5289 5290 // Try to match 5291 // 5292 // br %cond, label %left, label %right 5293 // left: 5294 // br label %merge 5295 // right: 5296 // br label %merge 5297 // merge: 5298 // V = phi [ %x, %left ], [ %y, %right ] 5299 // 5300 // as "select %cond, %x, %y" 5301 5302 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5303 assert(IDom && "At least the entry block should dominate PN"); 5304 5305 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5306 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5307 5308 if (BI && BI->isConditional() && 5309 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5310 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5311 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5312 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5313 } 5314 5315 return nullptr; 5316 } 5317 5318 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5319 if (const SCEV *S = createAddRecFromPHI(PN)) 5320 return S; 5321 5322 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5323 return S; 5324 5325 // If the PHI has a single incoming value, follow that value, unless the 5326 // PHI's incoming blocks are in a different loop, in which case doing so 5327 // risks breaking LCSSA form. Instcombine would normally zap these, but 5328 // it doesn't have DominatorTree information, so it may miss cases. 5329 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5330 if (LI.replacementPreservesLCSSAForm(PN, V)) 5331 return getSCEV(V); 5332 5333 // If it's not a loop phi, we can't handle it yet. 5334 return getUnknown(PN); 5335 } 5336 5337 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5338 Value *Cond, 5339 Value *TrueVal, 5340 Value *FalseVal) { 5341 // Handle "constant" branch or select. This can occur for instance when a 5342 // loop pass transforms an inner loop and moves on to process the outer loop. 5343 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5344 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5345 5346 // Try to match some simple smax or umax patterns. 5347 auto *ICI = dyn_cast<ICmpInst>(Cond); 5348 if (!ICI) 5349 return getUnknown(I); 5350 5351 Value *LHS = ICI->getOperand(0); 5352 Value *RHS = ICI->getOperand(1); 5353 5354 switch (ICI->getPredicate()) { 5355 case ICmpInst::ICMP_SLT: 5356 case ICmpInst::ICMP_SLE: 5357 std::swap(LHS, RHS); 5358 LLVM_FALLTHROUGH; 5359 case ICmpInst::ICMP_SGT: 5360 case ICmpInst::ICMP_SGE: 5361 // a >s b ? a+x : b+x -> smax(a, b)+x 5362 // a >s b ? b+x : a+x -> smin(a, b)+x 5363 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5364 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5365 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5366 const SCEV *LA = getSCEV(TrueVal); 5367 const SCEV *RA = getSCEV(FalseVal); 5368 const SCEV *LDiff = getMinusSCEV(LA, LS); 5369 const SCEV *RDiff = getMinusSCEV(RA, RS); 5370 if (LDiff == RDiff) 5371 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5372 LDiff = getMinusSCEV(LA, RS); 5373 RDiff = getMinusSCEV(RA, LS); 5374 if (LDiff == RDiff) 5375 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5376 } 5377 break; 5378 case ICmpInst::ICMP_ULT: 5379 case ICmpInst::ICMP_ULE: 5380 std::swap(LHS, RHS); 5381 LLVM_FALLTHROUGH; 5382 case ICmpInst::ICMP_UGT: 5383 case ICmpInst::ICMP_UGE: 5384 // a >u b ? a+x : b+x -> umax(a, b)+x 5385 // a >u b ? b+x : a+x -> umin(a, b)+x 5386 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5387 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5388 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5389 const SCEV *LA = getSCEV(TrueVal); 5390 const SCEV *RA = getSCEV(FalseVal); 5391 const SCEV *LDiff = getMinusSCEV(LA, LS); 5392 const SCEV *RDiff = getMinusSCEV(RA, RS); 5393 if (LDiff == RDiff) 5394 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5395 LDiff = getMinusSCEV(LA, RS); 5396 RDiff = getMinusSCEV(RA, LS); 5397 if (LDiff == RDiff) 5398 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5399 } 5400 break; 5401 case ICmpInst::ICMP_NE: 5402 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5403 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5404 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5405 const SCEV *One = getOne(I->getType()); 5406 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5407 const SCEV *LA = getSCEV(TrueVal); 5408 const SCEV *RA = getSCEV(FalseVal); 5409 const SCEV *LDiff = getMinusSCEV(LA, LS); 5410 const SCEV *RDiff = getMinusSCEV(RA, One); 5411 if (LDiff == RDiff) 5412 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5413 } 5414 break; 5415 case ICmpInst::ICMP_EQ: 5416 // n == 0 ? 1+x : n+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, One); 5424 const SCEV *RDiff = getMinusSCEV(RA, LS); 5425 if (LDiff == RDiff) 5426 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5427 } 5428 break; 5429 default: 5430 break; 5431 } 5432 5433 return getUnknown(I); 5434 } 5435 5436 /// Expand GEP instructions into add and multiply operations. This allows them 5437 /// to be analyzed by regular SCEV code. 5438 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5439 // Don't attempt to analyze GEPs over unsized objects. 5440 if (!GEP->getSourceElementType()->isSized()) 5441 return getUnknown(GEP); 5442 5443 SmallVector<const SCEV *, 4> IndexExprs; 5444 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5445 IndexExprs.push_back(getSCEV(*Index)); 5446 return getGEPExpr(GEP, IndexExprs); 5447 } 5448 5449 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5450 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5451 return C->getAPInt().countTrailingZeros(); 5452 5453 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5454 return std::min(GetMinTrailingZeros(T->getOperand()), 5455 (uint32_t)getTypeSizeInBits(T->getType())); 5456 5457 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5458 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5459 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5460 ? getTypeSizeInBits(E->getType()) 5461 : OpRes; 5462 } 5463 5464 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5465 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5466 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5467 ? getTypeSizeInBits(E->getType()) 5468 : OpRes; 5469 } 5470 5471 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5472 // The result is the min of all operands results. 5473 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5474 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5475 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5476 return MinOpRes; 5477 } 5478 5479 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5480 // The result is the sum of all operands results. 5481 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5482 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5483 for (unsigned i = 1, e = M->getNumOperands(); 5484 SumOpRes != BitWidth && i != e; ++i) 5485 SumOpRes = 5486 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5487 return SumOpRes; 5488 } 5489 5490 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5491 // The result is the min of all operands results. 5492 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5493 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5494 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5495 return MinOpRes; 5496 } 5497 5498 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5499 // The result is the min of all operands results. 5500 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5501 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5502 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5503 return MinOpRes; 5504 } 5505 5506 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5507 // The result is the min of all operands results. 5508 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5509 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5510 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5511 return MinOpRes; 5512 } 5513 5514 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5515 // For a SCEVUnknown, ask ValueTracking. 5516 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5517 return Known.countMinTrailingZeros(); 5518 } 5519 5520 // SCEVUDivExpr 5521 return 0; 5522 } 5523 5524 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5525 auto I = MinTrailingZerosCache.find(S); 5526 if (I != MinTrailingZerosCache.end()) 5527 return I->second; 5528 5529 uint32_t Result = GetMinTrailingZerosImpl(S); 5530 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5531 assert(InsertPair.second && "Should insert a new key"); 5532 return InsertPair.first->second; 5533 } 5534 5535 /// Helper method to assign a range to V from metadata present in the IR. 5536 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5537 if (Instruction *I = dyn_cast<Instruction>(V)) 5538 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5539 return getConstantRangeFromMetadata(*MD); 5540 5541 return None; 5542 } 5543 5544 /// Determine the range for a particular SCEV. If SignHint is 5545 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5546 /// with a "cleaner" unsigned (resp. signed) representation. 5547 const ConstantRange & 5548 ScalarEvolution::getRangeRef(const SCEV *S, 5549 ScalarEvolution::RangeSignHint SignHint) { 5550 DenseMap<const SCEV *, ConstantRange> &Cache = 5551 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5552 : SignedRanges; 5553 5554 // See if we've computed this range already. 5555 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5556 if (I != Cache.end()) 5557 return I->second; 5558 5559 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5560 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5561 5562 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5563 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5564 5565 // If the value has known zeros, the maximum value will have those known zeros 5566 // as well. 5567 uint32_t TZ = GetMinTrailingZeros(S); 5568 if (TZ != 0) { 5569 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5570 ConservativeResult = 5571 ConstantRange(APInt::getMinValue(BitWidth), 5572 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5573 else 5574 ConservativeResult = ConstantRange( 5575 APInt::getSignedMinValue(BitWidth), 5576 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5577 } 5578 5579 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5580 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5581 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5582 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5583 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 5584 } 5585 5586 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5587 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5588 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5589 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5590 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 5591 } 5592 5593 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5594 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5595 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5596 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5597 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 5598 } 5599 5600 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5601 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5602 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5603 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5604 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 5605 } 5606 5607 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5608 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5609 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5610 return setRange(UDiv, SignHint, 5611 ConservativeResult.intersectWith(X.udiv(Y))); 5612 } 5613 5614 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5615 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5616 return setRange(ZExt, SignHint, 5617 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 5618 } 5619 5620 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5621 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5622 return setRange(SExt, SignHint, 5623 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 5624 } 5625 5626 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5627 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5628 return setRange(Trunc, SignHint, 5629 ConservativeResult.intersectWith(X.truncate(BitWidth))); 5630 } 5631 5632 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5633 // If there's no unsigned wrap, the value will never be less than its 5634 // initial value. 5635 if (AddRec->hasNoUnsignedWrap()) 5636 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5637 if (!C->getValue()->isZero()) 5638 ConservativeResult = ConservativeResult.intersectWith( 5639 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 5640 5641 // If there's no signed wrap, and all the operands have the same sign or 5642 // zero, the value won't ever change sign. 5643 if (AddRec->hasNoSignedWrap()) { 5644 bool AllNonNeg = true; 5645 bool AllNonPos = true; 5646 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5647 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5648 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5649 } 5650 if (AllNonNeg) 5651 ConservativeResult = ConservativeResult.intersectWith( 5652 ConstantRange(APInt(BitWidth, 0), 5653 APInt::getSignedMinValue(BitWidth))); 5654 else if (AllNonPos) 5655 ConservativeResult = ConservativeResult.intersectWith( 5656 ConstantRange(APInt::getSignedMinValue(BitWidth), 5657 APInt(BitWidth, 1))); 5658 } 5659 5660 // TODO: non-affine addrec 5661 if (AddRec->isAffine()) { 5662 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 5663 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5664 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5665 auto RangeFromAffine = getRangeForAffineAR( 5666 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5667 BitWidth); 5668 if (!RangeFromAffine.isFullSet()) 5669 ConservativeResult = 5670 ConservativeResult.intersectWith(RangeFromAffine); 5671 5672 auto RangeFromFactoring = getRangeViaFactoring( 5673 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5674 BitWidth); 5675 if (!RangeFromFactoring.isFullSet()) 5676 ConservativeResult = 5677 ConservativeResult.intersectWith(RangeFromFactoring); 5678 } 5679 } 5680 5681 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5682 } 5683 5684 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5685 // Check if the IR explicitly contains !range metadata. 5686 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5687 if (MDRange.hasValue()) 5688 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 5689 5690 // Split here to avoid paying the compile-time cost of calling both 5691 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5692 // if needed. 5693 const DataLayout &DL = getDataLayout(); 5694 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5695 // For a SCEVUnknown, ask ValueTracking. 5696 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5697 if (Known.One != ~Known.Zero + 1) 5698 ConservativeResult = 5699 ConservativeResult.intersectWith(ConstantRange(Known.One, 5700 ~Known.Zero + 1)); 5701 } else { 5702 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5703 "generalize as needed!"); 5704 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5705 if (NS > 1) 5706 ConservativeResult = ConservativeResult.intersectWith( 5707 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5708 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 5709 } 5710 5711 // A range of Phi is a subset of union of all ranges of its input. 5712 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5713 // Make sure that we do not run over cycled Phis. 5714 if (PendingPhiRanges.insert(Phi).second) { 5715 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5716 for (auto &Op : Phi->operands()) { 5717 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5718 RangeFromOps = RangeFromOps.unionWith(OpRange); 5719 // No point to continue if we already have a full set. 5720 if (RangeFromOps.isFullSet()) 5721 break; 5722 } 5723 ConservativeResult = ConservativeResult.intersectWith(RangeFromOps); 5724 bool Erased = PendingPhiRanges.erase(Phi); 5725 assert(Erased && "Failed to erase Phi properly?"); 5726 (void) Erased; 5727 } 5728 } 5729 5730 return setRange(U, SignHint, std::move(ConservativeResult)); 5731 } 5732 5733 return setRange(S, SignHint, std::move(ConservativeResult)); 5734 } 5735 5736 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5737 // values that the expression can take. Initially, the expression has a value 5738 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5739 // argument defines if we treat Step as signed or unsigned. 5740 static ConstantRange getRangeForAffineARHelper(APInt Step, 5741 const ConstantRange &StartRange, 5742 const APInt &MaxBECount, 5743 unsigned BitWidth, bool Signed) { 5744 // If either Step or MaxBECount is 0, then the expression won't change, and we 5745 // just need to return the initial range. 5746 if (Step == 0 || MaxBECount == 0) 5747 return StartRange; 5748 5749 // If we don't know anything about the initial value (i.e. StartRange is 5750 // FullRange), then we don't know anything about the final range either. 5751 // Return FullRange. 5752 if (StartRange.isFullSet()) 5753 return ConstantRange(BitWidth, /* isFullSet = */ true); 5754 5755 // If Step is signed and negative, then we use its absolute value, but we also 5756 // note that we're moving in the opposite direction. 5757 bool Descending = Signed && Step.isNegative(); 5758 5759 if (Signed) 5760 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5761 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5762 // This equations hold true due to the well-defined wrap-around behavior of 5763 // APInt. 5764 Step = Step.abs(); 5765 5766 // Check if Offset is more than full span of BitWidth. If it is, the 5767 // expression is guaranteed to overflow. 5768 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5769 return ConstantRange(BitWidth, /* isFullSet = */ true); 5770 5771 // Offset is by how much the expression can change. Checks above guarantee no 5772 // overflow here. 5773 APInt Offset = Step * MaxBECount; 5774 5775 // Minimum value of the final range will match the minimal value of StartRange 5776 // if the expression is increasing and will be decreased by Offset otherwise. 5777 // Maximum value of the final range will match the maximal value of StartRange 5778 // if the expression is decreasing and will be increased by Offset otherwise. 5779 APInt StartLower = StartRange.getLower(); 5780 APInt StartUpper = StartRange.getUpper() - 1; 5781 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5782 : (StartUpper + std::move(Offset)); 5783 5784 // It's possible that the new minimum/maximum value will fall into the initial 5785 // range (due to wrap around). This means that the expression can take any 5786 // value in this bitwidth, and we have to return full range. 5787 if (StartRange.contains(MovedBoundary)) 5788 return ConstantRange(BitWidth, /* isFullSet = */ true); 5789 5790 APInt NewLower = 5791 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5792 APInt NewUpper = 5793 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5794 NewUpper += 1; 5795 5796 // If we end up with full range, return a proper full range. 5797 if (NewLower == NewUpper) 5798 return ConstantRange(BitWidth, /* isFullSet = */ true); 5799 5800 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5801 return ConstantRange(std::move(NewLower), std::move(NewUpper)); 5802 } 5803 5804 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5805 const SCEV *Step, 5806 const SCEV *MaxBECount, 5807 unsigned BitWidth) { 5808 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5809 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5810 "Precondition!"); 5811 5812 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5813 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5814 5815 // First, consider step signed. 5816 ConstantRange StartSRange = getSignedRange(Start); 5817 ConstantRange StepSRange = getSignedRange(Step); 5818 5819 // If Step can be both positive and negative, we need to find ranges for the 5820 // maximum absolute step values in both directions and union them. 5821 ConstantRange SR = 5822 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5823 MaxBECountValue, BitWidth, /* Signed = */ true); 5824 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5825 StartSRange, MaxBECountValue, 5826 BitWidth, /* Signed = */ true)); 5827 5828 // Next, consider step unsigned. 5829 ConstantRange UR = getRangeForAffineARHelper( 5830 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5831 MaxBECountValue, BitWidth, /* Signed = */ false); 5832 5833 // Finally, intersect signed and unsigned ranges. 5834 return SR.intersectWith(UR); 5835 } 5836 5837 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5838 const SCEV *Step, 5839 const SCEV *MaxBECount, 5840 unsigned BitWidth) { 5841 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5842 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5843 5844 struct SelectPattern { 5845 Value *Condition = nullptr; 5846 APInt TrueValue; 5847 APInt FalseValue; 5848 5849 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5850 const SCEV *S) { 5851 Optional<unsigned> CastOp; 5852 APInt Offset(BitWidth, 0); 5853 5854 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5855 "Should be!"); 5856 5857 // Peel off a constant offset: 5858 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5859 // In the future we could consider being smarter here and handle 5860 // {Start+Step,+,Step} too. 5861 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5862 return; 5863 5864 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5865 S = SA->getOperand(1); 5866 } 5867 5868 // Peel off a cast operation 5869 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5870 CastOp = SCast->getSCEVType(); 5871 S = SCast->getOperand(); 5872 } 5873 5874 using namespace llvm::PatternMatch; 5875 5876 auto *SU = dyn_cast<SCEVUnknown>(S); 5877 const APInt *TrueVal, *FalseVal; 5878 if (!SU || 5879 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5880 m_APInt(FalseVal)))) { 5881 Condition = nullptr; 5882 return; 5883 } 5884 5885 TrueValue = *TrueVal; 5886 FalseValue = *FalseVal; 5887 5888 // Re-apply the cast we peeled off earlier 5889 if (CastOp.hasValue()) 5890 switch (*CastOp) { 5891 default: 5892 llvm_unreachable("Unknown SCEV cast type!"); 5893 5894 case scTruncate: 5895 TrueValue = TrueValue.trunc(BitWidth); 5896 FalseValue = FalseValue.trunc(BitWidth); 5897 break; 5898 case scZeroExtend: 5899 TrueValue = TrueValue.zext(BitWidth); 5900 FalseValue = FalseValue.zext(BitWidth); 5901 break; 5902 case scSignExtend: 5903 TrueValue = TrueValue.sext(BitWidth); 5904 FalseValue = FalseValue.sext(BitWidth); 5905 break; 5906 } 5907 5908 // Re-apply the constant offset we peeled off earlier 5909 TrueValue += Offset; 5910 FalseValue += Offset; 5911 } 5912 5913 bool isRecognized() { return Condition != nullptr; } 5914 }; 5915 5916 SelectPattern StartPattern(*this, BitWidth, Start); 5917 if (!StartPattern.isRecognized()) 5918 return ConstantRange(BitWidth, /* isFullSet = */ true); 5919 5920 SelectPattern StepPattern(*this, BitWidth, Step); 5921 if (!StepPattern.isRecognized()) 5922 return ConstantRange(BitWidth, /* isFullSet = */ true); 5923 5924 if (StartPattern.Condition != StepPattern.Condition) { 5925 // We don't handle this case today; but we could, by considering four 5926 // possibilities below instead of two. I'm not sure if there are cases where 5927 // that will help over what getRange already does, though. 5928 return ConstantRange(BitWidth, /* isFullSet = */ true); 5929 } 5930 5931 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5932 // construct arbitrary general SCEV expressions here. This function is called 5933 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5934 // say) can end up caching a suboptimal value. 5935 5936 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5937 // C2352 and C2512 (otherwise it isn't needed). 5938 5939 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5940 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5941 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5942 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5943 5944 ConstantRange TrueRange = 5945 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5946 ConstantRange FalseRange = 5947 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5948 5949 return TrueRange.unionWith(FalseRange); 5950 } 5951 5952 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5953 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5954 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5955 5956 // Return early if there are no flags to propagate to the SCEV. 5957 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5958 if (BinOp->hasNoUnsignedWrap()) 5959 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5960 if (BinOp->hasNoSignedWrap()) 5961 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5962 if (Flags == SCEV::FlagAnyWrap) 5963 return SCEV::FlagAnyWrap; 5964 5965 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5966 } 5967 5968 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5969 // Here we check that I is in the header of the innermost loop containing I, 5970 // since we only deal with instructions in the loop header. The actual loop we 5971 // need to check later will come from an add recurrence, but getting that 5972 // requires computing the SCEV of the operands, which can be expensive. This 5973 // check we can do cheaply to rule out some cases early. 5974 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5975 if (InnermostContainingLoop == nullptr || 5976 InnermostContainingLoop->getHeader() != I->getParent()) 5977 return false; 5978 5979 // Only proceed if we can prove that I does not yield poison. 5980 if (!programUndefinedIfFullPoison(I)) 5981 return false; 5982 5983 // At this point we know that if I is executed, then it does not wrap 5984 // according to at least one of NSW or NUW. If I is not executed, then we do 5985 // not know if the calculation that I represents would wrap. Multiple 5986 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5987 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5988 // derived from other instructions that map to the same SCEV. We cannot make 5989 // that guarantee for cases where I is not executed. So we need to find the 5990 // loop that I is considered in relation to and prove that I is executed for 5991 // every iteration of that loop. That implies that the value that I 5992 // calculates does not wrap anywhere in the loop, so then we can apply the 5993 // flags to the SCEV. 5994 // 5995 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5996 // from different loops, so that we know which loop to prove that I is 5997 // executed in. 5998 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5999 // I could be an extractvalue from a call to an overflow intrinsic. 6000 // TODO: We can do better here in some cases. 6001 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6002 return false; 6003 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6004 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6005 bool AllOtherOpsLoopInvariant = true; 6006 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6007 ++OtherOpIndex) { 6008 if (OtherOpIndex != OpIndex) { 6009 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6010 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6011 AllOtherOpsLoopInvariant = false; 6012 break; 6013 } 6014 } 6015 } 6016 if (AllOtherOpsLoopInvariant && 6017 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6018 return true; 6019 } 6020 } 6021 return false; 6022 } 6023 6024 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6025 // If we know that \c I can never be poison period, then that's enough. 6026 if (isSCEVExprNeverPoison(I)) 6027 return true; 6028 6029 // For an add recurrence specifically, we assume that infinite loops without 6030 // side effects are undefined behavior, and then reason as follows: 6031 // 6032 // If the add recurrence is poison in any iteration, it is poison on all 6033 // future iterations (since incrementing poison yields poison). If the result 6034 // of the add recurrence is fed into the loop latch condition and the loop 6035 // does not contain any throws or exiting blocks other than the latch, we now 6036 // have the ability to "choose" whether the backedge is taken or not (by 6037 // choosing a sufficiently evil value for the poison feeding into the branch) 6038 // for every iteration including and after the one in which \p I first became 6039 // poison. There are two possibilities (let's call the iteration in which \p 6040 // I first became poison as K): 6041 // 6042 // 1. In the set of iterations including and after K, the loop body executes 6043 // no side effects. In this case executing the backege an infinte number 6044 // of times will yield undefined behavior. 6045 // 6046 // 2. In the set of iterations including and after K, the loop body executes 6047 // at least one side effect. In this case, that specific instance of side 6048 // effect is control dependent on poison, which also yields undefined 6049 // behavior. 6050 6051 auto *ExitingBB = L->getExitingBlock(); 6052 auto *LatchBB = L->getLoopLatch(); 6053 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6054 return false; 6055 6056 SmallPtrSet<const Instruction *, 16> Pushed; 6057 SmallVector<const Instruction *, 8> PoisonStack; 6058 6059 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6060 // things that are known to be fully poison under that assumption go on the 6061 // PoisonStack. 6062 Pushed.insert(I); 6063 PoisonStack.push_back(I); 6064 6065 bool LatchControlDependentOnPoison = false; 6066 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6067 const Instruction *Poison = PoisonStack.pop_back_val(); 6068 6069 for (auto *PoisonUser : Poison->users()) { 6070 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 6071 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6072 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6073 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6074 assert(BI->isConditional() && "Only possibility!"); 6075 if (BI->getParent() == LatchBB) { 6076 LatchControlDependentOnPoison = true; 6077 break; 6078 } 6079 } 6080 } 6081 } 6082 6083 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6084 } 6085 6086 ScalarEvolution::LoopProperties 6087 ScalarEvolution::getLoopProperties(const Loop *L) { 6088 using LoopProperties = ScalarEvolution::LoopProperties; 6089 6090 auto Itr = LoopPropertiesCache.find(L); 6091 if (Itr == LoopPropertiesCache.end()) { 6092 auto HasSideEffects = [](Instruction *I) { 6093 if (auto *SI = dyn_cast<StoreInst>(I)) 6094 return !SI->isSimple(); 6095 6096 return I->mayHaveSideEffects(); 6097 }; 6098 6099 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6100 /*HasNoSideEffects*/ true}; 6101 6102 for (auto *BB : L->getBlocks()) 6103 for (auto &I : *BB) { 6104 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6105 LP.HasNoAbnormalExits = false; 6106 if (HasSideEffects(&I)) 6107 LP.HasNoSideEffects = false; 6108 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6109 break; // We're already as pessimistic as we can get. 6110 } 6111 6112 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6113 assert(InsertPair.second && "We just checked!"); 6114 Itr = InsertPair.first; 6115 } 6116 6117 return Itr->second; 6118 } 6119 6120 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6121 if (!isSCEVable(V->getType())) 6122 return getUnknown(V); 6123 6124 if (Instruction *I = dyn_cast<Instruction>(V)) { 6125 // Don't attempt to analyze instructions in blocks that aren't 6126 // reachable. Such instructions don't matter, and they aren't required 6127 // to obey basic rules for definitions dominating uses which this 6128 // analysis depends on. 6129 if (!DT.isReachableFromEntry(I->getParent())) 6130 return getUnknown(V); 6131 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6132 return getConstant(CI); 6133 else if (isa<ConstantPointerNull>(V)) 6134 return getZero(V->getType()); 6135 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6136 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6137 else if (!isa<ConstantExpr>(V)) 6138 return getUnknown(V); 6139 6140 Operator *U = cast<Operator>(V); 6141 if (auto BO = MatchBinaryOp(U, DT)) { 6142 switch (BO->Opcode) { 6143 case Instruction::Add: { 6144 // The simple thing to do would be to just call getSCEV on both operands 6145 // and call getAddExpr with the result. However if we're looking at a 6146 // bunch of things all added together, this can be quite inefficient, 6147 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6148 // Instead, gather up all the operands and make a single getAddExpr call. 6149 // LLVM IR canonical form means we need only traverse the left operands. 6150 SmallVector<const SCEV *, 4> AddOps; 6151 do { 6152 if (BO->Op) { 6153 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6154 AddOps.push_back(OpSCEV); 6155 break; 6156 } 6157 6158 // If a NUW or NSW flag can be applied to the SCEV for this 6159 // addition, then compute the SCEV for this addition by itself 6160 // with a separate call to getAddExpr. We need to do that 6161 // instead of pushing the operands of the addition onto AddOps, 6162 // since the flags are only known to apply to this particular 6163 // addition - they may not apply to other additions that can be 6164 // formed with operands from AddOps. 6165 const SCEV *RHS = getSCEV(BO->RHS); 6166 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6167 if (Flags != SCEV::FlagAnyWrap) { 6168 const SCEV *LHS = getSCEV(BO->LHS); 6169 if (BO->Opcode == Instruction::Sub) 6170 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6171 else 6172 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6173 break; 6174 } 6175 } 6176 6177 if (BO->Opcode == Instruction::Sub) 6178 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6179 else 6180 AddOps.push_back(getSCEV(BO->RHS)); 6181 6182 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6183 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6184 NewBO->Opcode != Instruction::Sub)) { 6185 AddOps.push_back(getSCEV(BO->LHS)); 6186 break; 6187 } 6188 BO = NewBO; 6189 } while (true); 6190 6191 return getAddExpr(AddOps); 6192 } 6193 6194 case Instruction::Mul: { 6195 SmallVector<const SCEV *, 4> MulOps; 6196 do { 6197 if (BO->Op) { 6198 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6199 MulOps.push_back(OpSCEV); 6200 break; 6201 } 6202 6203 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6204 if (Flags != SCEV::FlagAnyWrap) { 6205 MulOps.push_back( 6206 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6207 break; 6208 } 6209 } 6210 6211 MulOps.push_back(getSCEV(BO->RHS)); 6212 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6213 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6214 MulOps.push_back(getSCEV(BO->LHS)); 6215 break; 6216 } 6217 BO = NewBO; 6218 } while (true); 6219 6220 return getMulExpr(MulOps); 6221 } 6222 case Instruction::UDiv: 6223 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6224 case Instruction::URem: 6225 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6226 case Instruction::Sub: { 6227 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6228 if (BO->Op) 6229 Flags = getNoWrapFlagsFromUB(BO->Op); 6230 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6231 } 6232 case Instruction::And: 6233 // For an expression like x&255 that merely masks off the high bits, 6234 // use zext(trunc(x)) as the SCEV expression. 6235 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6236 if (CI->isZero()) 6237 return getSCEV(BO->RHS); 6238 if (CI->isMinusOne()) 6239 return getSCEV(BO->LHS); 6240 const APInt &A = CI->getValue(); 6241 6242 // Instcombine's ShrinkDemandedConstant may strip bits out of 6243 // constants, obscuring what would otherwise be a low-bits mask. 6244 // Use computeKnownBits to compute what ShrinkDemandedConstant 6245 // knew about to reconstruct a low-bits mask value. 6246 unsigned LZ = A.countLeadingZeros(); 6247 unsigned TZ = A.countTrailingZeros(); 6248 unsigned BitWidth = A.getBitWidth(); 6249 KnownBits Known(BitWidth); 6250 computeKnownBits(BO->LHS, Known, getDataLayout(), 6251 0, &AC, nullptr, &DT); 6252 6253 APInt EffectiveMask = 6254 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6255 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6256 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6257 const SCEV *LHS = getSCEV(BO->LHS); 6258 const SCEV *ShiftedLHS = nullptr; 6259 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6260 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6261 // For an expression like (x * 8) & 8, simplify the multiply. 6262 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6263 unsigned GCD = std::min(MulZeros, TZ); 6264 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6265 SmallVector<const SCEV*, 4> MulOps; 6266 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6267 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6268 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6269 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6270 } 6271 } 6272 if (!ShiftedLHS) 6273 ShiftedLHS = getUDivExpr(LHS, MulCount); 6274 return getMulExpr( 6275 getZeroExtendExpr( 6276 getTruncateExpr(ShiftedLHS, 6277 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6278 BO->LHS->getType()), 6279 MulCount); 6280 } 6281 } 6282 break; 6283 6284 case Instruction::Or: 6285 // If the RHS of the Or is a constant, we may have something like: 6286 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6287 // optimizations will transparently handle this case. 6288 // 6289 // In order for this transformation to be safe, the LHS must be of the 6290 // form X*(2^n) and the Or constant must be less than 2^n. 6291 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6292 const SCEV *LHS = getSCEV(BO->LHS); 6293 const APInt &CIVal = CI->getValue(); 6294 if (GetMinTrailingZeros(LHS) >= 6295 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6296 // Build a plain add SCEV. 6297 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6298 // If the LHS of the add was an addrec and it has no-wrap flags, 6299 // transfer the no-wrap flags, since an or won't introduce a wrap. 6300 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6301 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6302 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6303 OldAR->getNoWrapFlags()); 6304 } 6305 return S; 6306 } 6307 } 6308 break; 6309 6310 case Instruction::Xor: 6311 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6312 // If the RHS of xor is -1, then this is a not operation. 6313 if (CI->isMinusOne()) 6314 return getNotSCEV(getSCEV(BO->LHS)); 6315 6316 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6317 // This is a variant of the check for xor with -1, and it handles 6318 // the case where instcombine has trimmed non-demanded bits out 6319 // of an xor with -1. 6320 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6321 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6322 if (LBO->getOpcode() == Instruction::And && 6323 LCI->getValue() == CI->getValue()) 6324 if (const SCEVZeroExtendExpr *Z = 6325 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6326 Type *UTy = BO->LHS->getType(); 6327 const SCEV *Z0 = Z->getOperand(); 6328 Type *Z0Ty = Z0->getType(); 6329 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6330 6331 // If C is a low-bits mask, the zero extend is serving to 6332 // mask off the high bits. Complement the operand and 6333 // re-apply the zext. 6334 if (CI->getValue().isMask(Z0TySize)) 6335 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6336 6337 // If C is a single bit, it may be in the sign-bit position 6338 // before the zero-extend. In this case, represent the xor 6339 // using an add, which is equivalent, and re-apply the zext. 6340 APInt Trunc = CI->getValue().trunc(Z0TySize); 6341 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6342 Trunc.isSignMask()) 6343 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6344 UTy); 6345 } 6346 } 6347 break; 6348 6349 case Instruction::Shl: 6350 // Turn shift left of a constant amount into a multiply. 6351 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6352 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6353 6354 // If the shift count is not less than the bitwidth, the result of 6355 // the shift is undefined. Don't try to analyze it, because the 6356 // resolution chosen here may differ from the resolution chosen in 6357 // other parts of the compiler. 6358 if (SA->getValue().uge(BitWidth)) 6359 break; 6360 6361 // It is currently not resolved how to interpret NSW for left 6362 // shift by BitWidth - 1, so we avoid applying flags in that 6363 // case. Remove this check (or this comment) once the situation 6364 // is resolved. See 6365 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6366 // and http://reviews.llvm.org/D8890 . 6367 auto Flags = SCEV::FlagAnyWrap; 6368 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6369 Flags = getNoWrapFlagsFromUB(BO->Op); 6370 6371 Constant *X = ConstantInt::get( 6372 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6373 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6374 } 6375 break; 6376 6377 case Instruction::AShr: { 6378 // AShr X, C, where C is a constant. 6379 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6380 if (!CI) 6381 break; 6382 6383 Type *OuterTy = BO->LHS->getType(); 6384 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6385 // If the shift count is not less than the bitwidth, the result of 6386 // the shift is undefined. Don't try to analyze it, because the 6387 // resolution chosen here may differ from the resolution chosen in 6388 // other parts of the compiler. 6389 if (CI->getValue().uge(BitWidth)) 6390 break; 6391 6392 if (CI->isZero()) 6393 return getSCEV(BO->LHS); // shift by zero --> noop 6394 6395 uint64_t AShrAmt = CI->getZExtValue(); 6396 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6397 6398 Operator *L = dyn_cast<Operator>(BO->LHS); 6399 if (L && L->getOpcode() == Instruction::Shl) { 6400 // X = Shl A, n 6401 // Y = AShr X, m 6402 // Both n and m are constant. 6403 6404 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6405 if (L->getOperand(1) == BO->RHS) 6406 // For a two-shift sext-inreg, i.e. n = m, 6407 // use sext(trunc(x)) as the SCEV expression. 6408 return getSignExtendExpr( 6409 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6410 6411 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6412 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6413 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6414 if (ShlAmt > AShrAmt) { 6415 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6416 // expression. We already checked that ShlAmt < BitWidth, so 6417 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6418 // ShlAmt - AShrAmt < Amt. 6419 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6420 ShlAmt - AShrAmt); 6421 return getSignExtendExpr( 6422 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6423 getConstant(Mul)), OuterTy); 6424 } 6425 } 6426 } 6427 break; 6428 } 6429 } 6430 } 6431 6432 switch (U->getOpcode()) { 6433 case Instruction::Trunc: 6434 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6435 6436 case Instruction::ZExt: 6437 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6438 6439 case Instruction::SExt: 6440 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6441 // The NSW flag of a subtract does not always survive the conversion to 6442 // A + (-1)*B. By pushing sign extension onto its operands we are much 6443 // more likely to preserve NSW and allow later AddRec optimisations. 6444 // 6445 // NOTE: This is effectively duplicating this logic from getSignExtend: 6446 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6447 // but by that point the NSW information has potentially been lost. 6448 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6449 Type *Ty = U->getType(); 6450 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6451 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6452 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6453 } 6454 } 6455 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6456 6457 case Instruction::BitCast: 6458 // BitCasts are no-op casts so we just eliminate the cast. 6459 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6460 return getSCEV(U->getOperand(0)); 6461 break; 6462 6463 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6464 // lead to pointer expressions which cannot safely be expanded to GEPs, 6465 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6466 // simplifying integer expressions. 6467 6468 case Instruction::GetElementPtr: 6469 return createNodeForGEP(cast<GEPOperator>(U)); 6470 6471 case Instruction::PHI: 6472 return createNodeForPHI(cast<PHINode>(U)); 6473 6474 case Instruction::Select: 6475 // U can also be a select constant expr, which let fall through. Since 6476 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6477 // constant expressions cannot have instructions as operands, we'd have 6478 // returned getUnknown for a select constant expressions anyway. 6479 if (isa<Instruction>(U)) 6480 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6481 U->getOperand(1), U->getOperand(2)); 6482 break; 6483 6484 case Instruction::Call: 6485 case Instruction::Invoke: 6486 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6487 return getSCEV(RV); 6488 break; 6489 } 6490 6491 return getUnknown(V); 6492 } 6493 6494 //===----------------------------------------------------------------------===// 6495 // Iteration Count Computation Code 6496 // 6497 6498 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6499 if (!ExitCount) 6500 return 0; 6501 6502 ConstantInt *ExitConst = ExitCount->getValue(); 6503 6504 // Guard against huge trip counts. 6505 if (ExitConst->getValue().getActiveBits() > 32) 6506 return 0; 6507 6508 // In case of integer overflow, this returns 0, which is correct. 6509 return ((unsigned)ExitConst->getZExtValue()) + 1; 6510 } 6511 6512 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6513 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6514 return getSmallConstantTripCount(L, ExitingBB); 6515 6516 // No trip count information for multiple exits. 6517 return 0; 6518 } 6519 6520 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6521 BasicBlock *ExitingBlock) { 6522 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6523 assert(L->isLoopExiting(ExitingBlock) && 6524 "Exiting block must actually branch out of the loop!"); 6525 const SCEVConstant *ExitCount = 6526 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6527 return getConstantTripCount(ExitCount); 6528 } 6529 6530 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6531 const auto *MaxExitCount = 6532 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 6533 return getConstantTripCount(MaxExitCount); 6534 } 6535 6536 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6537 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6538 return getSmallConstantTripMultiple(L, ExitingBB); 6539 6540 // No trip multiple information for multiple exits. 6541 return 0; 6542 } 6543 6544 /// Returns the largest constant divisor of the trip count of this loop as a 6545 /// normal unsigned value, if possible. This means that the actual trip count is 6546 /// always a multiple of the returned value (don't forget the trip count could 6547 /// very well be zero as well!). 6548 /// 6549 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6550 /// multiple of a constant (which is also the case if the trip count is simply 6551 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6552 /// if the trip count is very large (>= 2^32). 6553 /// 6554 /// As explained in the comments for getSmallConstantTripCount, this assumes 6555 /// that control exits the loop via ExitingBlock. 6556 unsigned 6557 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6558 BasicBlock *ExitingBlock) { 6559 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6560 assert(L->isLoopExiting(ExitingBlock) && 6561 "Exiting block must actually branch out of the loop!"); 6562 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6563 if (ExitCount == getCouldNotCompute()) 6564 return 1; 6565 6566 // Get the trip count from the BE count by adding 1. 6567 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6568 6569 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6570 if (!TC) 6571 // Attempt to factor more general cases. Returns the greatest power of 6572 // two divisor. If overflow happens, the trip count expression is still 6573 // divisible by the greatest power of 2 divisor returned. 6574 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6575 6576 ConstantInt *Result = TC->getValue(); 6577 6578 // Guard against huge trip counts (this requires checking 6579 // for zero to handle the case where the trip count == -1 and the 6580 // addition wraps). 6581 if (!Result || Result->getValue().getActiveBits() > 32 || 6582 Result->getValue().getActiveBits() == 0) 6583 return 1; 6584 6585 return (unsigned)Result->getZExtValue(); 6586 } 6587 6588 /// Get the expression for the number of loop iterations for which this loop is 6589 /// guaranteed not to exit via ExitingBlock. Otherwise return 6590 /// SCEVCouldNotCompute. 6591 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6592 BasicBlock *ExitingBlock) { 6593 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6594 } 6595 6596 const SCEV * 6597 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6598 SCEVUnionPredicate &Preds) { 6599 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6600 } 6601 6602 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6603 return getBackedgeTakenInfo(L).getExact(L, this); 6604 } 6605 6606 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6607 /// known never to be less than the actual backedge taken count. 6608 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 6609 return getBackedgeTakenInfo(L).getMax(this); 6610 } 6611 6612 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6613 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6614 } 6615 6616 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6617 static void 6618 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6619 BasicBlock *Header = L->getHeader(); 6620 6621 // Push all Loop-header PHIs onto the Worklist stack. 6622 for (PHINode &PN : Header->phis()) 6623 Worklist.push_back(&PN); 6624 } 6625 6626 const ScalarEvolution::BackedgeTakenInfo & 6627 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6628 auto &BTI = getBackedgeTakenInfo(L); 6629 if (BTI.hasFullInfo()) 6630 return BTI; 6631 6632 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6633 6634 if (!Pair.second) 6635 return Pair.first->second; 6636 6637 BackedgeTakenInfo Result = 6638 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6639 6640 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6641 } 6642 6643 const ScalarEvolution::BackedgeTakenInfo & 6644 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6645 // Initially insert an invalid entry for this loop. If the insertion 6646 // succeeds, proceed to actually compute a backedge-taken count and 6647 // update the value. The temporary CouldNotCompute value tells SCEV 6648 // code elsewhere that it shouldn't attempt to request a new 6649 // backedge-taken count, which could result in infinite recursion. 6650 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6651 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6652 if (!Pair.second) 6653 return Pair.first->second; 6654 6655 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6656 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6657 // must be cleared in this scope. 6658 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6659 6660 // In product build, there are no usage of statistic. 6661 (void)NumTripCountsComputed; 6662 (void)NumTripCountsNotComputed; 6663 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6664 const SCEV *BEExact = Result.getExact(L, this); 6665 if (BEExact != getCouldNotCompute()) { 6666 assert(isLoopInvariant(BEExact, L) && 6667 isLoopInvariant(Result.getMax(this), L) && 6668 "Computed backedge-taken count isn't loop invariant for loop!"); 6669 ++NumTripCountsComputed; 6670 } 6671 else if (Result.getMax(this) == getCouldNotCompute() && 6672 isa<PHINode>(L->getHeader()->begin())) { 6673 // Only count loops that have phi nodes as not being computable. 6674 ++NumTripCountsNotComputed; 6675 } 6676 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6677 6678 // Now that we know more about the trip count for this loop, forget any 6679 // existing SCEV values for PHI nodes in this loop since they are only 6680 // conservative estimates made without the benefit of trip count 6681 // information. This is similar to the code in forgetLoop, except that 6682 // it handles SCEVUnknown PHI nodes specially. 6683 if (Result.hasAnyInfo()) { 6684 SmallVector<Instruction *, 16> Worklist; 6685 PushLoopPHIs(L, Worklist); 6686 6687 SmallPtrSet<Instruction *, 8> Discovered; 6688 while (!Worklist.empty()) { 6689 Instruction *I = Worklist.pop_back_val(); 6690 6691 ValueExprMapType::iterator It = 6692 ValueExprMap.find_as(static_cast<Value *>(I)); 6693 if (It != ValueExprMap.end()) { 6694 const SCEV *Old = It->second; 6695 6696 // SCEVUnknown for a PHI either means that it has an unrecognized 6697 // structure, or it's a PHI that's in the progress of being computed 6698 // by createNodeForPHI. In the former case, additional loop trip 6699 // count information isn't going to change anything. In the later 6700 // case, createNodeForPHI will perform the necessary updates on its 6701 // own when it gets to that point. 6702 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6703 eraseValueFromMap(It->first); 6704 forgetMemoizedResults(Old); 6705 } 6706 if (PHINode *PN = dyn_cast<PHINode>(I)) 6707 ConstantEvolutionLoopExitValue.erase(PN); 6708 } 6709 6710 // Since we don't need to invalidate anything for correctness and we're 6711 // only invalidating to make SCEV's results more precise, we get to stop 6712 // early to avoid invalidating too much. This is especially important in 6713 // cases like: 6714 // 6715 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6716 // loop0: 6717 // %pn0 = phi 6718 // ... 6719 // loop1: 6720 // %pn1 = phi 6721 // ... 6722 // 6723 // where both loop0 and loop1's backedge taken count uses the SCEV 6724 // expression for %v. If we don't have the early stop below then in cases 6725 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6726 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6727 // count for loop1, effectively nullifying SCEV's trip count cache. 6728 for (auto *U : I->users()) 6729 if (auto *I = dyn_cast<Instruction>(U)) { 6730 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6731 if (LoopForUser && L->contains(LoopForUser) && 6732 Discovered.insert(I).second) 6733 Worklist.push_back(I); 6734 } 6735 } 6736 } 6737 6738 // Re-lookup the insert position, since the call to 6739 // computeBackedgeTakenCount above could result in a 6740 // recusive call to getBackedgeTakenInfo (on a different 6741 // loop), which would invalidate the iterator computed 6742 // earlier. 6743 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6744 } 6745 6746 void ScalarEvolution::forgetLoop(const Loop *L) { 6747 // Drop any stored trip count value. 6748 auto RemoveLoopFromBackedgeMap = 6749 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6750 auto BTCPos = Map.find(L); 6751 if (BTCPos != Map.end()) { 6752 BTCPos->second.clear(); 6753 Map.erase(BTCPos); 6754 } 6755 }; 6756 6757 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6758 SmallVector<Instruction *, 32> Worklist; 6759 SmallPtrSet<Instruction *, 16> Visited; 6760 6761 // Iterate over all the loops and sub-loops to drop SCEV information. 6762 while (!LoopWorklist.empty()) { 6763 auto *CurrL = LoopWorklist.pop_back_val(); 6764 6765 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6766 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6767 6768 // Drop information about predicated SCEV rewrites for this loop. 6769 for (auto I = PredicatedSCEVRewrites.begin(); 6770 I != PredicatedSCEVRewrites.end();) { 6771 std::pair<const SCEV *, const Loop *> Entry = I->first; 6772 if (Entry.second == CurrL) 6773 PredicatedSCEVRewrites.erase(I++); 6774 else 6775 ++I; 6776 } 6777 6778 auto LoopUsersItr = LoopUsers.find(CurrL); 6779 if (LoopUsersItr != LoopUsers.end()) { 6780 for (auto *S : LoopUsersItr->second) 6781 forgetMemoizedResults(S); 6782 LoopUsers.erase(LoopUsersItr); 6783 } 6784 6785 // Drop information about expressions based on loop-header PHIs. 6786 PushLoopPHIs(CurrL, Worklist); 6787 6788 while (!Worklist.empty()) { 6789 Instruction *I = Worklist.pop_back_val(); 6790 if (!Visited.insert(I).second) 6791 continue; 6792 6793 ValueExprMapType::iterator It = 6794 ValueExprMap.find_as(static_cast<Value *>(I)); 6795 if (It != ValueExprMap.end()) { 6796 eraseValueFromMap(It->first); 6797 forgetMemoizedResults(It->second); 6798 if (PHINode *PN = dyn_cast<PHINode>(I)) 6799 ConstantEvolutionLoopExitValue.erase(PN); 6800 } 6801 6802 PushDefUseChildren(I, Worklist); 6803 } 6804 6805 LoopPropertiesCache.erase(CurrL); 6806 // Forget all contained loops too, to avoid dangling entries in the 6807 // ValuesAtScopes map. 6808 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6809 } 6810 } 6811 6812 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6813 while (Loop *Parent = L->getParentLoop()) 6814 L = Parent; 6815 forgetLoop(L); 6816 } 6817 6818 void ScalarEvolution::forgetValue(Value *V) { 6819 Instruction *I = dyn_cast<Instruction>(V); 6820 if (!I) return; 6821 6822 // Drop information about expressions based on loop-header PHIs. 6823 SmallVector<Instruction *, 16> Worklist; 6824 Worklist.push_back(I); 6825 6826 SmallPtrSet<Instruction *, 8> Visited; 6827 while (!Worklist.empty()) { 6828 I = Worklist.pop_back_val(); 6829 if (!Visited.insert(I).second) 6830 continue; 6831 6832 ValueExprMapType::iterator It = 6833 ValueExprMap.find_as(static_cast<Value *>(I)); 6834 if (It != ValueExprMap.end()) { 6835 eraseValueFromMap(It->first); 6836 forgetMemoizedResults(It->second); 6837 if (PHINode *PN = dyn_cast<PHINode>(I)) 6838 ConstantEvolutionLoopExitValue.erase(PN); 6839 } 6840 6841 PushDefUseChildren(I, Worklist); 6842 } 6843 } 6844 6845 /// Get the exact loop backedge taken count considering all loop exits. A 6846 /// computable result can only be returned for loops with all exiting blocks 6847 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6848 /// is never skipped. This is a valid assumption as long as the loop exits via 6849 /// that test. For precise results, it is the caller's responsibility to specify 6850 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6851 const SCEV * 6852 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6853 SCEVUnionPredicate *Preds) const { 6854 // If any exits were not computable, the loop is not computable. 6855 if (!isComplete() || ExitNotTaken.empty()) 6856 return SE->getCouldNotCompute(); 6857 6858 const BasicBlock *Latch = L->getLoopLatch(); 6859 // All exiting blocks we have collected must dominate the only backedge. 6860 if (!Latch) 6861 return SE->getCouldNotCompute(); 6862 6863 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6864 // count is simply a minimum out of all these calculated exit counts. 6865 SmallVector<const SCEV *, 2> Ops; 6866 for (auto &ENT : ExitNotTaken) { 6867 const SCEV *BECount = ENT.ExactNotTaken; 6868 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6869 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6870 "We should only have known counts for exiting blocks that dominate " 6871 "latch!"); 6872 6873 Ops.push_back(BECount); 6874 6875 if (Preds && !ENT.hasAlwaysTruePredicate()) 6876 Preds->add(ENT.Predicate.get()); 6877 6878 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6879 "Predicate should be always true!"); 6880 } 6881 6882 return SE->getUMinFromMismatchedTypes(Ops); 6883 } 6884 6885 /// Get the exact not taken count for this loop exit. 6886 const SCEV * 6887 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6888 ScalarEvolution *SE) const { 6889 for (auto &ENT : ExitNotTaken) 6890 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6891 return ENT.ExactNotTaken; 6892 6893 return SE->getCouldNotCompute(); 6894 } 6895 6896 /// getMax - Get the max backedge taken count for the loop. 6897 const SCEV * 6898 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6899 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6900 return !ENT.hasAlwaysTruePredicate(); 6901 }; 6902 6903 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6904 return SE->getCouldNotCompute(); 6905 6906 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6907 "No point in having a non-constant max backedge taken count!"); 6908 return getMax(); 6909 } 6910 6911 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6912 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6913 return !ENT.hasAlwaysTruePredicate(); 6914 }; 6915 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6916 } 6917 6918 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6919 ScalarEvolution *SE) const { 6920 if (getMax() && getMax() != SE->getCouldNotCompute() && 6921 SE->hasOperand(getMax(), S)) 6922 return true; 6923 6924 for (auto &ENT : ExitNotTaken) 6925 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6926 SE->hasOperand(ENT.ExactNotTaken, S)) 6927 return true; 6928 6929 return false; 6930 } 6931 6932 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6933 : ExactNotTaken(E), MaxNotTaken(E) { 6934 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6935 isa<SCEVConstant>(MaxNotTaken)) && 6936 "No point in having a non-constant max backedge taken count!"); 6937 } 6938 6939 ScalarEvolution::ExitLimit::ExitLimit( 6940 const SCEV *E, const SCEV *M, bool MaxOrZero, 6941 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6942 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6943 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6944 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6945 "Exact is not allowed to be less precise than Max"); 6946 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6947 isa<SCEVConstant>(MaxNotTaken)) && 6948 "No point in having a non-constant max backedge taken count!"); 6949 for (auto *PredSet : PredSetList) 6950 for (auto *P : *PredSet) 6951 addPredicate(P); 6952 } 6953 6954 ScalarEvolution::ExitLimit::ExitLimit( 6955 const SCEV *E, const SCEV *M, bool MaxOrZero, 6956 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6957 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6958 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6959 isa<SCEVConstant>(MaxNotTaken)) && 6960 "No point in having a non-constant max backedge taken count!"); 6961 } 6962 6963 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6964 bool MaxOrZero) 6965 : ExitLimit(E, M, MaxOrZero, None) { 6966 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6967 isa<SCEVConstant>(MaxNotTaken)) && 6968 "No point in having a non-constant max backedge taken count!"); 6969 } 6970 6971 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 6972 /// computable exit into a persistent ExitNotTakenInfo array. 6973 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 6974 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 6975 &&ExitCounts, 6976 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 6977 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 6978 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6979 6980 ExitNotTaken.reserve(ExitCounts.size()); 6981 std::transform( 6982 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 6983 [&](const EdgeExitInfo &EEI) { 6984 BasicBlock *ExitBB = EEI.first; 6985 const ExitLimit &EL = EEI.second; 6986 if (EL.Predicates.empty()) 6987 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 6988 6989 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 6990 for (auto *Pred : EL.Predicates) 6991 Predicate->add(Pred); 6992 6993 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 6994 }); 6995 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 6996 "No point in having a non-constant max backedge taken count!"); 6997 } 6998 6999 /// Invalidate this result and free the ExitNotTakenInfo array. 7000 void ScalarEvolution::BackedgeTakenInfo::clear() { 7001 ExitNotTaken.clear(); 7002 } 7003 7004 /// Compute the number of times the backedge of the specified loop will execute. 7005 ScalarEvolution::BackedgeTakenInfo 7006 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7007 bool AllowPredicates) { 7008 SmallVector<BasicBlock *, 8> ExitingBlocks; 7009 L->getExitingBlocks(ExitingBlocks); 7010 7011 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7012 7013 SmallVector<EdgeExitInfo, 4> ExitCounts; 7014 bool CouldComputeBECount = true; 7015 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7016 const SCEV *MustExitMaxBECount = nullptr; 7017 const SCEV *MayExitMaxBECount = nullptr; 7018 bool MustExitMaxOrZero = false; 7019 7020 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7021 // and compute maxBECount. 7022 // Do a union of all the predicates here. 7023 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7024 BasicBlock *ExitBB = ExitingBlocks[i]; 7025 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7026 7027 assert((AllowPredicates || EL.Predicates.empty()) && 7028 "Predicated exit limit when predicates are not allowed!"); 7029 7030 // 1. For each exit that can be computed, add an entry to ExitCounts. 7031 // CouldComputeBECount is true only if all exits can be computed. 7032 if (EL.ExactNotTaken == getCouldNotCompute()) 7033 // We couldn't compute an exact value for this exit, so 7034 // we won't be able to compute an exact value for the loop. 7035 CouldComputeBECount = false; 7036 else 7037 ExitCounts.emplace_back(ExitBB, EL); 7038 7039 // 2. Derive the loop's MaxBECount from each exit's max number of 7040 // non-exiting iterations. Partition the loop exits into two kinds: 7041 // LoopMustExits and LoopMayExits. 7042 // 7043 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7044 // is a LoopMayExit. If any computable LoopMustExit is found, then 7045 // MaxBECount is the minimum EL.MaxNotTaken of computable 7046 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7047 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7048 // computable EL.MaxNotTaken. 7049 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7050 DT.dominates(ExitBB, Latch)) { 7051 if (!MustExitMaxBECount) { 7052 MustExitMaxBECount = EL.MaxNotTaken; 7053 MustExitMaxOrZero = EL.MaxOrZero; 7054 } else { 7055 MustExitMaxBECount = 7056 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7057 } 7058 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7059 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7060 MayExitMaxBECount = EL.MaxNotTaken; 7061 else { 7062 MayExitMaxBECount = 7063 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7064 } 7065 } 7066 } 7067 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7068 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7069 // The loop backedge will be taken the maximum or zero times if there's 7070 // a single exit that must be taken the maximum or zero times. 7071 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7072 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7073 MaxBECount, MaxOrZero); 7074 } 7075 7076 ScalarEvolution::ExitLimit 7077 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7078 bool AllowPredicates) { 7079 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7080 // If our exiting block does not dominate the latch, then its connection with 7081 // loop's exit limit may be far from trivial. 7082 const BasicBlock *Latch = L->getLoopLatch(); 7083 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7084 return getCouldNotCompute(); 7085 7086 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7087 Instruction *Term = ExitingBlock->getTerminator(); 7088 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7089 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7090 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7091 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7092 "It should have one successor in loop and one exit block!"); 7093 // Proceed to the next level to examine the exit condition expression. 7094 return computeExitLimitFromCond( 7095 L, BI->getCondition(), ExitIfTrue, 7096 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7097 } 7098 7099 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7100 // For switch, make sure that there is a single exit from the loop. 7101 BasicBlock *Exit = nullptr; 7102 for (auto *SBB : successors(ExitingBlock)) 7103 if (!L->contains(SBB)) { 7104 if (Exit) // Multiple exit successors. 7105 return getCouldNotCompute(); 7106 Exit = SBB; 7107 } 7108 assert(Exit && "Exiting block must have at least one exit"); 7109 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7110 /*ControlsExit=*/IsOnlyExit); 7111 } 7112 7113 return getCouldNotCompute(); 7114 } 7115 7116 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7117 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7118 bool ControlsExit, bool AllowPredicates) { 7119 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7120 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7121 ControlsExit, AllowPredicates); 7122 } 7123 7124 Optional<ScalarEvolution::ExitLimit> 7125 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7126 bool ExitIfTrue, bool ControlsExit, 7127 bool AllowPredicates) { 7128 (void)this->L; 7129 (void)this->ExitIfTrue; 7130 (void)this->AllowPredicates; 7131 7132 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7133 this->AllowPredicates == AllowPredicates && 7134 "Variance in assumed invariant key components!"); 7135 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7136 if (Itr == TripCountMap.end()) 7137 return None; 7138 return Itr->second; 7139 } 7140 7141 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7142 bool ExitIfTrue, 7143 bool ControlsExit, 7144 bool AllowPredicates, 7145 const ExitLimit &EL) { 7146 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7147 this->AllowPredicates == AllowPredicates && 7148 "Variance in assumed invariant key components!"); 7149 7150 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7151 assert(InsertResult.second && "Expected successful insertion!"); 7152 (void)InsertResult; 7153 (void)ExitIfTrue; 7154 } 7155 7156 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7157 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7158 bool ControlsExit, bool AllowPredicates) { 7159 7160 if (auto MaybeEL = 7161 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7162 return *MaybeEL; 7163 7164 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7165 ControlsExit, AllowPredicates); 7166 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7167 return EL; 7168 } 7169 7170 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7171 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7172 bool ControlsExit, bool AllowPredicates) { 7173 // Check if the controlling expression for this loop is an And or Or. 7174 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7175 if (BO->getOpcode() == Instruction::And) { 7176 // Recurse on the operands of the and. 7177 bool EitherMayExit = !ExitIfTrue; 7178 ExitLimit EL0 = computeExitLimitFromCondCached( 7179 Cache, L, BO->getOperand(0), ExitIfTrue, 7180 ControlsExit && !EitherMayExit, AllowPredicates); 7181 ExitLimit EL1 = computeExitLimitFromCondCached( 7182 Cache, L, BO->getOperand(1), ExitIfTrue, 7183 ControlsExit && !EitherMayExit, AllowPredicates); 7184 const SCEV *BECount = getCouldNotCompute(); 7185 const SCEV *MaxBECount = getCouldNotCompute(); 7186 if (EitherMayExit) { 7187 // Both conditions must be true for the loop to continue executing. 7188 // Choose the less conservative count. 7189 if (EL0.ExactNotTaken == getCouldNotCompute() || 7190 EL1.ExactNotTaken == getCouldNotCompute()) 7191 BECount = getCouldNotCompute(); 7192 else 7193 BECount = 7194 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7195 if (EL0.MaxNotTaken == getCouldNotCompute()) 7196 MaxBECount = EL1.MaxNotTaken; 7197 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7198 MaxBECount = EL0.MaxNotTaken; 7199 else 7200 MaxBECount = 7201 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7202 } else { 7203 // Both conditions must be true at the same time for the loop to exit. 7204 // For now, be conservative. 7205 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7206 MaxBECount = EL0.MaxNotTaken; 7207 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7208 BECount = EL0.ExactNotTaken; 7209 } 7210 7211 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7212 // to be more aggressive when computing BECount than when computing 7213 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7214 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7215 // to not. 7216 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7217 !isa<SCEVCouldNotCompute>(BECount)) 7218 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7219 7220 return ExitLimit(BECount, MaxBECount, false, 7221 {&EL0.Predicates, &EL1.Predicates}); 7222 } 7223 if (BO->getOpcode() == Instruction::Or) { 7224 // Recurse on the operands of the or. 7225 bool EitherMayExit = ExitIfTrue; 7226 ExitLimit EL0 = computeExitLimitFromCondCached( 7227 Cache, L, BO->getOperand(0), ExitIfTrue, 7228 ControlsExit && !EitherMayExit, AllowPredicates); 7229 ExitLimit EL1 = computeExitLimitFromCondCached( 7230 Cache, L, BO->getOperand(1), ExitIfTrue, 7231 ControlsExit && !EitherMayExit, AllowPredicates); 7232 const SCEV *BECount = getCouldNotCompute(); 7233 const SCEV *MaxBECount = getCouldNotCompute(); 7234 if (EitherMayExit) { 7235 // Both conditions must be false for the loop to continue executing. 7236 // Choose the less conservative count. 7237 if (EL0.ExactNotTaken == getCouldNotCompute() || 7238 EL1.ExactNotTaken == getCouldNotCompute()) 7239 BECount = getCouldNotCompute(); 7240 else 7241 BECount = 7242 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7243 if (EL0.MaxNotTaken == getCouldNotCompute()) 7244 MaxBECount = EL1.MaxNotTaken; 7245 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7246 MaxBECount = EL0.MaxNotTaken; 7247 else 7248 MaxBECount = 7249 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7250 } else { 7251 // Both conditions must be false at the same time for the loop to exit. 7252 // For now, be conservative. 7253 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7254 MaxBECount = EL0.MaxNotTaken; 7255 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7256 BECount = EL0.ExactNotTaken; 7257 } 7258 7259 return ExitLimit(BECount, MaxBECount, false, 7260 {&EL0.Predicates, &EL1.Predicates}); 7261 } 7262 } 7263 7264 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7265 // Proceed to the next level to examine the icmp. 7266 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7267 ExitLimit EL = 7268 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7269 if (EL.hasFullInfo() || !AllowPredicates) 7270 return EL; 7271 7272 // Try again, but use SCEV predicates this time. 7273 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7274 /*AllowPredicates=*/true); 7275 } 7276 7277 // Check for a constant condition. These are normally stripped out by 7278 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7279 // preserve the CFG and is temporarily leaving constant conditions 7280 // in place. 7281 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7282 if (ExitIfTrue == !CI->getZExtValue()) 7283 // The backedge is always taken. 7284 return getCouldNotCompute(); 7285 else 7286 // The backedge is never taken. 7287 return getZero(CI->getType()); 7288 } 7289 7290 // If it's not an integer or pointer comparison then compute it the hard way. 7291 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7292 } 7293 7294 ScalarEvolution::ExitLimit 7295 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7296 ICmpInst *ExitCond, 7297 bool ExitIfTrue, 7298 bool ControlsExit, 7299 bool AllowPredicates) { 7300 // If the condition was exit on true, convert the condition to exit on false 7301 ICmpInst::Predicate Pred; 7302 if (!ExitIfTrue) 7303 Pred = ExitCond->getPredicate(); 7304 else 7305 Pred = ExitCond->getInversePredicate(); 7306 const ICmpInst::Predicate OriginalPred = Pred; 7307 7308 // Handle common loops like: for (X = "string"; *X; ++X) 7309 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7310 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7311 ExitLimit ItCnt = 7312 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7313 if (ItCnt.hasAnyInfo()) 7314 return ItCnt; 7315 } 7316 7317 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7318 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7319 7320 // Try to evaluate any dependencies out of the loop. 7321 LHS = getSCEVAtScope(LHS, L); 7322 RHS = getSCEVAtScope(RHS, L); 7323 7324 // At this point, we would like to compute how many iterations of the 7325 // loop the predicate will return true for these inputs. 7326 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7327 // If there is a loop-invariant, force it into the RHS. 7328 std::swap(LHS, RHS); 7329 Pred = ICmpInst::getSwappedPredicate(Pred); 7330 } 7331 7332 // Simplify the operands before analyzing them. 7333 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7334 7335 // If we have a comparison of a chrec against a constant, try to use value 7336 // ranges to answer this query. 7337 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7338 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7339 if (AddRec->getLoop() == L) { 7340 // Form the constant range. 7341 ConstantRange CompRange = 7342 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7343 7344 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7345 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7346 } 7347 7348 switch (Pred) { 7349 case ICmpInst::ICMP_NE: { // while (X != Y) 7350 // Convert to: while (X-Y != 0) 7351 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7352 AllowPredicates); 7353 if (EL.hasAnyInfo()) return EL; 7354 break; 7355 } 7356 case ICmpInst::ICMP_EQ: { // while (X == Y) 7357 // Convert to: while (X-Y == 0) 7358 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7359 if (EL.hasAnyInfo()) return EL; 7360 break; 7361 } 7362 case ICmpInst::ICMP_SLT: 7363 case ICmpInst::ICMP_ULT: { // while (X < Y) 7364 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7365 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7366 AllowPredicates); 7367 if (EL.hasAnyInfo()) return EL; 7368 break; 7369 } 7370 case ICmpInst::ICMP_SGT: 7371 case ICmpInst::ICMP_UGT: { // while (X > Y) 7372 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7373 ExitLimit EL = 7374 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7375 AllowPredicates); 7376 if (EL.hasAnyInfo()) return EL; 7377 break; 7378 } 7379 default: 7380 break; 7381 } 7382 7383 auto *ExhaustiveCount = 7384 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7385 7386 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7387 return ExhaustiveCount; 7388 7389 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7390 ExitCond->getOperand(1), L, OriginalPred); 7391 } 7392 7393 ScalarEvolution::ExitLimit 7394 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7395 SwitchInst *Switch, 7396 BasicBlock *ExitingBlock, 7397 bool ControlsExit) { 7398 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7399 7400 // Give up if the exit is the default dest of a switch. 7401 if (Switch->getDefaultDest() == ExitingBlock) 7402 return getCouldNotCompute(); 7403 7404 assert(L->contains(Switch->getDefaultDest()) && 7405 "Default case must not exit the loop!"); 7406 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7407 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7408 7409 // while (X != Y) --> while (X-Y != 0) 7410 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7411 if (EL.hasAnyInfo()) 7412 return EL; 7413 7414 return getCouldNotCompute(); 7415 } 7416 7417 static ConstantInt * 7418 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7419 ScalarEvolution &SE) { 7420 const SCEV *InVal = SE.getConstant(C); 7421 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7422 assert(isa<SCEVConstant>(Val) && 7423 "Evaluation of SCEV at constant didn't fold correctly?"); 7424 return cast<SCEVConstant>(Val)->getValue(); 7425 } 7426 7427 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7428 /// compute the backedge execution count. 7429 ScalarEvolution::ExitLimit 7430 ScalarEvolution::computeLoadConstantCompareExitLimit( 7431 LoadInst *LI, 7432 Constant *RHS, 7433 const Loop *L, 7434 ICmpInst::Predicate predicate) { 7435 if (LI->isVolatile()) return getCouldNotCompute(); 7436 7437 // Check to see if the loaded pointer is a getelementptr of a global. 7438 // TODO: Use SCEV instead of manually grubbing with GEPs. 7439 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7440 if (!GEP) return getCouldNotCompute(); 7441 7442 // Make sure that it is really a constant global we are gepping, with an 7443 // initializer, and make sure the first IDX is really 0. 7444 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7445 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7446 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7447 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7448 return getCouldNotCompute(); 7449 7450 // Okay, we allow one non-constant index into the GEP instruction. 7451 Value *VarIdx = nullptr; 7452 std::vector<Constant*> Indexes; 7453 unsigned VarIdxNum = 0; 7454 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7455 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7456 Indexes.push_back(CI); 7457 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7458 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7459 VarIdx = GEP->getOperand(i); 7460 VarIdxNum = i-2; 7461 Indexes.push_back(nullptr); 7462 } 7463 7464 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7465 if (!VarIdx) 7466 return getCouldNotCompute(); 7467 7468 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7469 // Check to see if X is a loop variant variable value now. 7470 const SCEV *Idx = getSCEV(VarIdx); 7471 Idx = getSCEVAtScope(Idx, L); 7472 7473 // We can only recognize very limited forms of loop index expressions, in 7474 // particular, only affine AddRec's like {C1,+,C2}. 7475 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7476 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7477 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7478 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7479 return getCouldNotCompute(); 7480 7481 unsigned MaxSteps = MaxBruteForceIterations; 7482 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7483 ConstantInt *ItCst = ConstantInt::get( 7484 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7485 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7486 7487 // Form the GEP offset. 7488 Indexes[VarIdxNum] = Val; 7489 7490 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7491 Indexes); 7492 if (!Result) break; // Cannot compute! 7493 7494 // Evaluate the condition for this iteration. 7495 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7496 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7497 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7498 ++NumArrayLenItCounts; 7499 return getConstant(ItCst); // Found terminating iteration! 7500 } 7501 } 7502 return getCouldNotCompute(); 7503 } 7504 7505 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7506 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7507 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7508 if (!RHS) 7509 return getCouldNotCompute(); 7510 7511 const BasicBlock *Latch = L->getLoopLatch(); 7512 if (!Latch) 7513 return getCouldNotCompute(); 7514 7515 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7516 if (!Predecessor) 7517 return getCouldNotCompute(); 7518 7519 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7520 // Return LHS in OutLHS and shift_opt in OutOpCode. 7521 auto MatchPositiveShift = 7522 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7523 7524 using namespace PatternMatch; 7525 7526 ConstantInt *ShiftAmt; 7527 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7528 OutOpCode = Instruction::LShr; 7529 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7530 OutOpCode = Instruction::AShr; 7531 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7532 OutOpCode = Instruction::Shl; 7533 else 7534 return false; 7535 7536 return ShiftAmt->getValue().isStrictlyPositive(); 7537 }; 7538 7539 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7540 // 7541 // loop: 7542 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7543 // %iv.shifted = lshr i32 %iv, <positive constant> 7544 // 7545 // Return true on a successful match. Return the corresponding PHI node (%iv 7546 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7547 auto MatchShiftRecurrence = 7548 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7549 Optional<Instruction::BinaryOps> PostShiftOpCode; 7550 7551 { 7552 Instruction::BinaryOps OpC; 7553 Value *V; 7554 7555 // If we encounter a shift instruction, "peel off" the shift operation, 7556 // and remember that we did so. Later when we inspect %iv's backedge 7557 // value, we will make sure that the backedge value uses the same 7558 // operation. 7559 // 7560 // Note: the peeled shift operation does not have to be the same 7561 // instruction as the one feeding into the PHI's backedge value. We only 7562 // really care about it being the same *kind* of shift instruction -- 7563 // that's all that is required for our later inferences to hold. 7564 if (MatchPositiveShift(LHS, V, OpC)) { 7565 PostShiftOpCode = OpC; 7566 LHS = V; 7567 } 7568 } 7569 7570 PNOut = dyn_cast<PHINode>(LHS); 7571 if (!PNOut || PNOut->getParent() != L->getHeader()) 7572 return false; 7573 7574 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7575 Value *OpLHS; 7576 7577 return 7578 // The backedge value for the PHI node must be a shift by a positive 7579 // amount 7580 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7581 7582 // of the PHI node itself 7583 OpLHS == PNOut && 7584 7585 // and the kind of shift should be match the kind of shift we peeled 7586 // off, if any. 7587 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7588 }; 7589 7590 PHINode *PN; 7591 Instruction::BinaryOps OpCode; 7592 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7593 return getCouldNotCompute(); 7594 7595 const DataLayout &DL = getDataLayout(); 7596 7597 // The key rationale for this optimization is that for some kinds of shift 7598 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7599 // within a finite number of iterations. If the condition guarding the 7600 // backedge (in the sense that the backedge is taken if the condition is true) 7601 // is false for the value the shift recurrence stabilizes to, then we know 7602 // that the backedge is taken only a finite number of times. 7603 7604 ConstantInt *StableValue = nullptr; 7605 switch (OpCode) { 7606 default: 7607 llvm_unreachable("Impossible case!"); 7608 7609 case Instruction::AShr: { 7610 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7611 // bitwidth(K) iterations. 7612 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7613 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7614 Predecessor->getTerminator(), &DT); 7615 auto *Ty = cast<IntegerType>(RHS->getType()); 7616 if (Known.isNonNegative()) 7617 StableValue = ConstantInt::get(Ty, 0); 7618 else if (Known.isNegative()) 7619 StableValue = ConstantInt::get(Ty, -1, true); 7620 else 7621 return getCouldNotCompute(); 7622 7623 break; 7624 } 7625 case Instruction::LShr: 7626 case Instruction::Shl: 7627 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7628 // stabilize to 0 in at most bitwidth(K) iterations. 7629 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7630 break; 7631 } 7632 7633 auto *Result = 7634 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7635 assert(Result->getType()->isIntegerTy(1) && 7636 "Otherwise cannot be an operand to a branch instruction"); 7637 7638 if (Result->isZeroValue()) { 7639 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7640 const SCEV *UpperBound = 7641 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7642 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7643 } 7644 7645 return getCouldNotCompute(); 7646 } 7647 7648 /// Return true if we can constant fold an instruction of the specified type, 7649 /// assuming that all operands were constants. 7650 static bool CanConstantFold(const Instruction *I) { 7651 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7652 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7653 isa<LoadInst>(I)) 7654 return true; 7655 7656 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7657 if (const Function *F = CI->getCalledFunction()) 7658 return canConstantFoldCallTo(CI, F); 7659 return false; 7660 } 7661 7662 /// Determine whether this instruction can constant evolve within this loop 7663 /// assuming its operands can all constant evolve. 7664 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7665 // An instruction outside of the loop can't be derived from a loop PHI. 7666 if (!L->contains(I)) return false; 7667 7668 if (isa<PHINode>(I)) { 7669 // We don't currently keep track of the control flow needed to evaluate 7670 // PHIs, so we cannot handle PHIs inside of loops. 7671 return L->getHeader() == I->getParent(); 7672 } 7673 7674 // If we won't be able to constant fold this expression even if the operands 7675 // are constants, bail early. 7676 return CanConstantFold(I); 7677 } 7678 7679 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7680 /// recursing through each instruction operand until reaching a loop header phi. 7681 static PHINode * 7682 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7683 DenseMap<Instruction *, PHINode *> &PHIMap, 7684 unsigned Depth) { 7685 if (Depth > MaxConstantEvolvingDepth) 7686 return nullptr; 7687 7688 // Otherwise, we can evaluate this instruction if all of its operands are 7689 // constant or derived from a PHI node themselves. 7690 PHINode *PHI = nullptr; 7691 for (Value *Op : UseInst->operands()) { 7692 if (isa<Constant>(Op)) continue; 7693 7694 Instruction *OpInst = dyn_cast<Instruction>(Op); 7695 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7696 7697 PHINode *P = dyn_cast<PHINode>(OpInst); 7698 if (!P) 7699 // If this operand is already visited, reuse the prior result. 7700 // We may have P != PHI if this is the deepest point at which the 7701 // inconsistent paths meet. 7702 P = PHIMap.lookup(OpInst); 7703 if (!P) { 7704 // Recurse and memoize the results, whether a phi is found or not. 7705 // This recursive call invalidates pointers into PHIMap. 7706 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7707 PHIMap[OpInst] = P; 7708 } 7709 if (!P) 7710 return nullptr; // Not evolving from PHI 7711 if (PHI && PHI != P) 7712 return nullptr; // Evolving from multiple different PHIs. 7713 PHI = P; 7714 } 7715 // This is a expression evolving from a constant PHI! 7716 return PHI; 7717 } 7718 7719 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7720 /// in the loop that V is derived from. We allow arbitrary operations along the 7721 /// way, but the operands of an operation must either be constants or a value 7722 /// derived from a constant PHI. If this expression does not fit with these 7723 /// constraints, return null. 7724 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7725 Instruction *I = dyn_cast<Instruction>(V); 7726 if (!I || !canConstantEvolve(I, L)) return nullptr; 7727 7728 if (PHINode *PN = dyn_cast<PHINode>(I)) 7729 return PN; 7730 7731 // Record non-constant instructions contained by the loop. 7732 DenseMap<Instruction *, PHINode *> PHIMap; 7733 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7734 } 7735 7736 /// EvaluateExpression - Given an expression that passes the 7737 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7738 /// in the loop has the value PHIVal. If we can't fold this expression for some 7739 /// reason, return null. 7740 static Constant *EvaluateExpression(Value *V, const Loop *L, 7741 DenseMap<Instruction *, Constant *> &Vals, 7742 const DataLayout &DL, 7743 const TargetLibraryInfo *TLI) { 7744 // Convenient constant check, but redundant for recursive calls. 7745 if (Constant *C = dyn_cast<Constant>(V)) return C; 7746 Instruction *I = dyn_cast<Instruction>(V); 7747 if (!I) return nullptr; 7748 7749 if (Constant *C = Vals.lookup(I)) return C; 7750 7751 // An instruction inside the loop depends on a value outside the loop that we 7752 // weren't given a mapping for, or a value such as a call inside the loop. 7753 if (!canConstantEvolve(I, L)) return nullptr; 7754 7755 // An unmapped PHI can be due to a branch or another loop inside this loop, 7756 // or due to this not being the initial iteration through a loop where we 7757 // couldn't compute the evolution of this particular PHI last time. 7758 if (isa<PHINode>(I)) return nullptr; 7759 7760 std::vector<Constant*> Operands(I->getNumOperands()); 7761 7762 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7763 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7764 if (!Operand) { 7765 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7766 if (!Operands[i]) return nullptr; 7767 continue; 7768 } 7769 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7770 Vals[Operand] = C; 7771 if (!C) return nullptr; 7772 Operands[i] = C; 7773 } 7774 7775 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7776 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7777 Operands[1], DL, TLI); 7778 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7779 if (!LI->isVolatile()) 7780 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7781 } 7782 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7783 } 7784 7785 7786 // If every incoming value to PN except the one for BB is a specific Constant, 7787 // return that, else return nullptr. 7788 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7789 Constant *IncomingVal = nullptr; 7790 7791 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7792 if (PN->getIncomingBlock(i) == BB) 7793 continue; 7794 7795 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7796 if (!CurrentVal) 7797 return nullptr; 7798 7799 if (IncomingVal != CurrentVal) { 7800 if (IncomingVal) 7801 return nullptr; 7802 IncomingVal = CurrentVal; 7803 } 7804 } 7805 7806 return IncomingVal; 7807 } 7808 7809 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7810 /// in the header of its containing loop, we know the loop executes a 7811 /// constant number of times, and the PHI node is just a recurrence 7812 /// involving constants, fold it. 7813 Constant * 7814 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7815 const APInt &BEs, 7816 const Loop *L) { 7817 auto I = ConstantEvolutionLoopExitValue.find(PN); 7818 if (I != ConstantEvolutionLoopExitValue.end()) 7819 return I->second; 7820 7821 if (BEs.ugt(MaxBruteForceIterations)) 7822 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7823 7824 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7825 7826 DenseMap<Instruction *, Constant *> CurrentIterVals; 7827 BasicBlock *Header = L->getHeader(); 7828 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7829 7830 BasicBlock *Latch = L->getLoopLatch(); 7831 if (!Latch) 7832 return nullptr; 7833 7834 for (PHINode &PHI : Header->phis()) { 7835 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7836 CurrentIterVals[&PHI] = StartCST; 7837 } 7838 if (!CurrentIterVals.count(PN)) 7839 return RetVal = nullptr; 7840 7841 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7842 7843 // Execute the loop symbolically to determine the exit value. 7844 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7845 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7846 7847 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7848 unsigned IterationNum = 0; 7849 const DataLayout &DL = getDataLayout(); 7850 for (; ; ++IterationNum) { 7851 if (IterationNum == NumIterations) 7852 return RetVal = CurrentIterVals[PN]; // Got exit value! 7853 7854 // Compute the value of the PHIs for the next iteration. 7855 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7856 DenseMap<Instruction *, Constant *> NextIterVals; 7857 Constant *NextPHI = 7858 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7859 if (!NextPHI) 7860 return nullptr; // Couldn't evaluate! 7861 NextIterVals[PN] = NextPHI; 7862 7863 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7864 7865 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7866 // cease to be able to evaluate one of them or if they stop evolving, 7867 // because that doesn't necessarily prevent us from computing PN. 7868 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7869 for (const auto &I : CurrentIterVals) { 7870 PHINode *PHI = dyn_cast<PHINode>(I.first); 7871 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7872 PHIsToCompute.emplace_back(PHI, I.second); 7873 } 7874 // We use two distinct loops because EvaluateExpression may invalidate any 7875 // iterators into CurrentIterVals. 7876 for (const auto &I : PHIsToCompute) { 7877 PHINode *PHI = I.first; 7878 Constant *&NextPHI = NextIterVals[PHI]; 7879 if (!NextPHI) { // Not already computed. 7880 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7881 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7882 } 7883 if (NextPHI != I.second) 7884 StoppedEvolving = false; 7885 } 7886 7887 // If all entries in CurrentIterVals == NextIterVals then we can stop 7888 // iterating, the loop can't continue to change. 7889 if (StoppedEvolving) 7890 return RetVal = CurrentIterVals[PN]; 7891 7892 CurrentIterVals.swap(NextIterVals); 7893 } 7894 } 7895 7896 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7897 Value *Cond, 7898 bool ExitWhen) { 7899 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7900 if (!PN) return getCouldNotCompute(); 7901 7902 // If the loop is canonicalized, the PHI will have exactly two entries. 7903 // That's the only form we support here. 7904 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7905 7906 DenseMap<Instruction *, Constant *> CurrentIterVals; 7907 BasicBlock *Header = L->getHeader(); 7908 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7909 7910 BasicBlock *Latch = L->getLoopLatch(); 7911 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7912 7913 for (PHINode &PHI : Header->phis()) { 7914 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7915 CurrentIterVals[&PHI] = StartCST; 7916 } 7917 if (!CurrentIterVals.count(PN)) 7918 return getCouldNotCompute(); 7919 7920 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7921 // the loop symbolically to determine when the condition gets a value of 7922 // "ExitWhen". 7923 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7924 const DataLayout &DL = getDataLayout(); 7925 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7926 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7927 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7928 7929 // Couldn't symbolically evaluate. 7930 if (!CondVal) return getCouldNotCompute(); 7931 7932 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7933 ++NumBruteForceTripCountsComputed; 7934 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7935 } 7936 7937 // Update all the PHI nodes for the next iteration. 7938 DenseMap<Instruction *, Constant *> NextIterVals; 7939 7940 // Create a list of which PHIs we need to compute. We want to do this before 7941 // calling EvaluateExpression on them because that may invalidate iterators 7942 // into CurrentIterVals. 7943 SmallVector<PHINode *, 8> PHIsToCompute; 7944 for (const auto &I : CurrentIterVals) { 7945 PHINode *PHI = dyn_cast<PHINode>(I.first); 7946 if (!PHI || PHI->getParent() != Header) continue; 7947 PHIsToCompute.push_back(PHI); 7948 } 7949 for (PHINode *PHI : PHIsToCompute) { 7950 Constant *&NextPHI = NextIterVals[PHI]; 7951 if (NextPHI) continue; // Already computed! 7952 7953 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7954 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7955 } 7956 CurrentIterVals.swap(NextIterVals); 7957 } 7958 7959 // Too many iterations were needed to evaluate. 7960 return getCouldNotCompute(); 7961 } 7962 7963 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 7964 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 7965 ValuesAtScopes[V]; 7966 // Check to see if we've folded this expression at this loop before. 7967 for (auto &LS : Values) 7968 if (LS.first == L) 7969 return LS.second ? LS.second : V; 7970 7971 Values.emplace_back(L, nullptr); 7972 7973 // Otherwise compute it. 7974 const SCEV *C = computeSCEVAtScope(V, L); 7975 for (auto &LS : reverse(ValuesAtScopes[V])) 7976 if (LS.first == L) { 7977 LS.second = C; 7978 break; 7979 } 7980 return C; 7981 } 7982 7983 /// This builds up a Constant using the ConstantExpr interface. That way, we 7984 /// will return Constants for objects which aren't represented by a 7985 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 7986 /// Returns NULL if the SCEV isn't representable as a Constant. 7987 static Constant *BuildConstantFromSCEV(const SCEV *V) { 7988 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 7989 case scCouldNotCompute: 7990 case scAddRecExpr: 7991 break; 7992 case scConstant: 7993 return cast<SCEVConstant>(V)->getValue(); 7994 case scUnknown: 7995 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 7996 case scSignExtend: { 7997 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 7998 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 7999 return ConstantExpr::getSExt(CastOp, SS->getType()); 8000 break; 8001 } 8002 case scZeroExtend: { 8003 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8004 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8005 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8006 break; 8007 } 8008 case scTruncate: { 8009 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8010 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8011 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8012 break; 8013 } 8014 case scAddExpr: { 8015 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8016 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8017 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8018 unsigned AS = PTy->getAddressSpace(); 8019 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8020 C = ConstantExpr::getBitCast(C, DestPtrTy); 8021 } 8022 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8023 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8024 if (!C2) return nullptr; 8025 8026 // First pointer! 8027 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8028 unsigned AS = C2->getType()->getPointerAddressSpace(); 8029 std::swap(C, C2); 8030 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8031 // The offsets have been converted to bytes. We can add bytes to an 8032 // i8* by GEP with the byte count in the first index. 8033 C = ConstantExpr::getBitCast(C, DestPtrTy); 8034 } 8035 8036 // Don't bother trying to sum two pointers. We probably can't 8037 // statically compute a load that results from it anyway. 8038 if (C2->getType()->isPointerTy()) 8039 return nullptr; 8040 8041 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8042 if (PTy->getElementType()->isStructTy()) 8043 C2 = ConstantExpr::getIntegerCast( 8044 C2, Type::getInt32Ty(C->getContext()), true); 8045 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8046 } else 8047 C = ConstantExpr::getAdd(C, C2); 8048 } 8049 return C; 8050 } 8051 break; 8052 } 8053 case scMulExpr: { 8054 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8055 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8056 // Don't bother with pointers at all. 8057 if (C->getType()->isPointerTy()) return nullptr; 8058 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8059 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8060 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8061 C = ConstantExpr::getMul(C, C2); 8062 } 8063 return C; 8064 } 8065 break; 8066 } 8067 case scUDivExpr: { 8068 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8069 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8070 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8071 if (LHS->getType() == RHS->getType()) 8072 return ConstantExpr::getUDiv(LHS, RHS); 8073 break; 8074 } 8075 case scSMaxExpr: 8076 case scUMaxExpr: 8077 break; // TODO: smax, umax. 8078 } 8079 return nullptr; 8080 } 8081 8082 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8083 if (isa<SCEVConstant>(V)) return V; 8084 8085 // If this instruction is evolved from a constant-evolving PHI, compute the 8086 // exit value from the loop without using SCEVs. 8087 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8088 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8089 const Loop *LI = this->LI[I->getParent()]; 8090 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 8091 if (PHINode *PN = dyn_cast<PHINode>(I)) 8092 if (PN->getParent() == LI->getHeader()) { 8093 // Okay, there is no closed form solution for the PHI node. Check 8094 // to see if the loop that contains it has a known backedge-taken 8095 // count. If so, we may be able to force computation of the exit 8096 // value. 8097 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8098 if (const SCEVConstant *BTCC = 8099 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8100 8101 // This trivial case can show up in some degenerate cases where 8102 // the incoming IR has not yet been fully simplified. 8103 if (BTCC->getValue()->isZero()) { 8104 Value *InitValue = nullptr; 8105 bool MultipleInitValues = false; 8106 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8107 if (!LI->contains(PN->getIncomingBlock(i))) { 8108 if (!InitValue) 8109 InitValue = PN->getIncomingValue(i); 8110 else if (InitValue != PN->getIncomingValue(i)) { 8111 MultipleInitValues = true; 8112 break; 8113 } 8114 } 8115 if (!MultipleInitValues && InitValue) 8116 return getSCEV(InitValue); 8117 } 8118 } 8119 // Okay, we know how many times the containing loop executes. If 8120 // this is a constant evolving PHI node, get the final value at 8121 // the specified iteration number. 8122 Constant *RV = 8123 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8124 if (RV) return getSCEV(RV); 8125 } 8126 } 8127 8128 // Okay, this is an expression that we cannot symbolically evaluate 8129 // into a SCEV. Check to see if it's possible to symbolically evaluate 8130 // the arguments into constants, and if so, try to constant propagate the 8131 // result. This is particularly useful for computing loop exit values. 8132 if (CanConstantFold(I)) { 8133 SmallVector<Constant *, 4> Operands; 8134 bool MadeImprovement = false; 8135 for (Value *Op : I->operands()) { 8136 if (Constant *C = dyn_cast<Constant>(Op)) { 8137 Operands.push_back(C); 8138 continue; 8139 } 8140 8141 // If any of the operands is non-constant and if they are 8142 // non-integer and non-pointer, don't even try to analyze them 8143 // with scev techniques. 8144 if (!isSCEVable(Op->getType())) 8145 return V; 8146 8147 const SCEV *OrigV = getSCEV(Op); 8148 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8149 MadeImprovement |= OrigV != OpV; 8150 8151 Constant *C = BuildConstantFromSCEV(OpV); 8152 if (!C) return V; 8153 if (C->getType() != Op->getType()) 8154 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8155 Op->getType(), 8156 false), 8157 C, Op->getType()); 8158 Operands.push_back(C); 8159 } 8160 8161 // Check to see if getSCEVAtScope actually made an improvement. 8162 if (MadeImprovement) { 8163 Constant *C = nullptr; 8164 const DataLayout &DL = getDataLayout(); 8165 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8166 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8167 Operands[1], DL, &TLI); 8168 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8169 if (!LI->isVolatile()) 8170 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8171 } else 8172 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8173 if (!C) return V; 8174 return getSCEV(C); 8175 } 8176 } 8177 } 8178 8179 // This is some other type of SCEVUnknown, just return it. 8180 return V; 8181 } 8182 8183 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8184 // Avoid performing the look-up in the common case where the specified 8185 // expression has no loop-variant portions. 8186 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8187 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8188 if (OpAtScope != Comm->getOperand(i)) { 8189 // Okay, at least one of these operands is loop variant but might be 8190 // foldable. Build a new instance of the folded commutative expression. 8191 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8192 Comm->op_begin()+i); 8193 NewOps.push_back(OpAtScope); 8194 8195 for (++i; i != e; ++i) { 8196 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8197 NewOps.push_back(OpAtScope); 8198 } 8199 if (isa<SCEVAddExpr>(Comm)) 8200 return getAddExpr(NewOps); 8201 if (isa<SCEVMulExpr>(Comm)) 8202 return getMulExpr(NewOps); 8203 if (isa<SCEVSMaxExpr>(Comm)) 8204 return getSMaxExpr(NewOps); 8205 if (isa<SCEVUMaxExpr>(Comm)) 8206 return getUMaxExpr(NewOps); 8207 llvm_unreachable("Unknown commutative SCEV type!"); 8208 } 8209 } 8210 // If we got here, all operands are loop invariant. 8211 return Comm; 8212 } 8213 8214 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8215 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8216 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8217 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8218 return Div; // must be loop invariant 8219 return getUDivExpr(LHS, RHS); 8220 } 8221 8222 // If this is a loop recurrence for a loop that does not contain L, then we 8223 // are dealing with the final value computed by the loop. 8224 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8225 // First, attempt to evaluate each operand. 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 = AddRec->getNumOperands(); i != e; ++i) { 8229 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8230 if (OpAtScope == AddRec->getOperand(i)) 8231 continue; 8232 8233 // Okay, at least one of these operands is loop variant but might be 8234 // foldable. Build a new instance of the folded commutative expression. 8235 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8236 AddRec->op_begin()+i); 8237 NewOps.push_back(OpAtScope); 8238 for (++i; i != e; ++i) 8239 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8240 8241 const SCEV *FoldedRec = 8242 getAddRecExpr(NewOps, AddRec->getLoop(), 8243 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8244 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8245 // The addrec may be folded to a nonrecurrence, for example, if the 8246 // induction variable is multiplied by zero after constant folding. Go 8247 // ahead and return the folded value. 8248 if (!AddRec) 8249 return FoldedRec; 8250 break; 8251 } 8252 8253 // If the scope is outside the addrec's loop, evaluate it by using the 8254 // loop exit value of the addrec. 8255 if (!AddRec->getLoop()->contains(L)) { 8256 // To evaluate this recurrence, we need to know how many times the AddRec 8257 // loop iterates. Compute this now. 8258 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8259 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8260 8261 // Then, evaluate the AddRec. 8262 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8263 } 8264 8265 return AddRec; 8266 } 8267 8268 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8269 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8270 if (Op == Cast->getOperand()) 8271 return Cast; // must be loop invariant 8272 return getZeroExtendExpr(Op, Cast->getType()); 8273 } 8274 8275 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8276 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8277 if (Op == Cast->getOperand()) 8278 return Cast; // must be loop invariant 8279 return getSignExtendExpr(Op, Cast->getType()); 8280 } 8281 8282 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8283 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8284 if (Op == Cast->getOperand()) 8285 return Cast; // must be loop invariant 8286 return getTruncateExpr(Op, Cast->getType()); 8287 } 8288 8289 llvm_unreachable("Unknown SCEV type!"); 8290 } 8291 8292 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8293 return getSCEVAtScope(getSCEV(V), L); 8294 } 8295 8296 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8297 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8298 return stripInjectiveFunctions(ZExt->getOperand()); 8299 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8300 return stripInjectiveFunctions(SExt->getOperand()); 8301 return S; 8302 } 8303 8304 /// Finds the minimum unsigned root of the following equation: 8305 /// 8306 /// A * X = B (mod N) 8307 /// 8308 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8309 /// A and B isn't important. 8310 /// 8311 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8312 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8313 ScalarEvolution &SE) { 8314 uint32_t BW = A.getBitWidth(); 8315 assert(BW == SE.getTypeSizeInBits(B->getType())); 8316 assert(A != 0 && "A must be non-zero."); 8317 8318 // 1. D = gcd(A, N) 8319 // 8320 // The gcd of A and N may have only one prime factor: 2. The number of 8321 // trailing zeros in A is its multiplicity 8322 uint32_t Mult2 = A.countTrailingZeros(); 8323 // D = 2^Mult2 8324 8325 // 2. Check if B is divisible by D. 8326 // 8327 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8328 // is not less than multiplicity of this prime factor for D. 8329 if (SE.GetMinTrailingZeros(B) < Mult2) 8330 return SE.getCouldNotCompute(); 8331 8332 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8333 // modulo (N / D). 8334 // 8335 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8336 // (N / D) in general. The inverse itself always fits into BW bits, though, 8337 // so we immediately truncate it. 8338 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8339 APInt Mod(BW + 1, 0); 8340 Mod.setBit(BW - Mult2); // Mod = N / D 8341 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8342 8343 // 4. Compute the minimum unsigned root of the equation: 8344 // I * (B / D) mod (N / D) 8345 // To simplify the computation, we factor out the divide by D: 8346 // (I * B mod N) / D 8347 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8348 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8349 } 8350 8351 /// For a given quadratic addrec, generate coefficients of the corresponding 8352 /// quadratic equation, multiplied by a common value to ensure that they are 8353 /// integers. 8354 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8355 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8356 /// were multiplied by, and BitWidth is the bit width of the original addrec 8357 /// coefficients. 8358 /// This function returns None if the addrec coefficients are not compile- 8359 /// time constants. 8360 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8361 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8362 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8363 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8364 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8365 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8366 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8367 << *AddRec << '\n'); 8368 8369 // We currently can only solve this if the coefficients are constants. 8370 if (!LC || !MC || !NC) { 8371 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8372 return None; 8373 } 8374 8375 APInt L = LC->getAPInt(); 8376 APInt M = MC->getAPInt(); 8377 APInt N = NC->getAPInt(); 8378 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8379 8380 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8381 unsigned NewWidth = BitWidth + 1; 8382 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8383 << BitWidth << '\n'); 8384 // The sign-extension (as opposed to a zero-extension) here matches the 8385 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8386 N = N.sext(NewWidth); 8387 M = M.sext(NewWidth); 8388 L = L.sext(NewWidth); 8389 8390 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8391 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8392 // L+M, L+2M+N, L+3M+3N, ... 8393 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8394 // 8395 // The equation Acc = 0 is then 8396 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8397 // In a quadratic form it becomes: 8398 // N n^2 + (2M-N) n + 2L = 0. 8399 8400 APInt A = N; 8401 APInt B = 2 * M - A; 8402 APInt C = 2 * L; 8403 APInt T = APInt(NewWidth, 2); 8404 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8405 << "x + " << C << ", coeff bw: " << NewWidth 8406 << ", multiplied by " << T << '\n'); 8407 return std::make_tuple(A, B, C, T, BitWidth); 8408 } 8409 8410 /// Helper function to compare optional APInts: 8411 /// (a) if X and Y both exist, return min(X, Y), 8412 /// (b) if neither X nor Y exist, return None, 8413 /// (c) if exactly one of X and Y exists, return that value. 8414 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8415 if (X.hasValue() && Y.hasValue()) { 8416 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8417 APInt XW = X->sextOrSelf(W); 8418 APInt YW = Y->sextOrSelf(W); 8419 return XW.slt(YW) ? *X : *Y; 8420 } 8421 if (!X.hasValue() && !Y.hasValue()) 8422 return None; 8423 return X.hasValue() ? *X : *Y; 8424 } 8425 8426 /// Helper function to truncate an optional APInt to a given BitWidth. 8427 /// When solving addrec-related equations, it is preferable to return a value 8428 /// that has the same bit width as the original addrec's coefficients. If the 8429 /// solution fits in the original bit width, truncate it (except for i1). 8430 /// Returning a value of a different bit width may inhibit some optimizations. 8431 /// 8432 /// In general, a solution to a quadratic equation generated from an addrec 8433 /// may require BW+1 bits, where BW is the bit width of the addrec's 8434 /// coefficients. The reason is that the coefficients of the quadratic 8435 /// equation are BW+1 bits wide (to avoid truncation when converting from 8436 /// the addrec to the equation). 8437 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8438 if (!X.hasValue()) 8439 return None; 8440 unsigned W = X->getBitWidth(); 8441 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8442 return X->trunc(BitWidth); 8443 return X; 8444 } 8445 8446 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8447 /// iterations. The values L, M, N are assumed to be signed, and they 8448 /// should all have the same bit widths. 8449 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8450 /// where BW is the bit width of the addrec's coefficients. 8451 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8452 /// returned as such, otherwise the bit width of the returned value may 8453 /// be greater than BW. 8454 /// 8455 /// This function returns None if 8456 /// (a) the addrec coefficients are not constant, or 8457 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8458 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8459 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8460 static Optional<APInt> 8461 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8462 APInt A, B, C, M; 8463 unsigned BitWidth; 8464 auto T = GetQuadraticEquation(AddRec); 8465 if (!T.hasValue()) 8466 return None; 8467 8468 std::tie(A, B, C, M, BitWidth) = *T; 8469 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8470 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8471 if (!X.hasValue()) 8472 return None; 8473 8474 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8475 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8476 if (!V->isZero()) 8477 return None; 8478 8479 return TruncIfPossible(X, BitWidth); 8480 } 8481 8482 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8483 /// iterations. The values M, N are assumed to be signed, and they 8484 /// should all have the same bit widths. 8485 /// Find the least n such that c(n) does not belong to the given range, 8486 /// while c(n-1) does. 8487 /// 8488 /// This function returns None if 8489 /// (a) the addrec coefficients are not constant, or 8490 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8491 /// bounds of the range. 8492 static Optional<APInt> 8493 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8494 const ConstantRange &Range, ScalarEvolution &SE) { 8495 assert(AddRec->getOperand(0)->isZero() && 8496 "Starting value of addrec should be 0"); 8497 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8498 << Range << ", addrec " << *AddRec << '\n'); 8499 // This case is handled in getNumIterationsInRange. Here we can assume that 8500 // we start in the range. 8501 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8502 "Addrec's initial value should be in range"); 8503 8504 APInt A, B, C, M; 8505 unsigned BitWidth; 8506 auto T = GetQuadraticEquation(AddRec); 8507 if (!T.hasValue()) 8508 return None; 8509 8510 // Be careful about the return value: there can be two reasons for not 8511 // returning an actual number. First, if no solutions to the equations 8512 // were found, and second, if the solutions don't leave the given range. 8513 // The first case means that the actual solution is "unknown", the second 8514 // means that it's known, but not valid. If the solution is unknown, we 8515 // cannot make any conclusions. 8516 // Return a pair: the optional solution and a flag indicating if the 8517 // solution was found. 8518 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8519 // Solve for signed overflow and unsigned overflow, pick the lower 8520 // solution. 8521 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8522 << Bound << " (before multiplying by " << M << ")\n"); 8523 Bound *= M; // The quadratic equation multiplier. 8524 8525 Optional<APInt> SO = None; 8526 if (BitWidth > 1) { 8527 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8528 "signed overflow\n"); 8529 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8530 } 8531 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8532 "unsigned overflow\n"); 8533 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8534 BitWidth+1); 8535 8536 auto LeavesRange = [&] (const APInt &X) { 8537 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8538 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8539 if (Range.contains(V0->getValue())) 8540 return false; 8541 // X should be at least 1, so X-1 is non-negative. 8542 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8543 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8544 if (Range.contains(V1->getValue())) 8545 return true; 8546 return false; 8547 }; 8548 8549 // If SolveQuadraticEquationWrap returns None, it means that there can 8550 // be a solution, but the function failed to find it. We cannot treat it 8551 // as "no solution". 8552 if (!SO.hasValue() || !UO.hasValue()) 8553 return { None, false }; 8554 8555 // Check the smaller value first to see if it leaves the range. 8556 // At this point, both SO and UO must have values. 8557 Optional<APInt> Min = MinOptional(SO, UO); 8558 if (LeavesRange(*Min)) 8559 return { Min, true }; 8560 Optional<APInt> Max = Min == SO ? UO : SO; 8561 if (LeavesRange(*Max)) 8562 return { Max, true }; 8563 8564 // Solutions were found, but were eliminated, hence the "true". 8565 return { None, true }; 8566 }; 8567 8568 std::tie(A, B, C, M, BitWidth) = *T; 8569 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8570 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8571 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8572 auto SL = SolveForBoundary(Lower); 8573 auto SU = SolveForBoundary(Upper); 8574 // If any of the solutions was unknown, no meaninigful conclusions can 8575 // be made. 8576 if (!SL.second || !SU.second) 8577 return None; 8578 8579 // Claim: The correct solution is not some value between Min and Max. 8580 // 8581 // Justification: Assuming that Min and Max are different values, one of 8582 // them is when the first signed overflow happens, the other is when the 8583 // first unsigned overflow happens. Crossing the range boundary is only 8584 // possible via an overflow (treating 0 as a special case of it, modeling 8585 // an overflow as crossing k*2^W for some k). 8586 // 8587 // The interesting case here is when Min was eliminated as an invalid 8588 // solution, but Max was not. The argument is that if there was another 8589 // overflow between Min and Max, it would also have been eliminated if 8590 // it was considered. 8591 // 8592 // For a given boundary, it is possible to have two overflows of the same 8593 // type (signed/unsigned) without having the other type in between: this 8594 // can happen when the vertex of the parabola is between the iterations 8595 // corresponding to the overflows. This is only possible when the two 8596 // overflows cross k*2^W for the same k. In such case, if the second one 8597 // left the range (and was the first one to do so), the first overflow 8598 // would have to enter the range, which would mean that either we had left 8599 // the range before or that we started outside of it. Both of these cases 8600 // are contradictions. 8601 // 8602 // Claim: In the case where SolveForBoundary returns None, the correct 8603 // solution is not some value between the Max for this boundary and the 8604 // Min of the other boundary. 8605 // 8606 // Justification: Assume that we had such Max_A and Min_B corresponding 8607 // to range boundaries A and B and such that Max_A < Min_B. If there was 8608 // a solution between Max_A and Min_B, it would have to be caused by an 8609 // overflow corresponding to either A or B. It cannot correspond to B, 8610 // since Min_B is the first occurrence of such an overflow. If it 8611 // corresponded to A, it would have to be either a signed or an unsigned 8612 // overflow that is larger than both eliminated overflows for A. But 8613 // between the eliminated overflows and this overflow, the values would 8614 // cover the entire value space, thus crossing the other boundary, which 8615 // is a contradiction. 8616 8617 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8618 } 8619 8620 ScalarEvolution::ExitLimit 8621 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8622 bool AllowPredicates) { 8623 8624 // This is only used for loops with a "x != y" exit test. The exit condition 8625 // is now expressed as a single expression, V = x-y. So the exit test is 8626 // effectively V != 0. We know and take advantage of the fact that this 8627 // expression only being used in a comparison by zero context. 8628 8629 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8630 // If the value is a constant 8631 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8632 // If the value is already zero, the branch will execute zero times. 8633 if (C->getValue()->isZero()) return C; 8634 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8635 } 8636 8637 const SCEVAddRecExpr *AddRec = 8638 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8639 8640 if (!AddRec && AllowPredicates) 8641 // Try to make this an AddRec using runtime tests, in the first X 8642 // iterations of this loop, where X is the SCEV expression found by the 8643 // algorithm below. 8644 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8645 8646 if (!AddRec || AddRec->getLoop() != L) 8647 return getCouldNotCompute(); 8648 8649 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8650 // the quadratic equation to solve it. 8651 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8652 // We can only use this value if the chrec ends up with an exact zero 8653 // value at this index. When solving for "X*X != 5", for example, we 8654 // should not accept a root of 2. 8655 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8656 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8657 return ExitLimit(R, R, false, Predicates); 8658 } 8659 return getCouldNotCompute(); 8660 } 8661 8662 // Otherwise we can only handle this if it is affine. 8663 if (!AddRec->isAffine()) 8664 return getCouldNotCompute(); 8665 8666 // If this is an affine expression, the execution count of this branch is 8667 // the minimum unsigned root of the following equation: 8668 // 8669 // Start + Step*N = 0 (mod 2^BW) 8670 // 8671 // equivalent to: 8672 // 8673 // Step*N = -Start (mod 2^BW) 8674 // 8675 // where BW is the common bit width of Start and Step. 8676 8677 // Get the initial value for the loop. 8678 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8679 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8680 8681 // For now we handle only constant steps. 8682 // 8683 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8684 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8685 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8686 // We have not yet seen any such cases. 8687 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8688 if (!StepC || StepC->getValue()->isZero()) 8689 return getCouldNotCompute(); 8690 8691 // For positive steps (counting up until unsigned overflow): 8692 // N = -Start/Step (as unsigned) 8693 // For negative steps (counting down to zero): 8694 // N = Start/-Step 8695 // First compute the unsigned distance from zero in the direction of Step. 8696 bool CountDown = StepC->getAPInt().isNegative(); 8697 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8698 8699 // Handle unitary steps, which cannot wraparound. 8700 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8701 // N = Distance (as unsigned) 8702 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8703 APInt MaxBECount = getUnsignedRangeMax(Distance); 8704 8705 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8706 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8707 // case, and see if we can improve the bound. 8708 // 8709 // Explicitly handling this here is necessary because getUnsignedRange 8710 // isn't context-sensitive; it doesn't know that we only care about the 8711 // range inside the loop. 8712 const SCEV *Zero = getZero(Distance->getType()); 8713 const SCEV *One = getOne(Distance->getType()); 8714 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8715 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8716 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8717 // as "unsigned_max(Distance + 1) - 1". 8718 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8719 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8720 } 8721 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8722 } 8723 8724 // If the condition controls loop exit (the loop exits only if the expression 8725 // is true) and the addition is no-wrap we can use unsigned divide to 8726 // compute the backedge count. In this case, the step may not divide the 8727 // distance, but we don't care because if the condition is "missed" the loop 8728 // will have undefined behavior due to wrapping. 8729 if (ControlsExit && AddRec->hasNoSelfWrap() && 8730 loopHasNoAbnormalExits(AddRec->getLoop())) { 8731 const SCEV *Exact = 8732 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8733 const SCEV *Max = 8734 Exact == getCouldNotCompute() 8735 ? Exact 8736 : getConstant(getUnsignedRangeMax(Exact)); 8737 return ExitLimit(Exact, Max, false, Predicates); 8738 } 8739 8740 // Solve the general equation. 8741 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8742 getNegativeSCEV(Start), *this); 8743 const SCEV *M = E == getCouldNotCompute() 8744 ? E 8745 : getConstant(getUnsignedRangeMax(E)); 8746 return ExitLimit(E, M, false, Predicates); 8747 } 8748 8749 ScalarEvolution::ExitLimit 8750 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8751 // Loops that look like: while (X == 0) are very strange indeed. We don't 8752 // handle them yet except for the trivial case. This could be expanded in the 8753 // future as needed. 8754 8755 // If the value is a constant, check to see if it is known to be non-zero 8756 // already. If so, the backedge will execute zero times. 8757 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8758 if (!C->getValue()->isZero()) 8759 return getZero(C->getType()); 8760 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8761 } 8762 8763 // We could implement others, but I really doubt anyone writes loops like 8764 // this, and if they did, they would already be constant folded. 8765 return getCouldNotCompute(); 8766 } 8767 8768 std::pair<BasicBlock *, BasicBlock *> 8769 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8770 // If the block has a unique predecessor, then there is no path from the 8771 // predecessor to the block that does not go through the direct edge 8772 // from the predecessor to the block. 8773 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8774 return {Pred, BB}; 8775 8776 // A loop's header is defined to be a block that dominates the loop. 8777 // If the header has a unique predecessor outside the loop, it must be 8778 // a block that has exactly one successor that can reach the loop. 8779 if (Loop *L = LI.getLoopFor(BB)) 8780 return {L->getLoopPredecessor(), L->getHeader()}; 8781 8782 return {nullptr, nullptr}; 8783 } 8784 8785 /// SCEV structural equivalence is usually sufficient for testing whether two 8786 /// expressions are equal, however for the purposes of looking for a condition 8787 /// guarding a loop, it can be useful to be a little more general, since a 8788 /// front-end may have replicated the controlling expression. 8789 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8790 // Quick check to see if they are the same SCEV. 8791 if (A == B) return true; 8792 8793 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8794 // Not all instructions that are "identical" compute the same value. For 8795 // instance, two distinct alloca instructions allocating the same type are 8796 // identical and do not read memory; but compute distinct values. 8797 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8798 }; 8799 8800 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8801 // two different instructions with the same value. Check for this case. 8802 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8803 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8804 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8805 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8806 if (ComputesEqualValues(AI, BI)) 8807 return true; 8808 8809 // Otherwise assume they may have a different value. 8810 return false; 8811 } 8812 8813 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8814 const SCEV *&LHS, const SCEV *&RHS, 8815 unsigned Depth) { 8816 bool Changed = false; 8817 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8818 // '0 != 0'. 8819 auto TrivialCase = [&](bool TriviallyTrue) { 8820 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8821 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8822 return true; 8823 }; 8824 // If we hit the max recursion limit bail out. 8825 if (Depth >= 3) 8826 return false; 8827 8828 // Canonicalize a constant to the right side. 8829 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8830 // Check for both operands constant. 8831 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8832 if (ConstantExpr::getICmp(Pred, 8833 LHSC->getValue(), 8834 RHSC->getValue())->isNullValue()) 8835 return TrivialCase(false); 8836 else 8837 return TrivialCase(true); 8838 } 8839 // Otherwise swap the operands to put the constant on the right. 8840 std::swap(LHS, RHS); 8841 Pred = ICmpInst::getSwappedPredicate(Pred); 8842 Changed = true; 8843 } 8844 8845 // If we're comparing an addrec with a value which is loop-invariant in the 8846 // addrec's loop, put the addrec on the left. Also make a dominance check, 8847 // as both operands could be addrecs loop-invariant in each other's loop. 8848 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8849 const Loop *L = AR->getLoop(); 8850 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8851 std::swap(LHS, RHS); 8852 Pred = ICmpInst::getSwappedPredicate(Pred); 8853 Changed = true; 8854 } 8855 } 8856 8857 // If there's a constant operand, canonicalize comparisons with boundary 8858 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8859 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8860 const APInt &RA = RC->getAPInt(); 8861 8862 bool SimplifiedByConstantRange = false; 8863 8864 if (!ICmpInst::isEquality(Pred)) { 8865 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8866 if (ExactCR.isFullSet()) 8867 return TrivialCase(true); 8868 else if (ExactCR.isEmptySet()) 8869 return TrivialCase(false); 8870 8871 APInt NewRHS; 8872 CmpInst::Predicate NewPred; 8873 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8874 ICmpInst::isEquality(NewPred)) { 8875 // We were able to convert an inequality to an equality. 8876 Pred = NewPred; 8877 RHS = getConstant(NewRHS); 8878 Changed = SimplifiedByConstantRange = true; 8879 } 8880 } 8881 8882 if (!SimplifiedByConstantRange) { 8883 switch (Pred) { 8884 default: 8885 break; 8886 case ICmpInst::ICMP_EQ: 8887 case ICmpInst::ICMP_NE: 8888 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8889 if (!RA) 8890 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8891 if (const SCEVMulExpr *ME = 8892 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8893 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8894 ME->getOperand(0)->isAllOnesValue()) { 8895 RHS = AE->getOperand(1); 8896 LHS = ME->getOperand(1); 8897 Changed = true; 8898 } 8899 break; 8900 8901 8902 // The "Should have been caught earlier!" messages refer to the fact 8903 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8904 // should have fired on the corresponding cases, and canonicalized the 8905 // check to trivial case. 8906 8907 case ICmpInst::ICMP_UGE: 8908 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8909 Pred = ICmpInst::ICMP_UGT; 8910 RHS = getConstant(RA - 1); 8911 Changed = true; 8912 break; 8913 case ICmpInst::ICMP_ULE: 8914 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8915 Pred = ICmpInst::ICMP_ULT; 8916 RHS = getConstant(RA + 1); 8917 Changed = true; 8918 break; 8919 case ICmpInst::ICMP_SGE: 8920 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8921 Pred = ICmpInst::ICMP_SGT; 8922 RHS = getConstant(RA - 1); 8923 Changed = true; 8924 break; 8925 case ICmpInst::ICMP_SLE: 8926 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8927 Pred = ICmpInst::ICMP_SLT; 8928 RHS = getConstant(RA + 1); 8929 Changed = true; 8930 break; 8931 } 8932 } 8933 } 8934 8935 // Check for obvious equality. 8936 if (HasSameValue(LHS, RHS)) { 8937 if (ICmpInst::isTrueWhenEqual(Pred)) 8938 return TrivialCase(true); 8939 if (ICmpInst::isFalseWhenEqual(Pred)) 8940 return TrivialCase(false); 8941 } 8942 8943 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8944 // adding or subtracting 1 from one of the operands. 8945 switch (Pred) { 8946 case ICmpInst::ICMP_SLE: 8947 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8948 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8949 SCEV::FlagNSW); 8950 Pred = ICmpInst::ICMP_SLT; 8951 Changed = true; 8952 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8953 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8954 SCEV::FlagNSW); 8955 Pred = ICmpInst::ICMP_SLT; 8956 Changed = true; 8957 } 8958 break; 8959 case ICmpInst::ICMP_SGE: 8960 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 8961 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 8962 SCEV::FlagNSW); 8963 Pred = ICmpInst::ICMP_SGT; 8964 Changed = true; 8965 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 8966 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8967 SCEV::FlagNSW); 8968 Pred = ICmpInst::ICMP_SGT; 8969 Changed = true; 8970 } 8971 break; 8972 case ICmpInst::ICMP_ULE: 8973 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 8974 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8975 SCEV::FlagNUW); 8976 Pred = ICmpInst::ICMP_ULT; 8977 Changed = true; 8978 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 8979 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 8980 Pred = ICmpInst::ICMP_ULT; 8981 Changed = true; 8982 } 8983 break; 8984 case ICmpInst::ICMP_UGE: 8985 if (!getUnsignedRangeMin(RHS).isMinValue()) { 8986 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 8987 Pred = ICmpInst::ICMP_UGT; 8988 Changed = true; 8989 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 8990 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8991 SCEV::FlagNUW); 8992 Pred = ICmpInst::ICMP_UGT; 8993 Changed = true; 8994 } 8995 break; 8996 default: 8997 break; 8998 } 8999 9000 // TODO: More simplifications are possible here. 9001 9002 // Recursively simplify until we either hit a recursion limit or nothing 9003 // changes. 9004 if (Changed) 9005 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9006 9007 return Changed; 9008 } 9009 9010 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9011 return getSignedRangeMax(S).isNegative(); 9012 } 9013 9014 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9015 return getSignedRangeMin(S).isStrictlyPositive(); 9016 } 9017 9018 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9019 return !getSignedRangeMin(S).isNegative(); 9020 } 9021 9022 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9023 return !getSignedRangeMax(S).isStrictlyPositive(); 9024 } 9025 9026 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9027 return isKnownNegative(S) || isKnownPositive(S); 9028 } 9029 9030 std::pair<const SCEV *, const SCEV *> 9031 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9032 // Compute SCEV on entry of loop L. 9033 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9034 if (Start == getCouldNotCompute()) 9035 return { Start, Start }; 9036 // Compute post increment SCEV for loop L. 9037 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9038 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9039 return { Start, PostInc }; 9040 } 9041 9042 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9043 const SCEV *LHS, const SCEV *RHS) { 9044 // First collect all loops. 9045 SmallPtrSet<const Loop *, 8> LoopsUsed; 9046 getUsedLoops(LHS, LoopsUsed); 9047 getUsedLoops(RHS, LoopsUsed); 9048 9049 if (LoopsUsed.empty()) 9050 return false; 9051 9052 // Domination relationship must be a linear order on collected loops. 9053 #ifndef NDEBUG 9054 for (auto *L1 : LoopsUsed) 9055 for (auto *L2 : LoopsUsed) 9056 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9057 DT.dominates(L2->getHeader(), L1->getHeader())) && 9058 "Domination relationship is not a linear order"); 9059 #endif 9060 9061 const Loop *MDL = 9062 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9063 [&](const Loop *L1, const Loop *L2) { 9064 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9065 }); 9066 9067 // Get init and post increment value for LHS. 9068 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9069 // if LHS contains unknown non-invariant SCEV then bail out. 9070 if (SplitLHS.first == getCouldNotCompute()) 9071 return false; 9072 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9073 // Get init and post increment value for RHS. 9074 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9075 // if RHS contains unknown non-invariant SCEV then bail out. 9076 if (SplitRHS.first == getCouldNotCompute()) 9077 return false; 9078 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9079 // It is possible that init SCEV contains an invariant load but it does 9080 // not dominate MDL and is not available at MDL loop entry, so we should 9081 // check it here. 9082 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9083 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9084 return false; 9085 9086 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 9087 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9088 SplitRHS.second); 9089 } 9090 9091 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9092 const SCEV *LHS, const SCEV *RHS) { 9093 // Canonicalize the inputs first. 9094 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9095 9096 if (isKnownViaInduction(Pred, LHS, RHS)) 9097 return true; 9098 9099 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9100 return true; 9101 9102 // Otherwise see what can be done with some simple reasoning. 9103 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9104 } 9105 9106 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9107 const SCEVAddRecExpr *LHS, 9108 const SCEV *RHS) { 9109 const Loop *L = LHS->getLoop(); 9110 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9111 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9112 } 9113 9114 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9115 ICmpInst::Predicate Pred, 9116 bool &Increasing) { 9117 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9118 9119 #ifndef NDEBUG 9120 // Verify an invariant: inverting the predicate should turn a monotonically 9121 // increasing change to a monotonically decreasing one, and vice versa. 9122 bool IncreasingSwapped; 9123 bool ResultSwapped = isMonotonicPredicateImpl( 9124 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9125 9126 assert(Result == ResultSwapped && "should be able to analyze both!"); 9127 if (ResultSwapped) 9128 assert(Increasing == !IncreasingSwapped && 9129 "monotonicity should flip as we flip the predicate"); 9130 #endif 9131 9132 return Result; 9133 } 9134 9135 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9136 ICmpInst::Predicate Pred, 9137 bool &Increasing) { 9138 9139 // A zero step value for LHS means the induction variable is essentially a 9140 // loop invariant value. We don't really depend on the predicate actually 9141 // flipping from false to true (for increasing predicates, and the other way 9142 // around for decreasing predicates), all we care about is that *if* the 9143 // predicate changes then it only changes from false to true. 9144 // 9145 // A zero step value in itself is not very useful, but there may be places 9146 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9147 // as general as possible. 9148 9149 switch (Pred) { 9150 default: 9151 return false; // Conservative answer 9152 9153 case ICmpInst::ICMP_UGT: 9154 case ICmpInst::ICMP_UGE: 9155 case ICmpInst::ICMP_ULT: 9156 case ICmpInst::ICMP_ULE: 9157 if (!LHS->hasNoUnsignedWrap()) 9158 return false; 9159 9160 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9161 return true; 9162 9163 case ICmpInst::ICMP_SGT: 9164 case ICmpInst::ICMP_SGE: 9165 case ICmpInst::ICMP_SLT: 9166 case ICmpInst::ICMP_SLE: { 9167 if (!LHS->hasNoSignedWrap()) 9168 return false; 9169 9170 const SCEV *Step = LHS->getStepRecurrence(*this); 9171 9172 if (isKnownNonNegative(Step)) { 9173 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9174 return true; 9175 } 9176 9177 if (isKnownNonPositive(Step)) { 9178 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9179 return true; 9180 } 9181 9182 return false; 9183 } 9184 9185 } 9186 9187 llvm_unreachable("switch has default clause!"); 9188 } 9189 9190 bool ScalarEvolution::isLoopInvariantPredicate( 9191 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9192 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9193 const SCEV *&InvariantRHS) { 9194 9195 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9196 if (!isLoopInvariant(RHS, L)) { 9197 if (!isLoopInvariant(LHS, L)) 9198 return false; 9199 9200 std::swap(LHS, RHS); 9201 Pred = ICmpInst::getSwappedPredicate(Pred); 9202 } 9203 9204 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9205 if (!ArLHS || ArLHS->getLoop() != L) 9206 return false; 9207 9208 bool Increasing; 9209 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9210 return false; 9211 9212 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9213 // true as the loop iterates, and the backedge is control dependent on 9214 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9215 // 9216 // * if the predicate was false in the first iteration then the predicate 9217 // is never evaluated again, since the loop exits without taking the 9218 // backedge. 9219 // * if the predicate was true in the first iteration then it will 9220 // continue to be true for all future iterations since it is 9221 // monotonically increasing. 9222 // 9223 // For both the above possibilities, we can replace the loop varying 9224 // predicate with its value on the first iteration of the loop (which is 9225 // loop invariant). 9226 // 9227 // A similar reasoning applies for a monotonically decreasing predicate, by 9228 // replacing true with false and false with true in the above two bullets. 9229 9230 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9231 9232 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9233 return false; 9234 9235 InvariantPred = Pred; 9236 InvariantLHS = ArLHS->getStart(); 9237 InvariantRHS = RHS; 9238 return true; 9239 } 9240 9241 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9242 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9243 if (HasSameValue(LHS, RHS)) 9244 return ICmpInst::isTrueWhenEqual(Pred); 9245 9246 // This code is split out from isKnownPredicate because it is called from 9247 // within isLoopEntryGuardedByCond. 9248 9249 auto CheckRanges = 9250 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9251 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9252 .contains(RangeLHS); 9253 }; 9254 9255 // The check at the top of the function catches the case where the values are 9256 // known to be equal. 9257 if (Pred == CmpInst::ICMP_EQ) 9258 return false; 9259 9260 if (Pred == CmpInst::ICMP_NE) 9261 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9262 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9263 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9264 9265 if (CmpInst::isSigned(Pred)) 9266 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9267 9268 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9269 } 9270 9271 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9272 const SCEV *LHS, 9273 const SCEV *RHS) { 9274 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9275 // Return Y via OutY. 9276 auto MatchBinaryAddToConst = 9277 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9278 SCEV::NoWrapFlags ExpectedFlags) { 9279 const SCEV *NonConstOp, *ConstOp; 9280 SCEV::NoWrapFlags FlagsPresent; 9281 9282 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9283 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9284 return false; 9285 9286 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9287 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9288 }; 9289 9290 APInt C; 9291 9292 switch (Pred) { 9293 default: 9294 break; 9295 9296 case ICmpInst::ICMP_SGE: 9297 std::swap(LHS, RHS); 9298 LLVM_FALLTHROUGH; 9299 case ICmpInst::ICMP_SLE: 9300 // X s<= (X + C)<nsw> if C >= 0 9301 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9302 return true; 9303 9304 // (X + C)<nsw> s<= X if C <= 0 9305 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9306 !C.isStrictlyPositive()) 9307 return true; 9308 break; 9309 9310 case ICmpInst::ICMP_SGT: 9311 std::swap(LHS, RHS); 9312 LLVM_FALLTHROUGH; 9313 case ICmpInst::ICMP_SLT: 9314 // X s< (X + C)<nsw> if C > 0 9315 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9316 C.isStrictlyPositive()) 9317 return true; 9318 9319 // (X + C)<nsw> s< X if C < 0 9320 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9321 return true; 9322 break; 9323 } 9324 9325 return false; 9326 } 9327 9328 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9329 const SCEV *LHS, 9330 const SCEV *RHS) { 9331 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9332 return false; 9333 9334 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9335 // the stack can result in exponential time complexity. 9336 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9337 9338 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9339 // 9340 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9341 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9342 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9343 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9344 // use isKnownPredicate later if needed. 9345 return isKnownNonNegative(RHS) && 9346 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9347 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9348 } 9349 9350 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9351 ICmpInst::Predicate Pred, 9352 const SCEV *LHS, const SCEV *RHS) { 9353 // No need to even try if we know the module has no guards. 9354 if (!HasGuards) 9355 return false; 9356 9357 return any_of(*BB, [&](Instruction &I) { 9358 using namespace llvm::PatternMatch; 9359 9360 Value *Condition; 9361 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9362 m_Value(Condition))) && 9363 isImpliedCond(Pred, LHS, RHS, Condition, false); 9364 }); 9365 } 9366 9367 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9368 /// protected by a conditional between LHS and RHS. This is used to 9369 /// to eliminate casts. 9370 bool 9371 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9372 ICmpInst::Predicate Pred, 9373 const SCEV *LHS, const SCEV *RHS) { 9374 // Interpret a null as meaning no loop, where there is obviously no guard 9375 // (interprocedural conditions notwithstanding). 9376 if (!L) return true; 9377 9378 if (VerifyIR) 9379 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9380 "This cannot be done on broken IR!"); 9381 9382 9383 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9384 return true; 9385 9386 BasicBlock *Latch = L->getLoopLatch(); 9387 if (!Latch) 9388 return false; 9389 9390 BranchInst *LoopContinuePredicate = 9391 dyn_cast<BranchInst>(Latch->getTerminator()); 9392 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9393 isImpliedCond(Pred, LHS, RHS, 9394 LoopContinuePredicate->getCondition(), 9395 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9396 return true; 9397 9398 // We don't want more than one activation of the following loops on the stack 9399 // -- that can lead to O(n!) time complexity. 9400 if (WalkingBEDominatingConds) 9401 return false; 9402 9403 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9404 9405 // See if we can exploit a trip count to prove the predicate. 9406 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9407 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9408 if (LatchBECount != getCouldNotCompute()) { 9409 // We know that Latch branches back to the loop header exactly 9410 // LatchBECount times. This means the backdege condition at Latch is 9411 // equivalent to "{0,+,1} u< LatchBECount". 9412 Type *Ty = LatchBECount->getType(); 9413 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9414 const SCEV *LoopCounter = 9415 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9416 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9417 LatchBECount)) 9418 return true; 9419 } 9420 9421 // Check conditions due to any @llvm.assume intrinsics. 9422 for (auto &AssumeVH : AC.assumptions()) { 9423 if (!AssumeVH) 9424 continue; 9425 auto *CI = cast<CallInst>(AssumeVH); 9426 if (!DT.dominates(CI, Latch->getTerminator())) 9427 continue; 9428 9429 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9430 return true; 9431 } 9432 9433 // If the loop is not reachable from the entry block, we risk running into an 9434 // infinite loop as we walk up into the dom tree. These loops do not matter 9435 // anyway, so we just return a conservative answer when we see them. 9436 if (!DT.isReachableFromEntry(L->getHeader())) 9437 return false; 9438 9439 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9440 return true; 9441 9442 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9443 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9444 assert(DTN && "should reach the loop header before reaching the root!"); 9445 9446 BasicBlock *BB = DTN->getBlock(); 9447 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9448 return true; 9449 9450 BasicBlock *PBB = BB->getSinglePredecessor(); 9451 if (!PBB) 9452 continue; 9453 9454 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9455 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9456 continue; 9457 9458 Value *Condition = ContinuePredicate->getCondition(); 9459 9460 // If we have an edge `E` within the loop body that dominates the only 9461 // latch, the condition guarding `E` also guards the backedge. This 9462 // reasoning works only for loops with a single latch. 9463 9464 BasicBlockEdge DominatingEdge(PBB, BB); 9465 if (DominatingEdge.isSingleEdge()) { 9466 // We're constructively (and conservatively) enumerating edges within the 9467 // loop body that dominate the latch. The dominator tree better agree 9468 // with us on this: 9469 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9470 9471 if (isImpliedCond(Pred, LHS, RHS, Condition, 9472 BB != ContinuePredicate->getSuccessor(0))) 9473 return true; 9474 } 9475 } 9476 9477 return false; 9478 } 9479 9480 bool 9481 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9482 ICmpInst::Predicate Pred, 9483 const SCEV *LHS, const SCEV *RHS) { 9484 // Interpret a null as meaning no loop, where there is obviously no guard 9485 // (interprocedural conditions notwithstanding). 9486 if (!L) return false; 9487 9488 if (VerifyIR) 9489 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9490 "This cannot be done on broken IR!"); 9491 9492 // Both LHS and RHS must be available at loop entry. 9493 assert(isAvailableAtLoopEntry(LHS, L) && 9494 "LHS is not available at Loop Entry"); 9495 assert(isAvailableAtLoopEntry(RHS, L) && 9496 "RHS is not available at Loop Entry"); 9497 9498 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9499 return true; 9500 9501 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9502 // the facts (a >= b && a != b) separately. A typical situation is when the 9503 // non-strict comparison is known from ranges and non-equality is known from 9504 // dominating predicates. If we are proving strict comparison, we always try 9505 // to prove non-equality and non-strict comparison separately. 9506 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9507 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9508 bool ProvedNonStrictComparison = false; 9509 bool ProvedNonEquality = false; 9510 9511 if (ProvingStrictComparison) { 9512 ProvedNonStrictComparison = 9513 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9514 ProvedNonEquality = 9515 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9516 if (ProvedNonStrictComparison && ProvedNonEquality) 9517 return true; 9518 } 9519 9520 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9521 auto ProveViaGuard = [&](BasicBlock *Block) { 9522 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9523 return true; 9524 if (ProvingStrictComparison) { 9525 if (!ProvedNonStrictComparison) 9526 ProvedNonStrictComparison = 9527 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9528 if (!ProvedNonEquality) 9529 ProvedNonEquality = 9530 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9531 if (ProvedNonStrictComparison && ProvedNonEquality) 9532 return true; 9533 } 9534 return false; 9535 }; 9536 9537 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9538 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9539 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9540 return true; 9541 if (ProvingStrictComparison) { 9542 if (!ProvedNonStrictComparison) 9543 ProvedNonStrictComparison = 9544 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9545 if (!ProvedNonEquality) 9546 ProvedNonEquality = 9547 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9548 if (ProvedNonStrictComparison && ProvedNonEquality) 9549 return true; 9550 } 9551 return false; 9552 }; 9553 9554 // Starting at the loop predecessor, climb up the predecessor chain, as long 9555 // as there are predecessors that can be found that have unique successors 9556 // leading to the original header. 9557 for (std::pair<BasicBlock *, BasicBlock *> 9558 Pair(L->getLoopPredecessor(), L->getHeader()); 9559 Pair.first; 9560 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9561 9562 if (ProveViaGuard(Pair.first)) 9563 return true; 9564 9565 BranchInst *LoopEntryPredicate = 9566 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9567 if (!LoopEntryPredicate || 9568 LoopEntryPredicate->isUnconditional()) 9569 continue; 9570 9571 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9572 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9573 return true; 9574 } 9575 9576 // Check conditions due to any @llvm.assume intrinsics. 9577 for (auto &AssumeVH : AC.assumptions()) { 9578 if (!AssumeVH) 9579 continue; 9580 auto *CI = cast<CallInst>(AssumeVH); 9581 if (!DT.dominates(CI, L->getHeader())) 9582 continue; 9583 9584 if (ProveViaCond(CI->getArgOperand(0), false)) 9585 return true; 9586 } 9587 9588 return false; 9589 } 9590 9591 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9592 const SCEV *LHS, const SCEV *RHS, 9593 Value *FoundCondValue, 9594 bool Inverse) { 9595 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9596 return false; 9597 9598 auto ClearOnExit = 9599 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9600 9601 // Recursively handle And and Or conditions. 9602 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9603 if (BO->getOpcode() == Instruction::And) { 9604 if (!Inverse) 9605 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9606 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9607 } else if (BO->getOpcode() == Instruction::Or) { 9608 if (Inverse) 9609 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9610 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9611 } 9612 } 9613 9614 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9615 if (!ICI) return false; 9616 9617 // Now that we found a conditional branch that dominates the loop or controls 9618 // the loop latch. Check to see if it is the comparison we are looking for. 9619 ICmpInst::Predicate FoundPred; 9620 if (Inverse) 9621 FoundPred = ICI->getInversePredicate(); 9622 else 9623 FoundPred = ICI->getPredicate(); 9624 9625 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9626 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9627 9628 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9629 } 9630 9631 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9632 const SCEV *RHS, 9633 ICmpInst::Predicate FoundPred, 9634 const SCEV *FoundLHS, 9635 const SCEV *FoundRHS) { 9636 // Balance the types. 9637 if (getTypeSizeInBits(LHS->getType()) < 9638 getTypeSizeInBits(FoundLHS->getType())) { 9639 if (CmpInst::isSigned(Pred)) { 9640 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9641 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9642 } else { 9643 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9644 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9645 } 9646 } else if (getTypeSizeInBits(LHS->getType()) > 9647 getTypeSizeInBits(FoundLHS->getType())) { 9648 if (CmpInst::isSigned(FoundPred)) { 9649 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9650 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9651 } else { 9652 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9653 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9654 } 9655 } 9656 9657 // Canonicalize the query to match the way instcombine will have 9658 // canonicalized the comparison. 9659 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9660 if (LHS == RHS) 9661 return CmpInst::isTrueWhenEqual(Pred); 9662 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9663 if (FoundLHS == FoundRHS) 9664 return CmpInst::isFalseWhenEqual(FoundPred); 9665 9666 // Check to see if we can make the LHS or RHS match. 9667 if (LHS == FoundRHS || RHS == FoundLHS) { 9668 if (isa<SCEVConstant>(RHS)) { 9669 std::swap(FoundLHS, FoundRHS); 9670 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9671 } else { 9672 std::swap(LHS, RHS); 9673 Pred = ICmpInst::getSwappedPredicate(Pred); 9674 } 9675 } 9676 9677 // Check whether the found predicate is the same as the desired predicate. 9678 if (FoundPred == Pred) 9679 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9680 9681 // Check whether swapping the found predicate makes it the same as the 9682 // desired predicate. 9683 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9684 if (isa<SCEVConstant>(RHS)) 9685 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9686 else 9687 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9688 RHS, LHS, FoundLHS, FoundRHS); 9689 } 9690 9691 // Unsigned comparison is the same as signed comparison when both the operands 9692 // are non-negative. 9693 if (CmpInst::isUnsigned(FoundPred) && 9694 CmpInst::getSignedPredicate(FoundPred) == Pred && 9695 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9696 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9697 9698 // Check if we can make progress by sharpening ranges. 9699 if (FoundPred == ICmpInst::ICMP_NE && 9700 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9701 9702 const SCEVConstant *C = nullptr; 9703 const SCEV *V = nullptr; 9704 9705 if (isa<SCEVConstant>(FoundLHS)) { 9706 C = cast<SCEVConstant>(FoundLHS); 9707 V = FoundRHS; 9708 } else { 9709 C = cast<SCEVConstant>(FoundRHS); 9710 V = FoundLHS; 9711 } 9712 9713 // The guarding predicate tells us that C != V. If the known range 9714 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9715 // range we consider has to correspond to same signedness as the 9716 // predicate we're interested in folding. 9717 9718 APInt Min = ICmpInst::isSigned(Pred) ? 9719 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9720 9721 if (Min == C->getAPInt()) { 9722 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9723 // This is true even if (Min + 1) wraps around -- in case of 9724 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9725 9726 APInt SharperMin = Min + 1; 9727 9728 switch (Pred) { 9729 case ICmpInst::ICMP_SGE: 9730 case ICmpInst::ICMP_UGE: 9731 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9732 // RHS, we're done. 9733 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9734 getConstant(SharperMin))) 9735 return true; 9736 LLVM_FALLTHROUGH; 9737 9738 case ICmpInst::ICMP_SGT: 9739 case ICmpInst::ICMP_UGT: 9740 // We know from the range information that (V `Pred` Min || 9741 // V == Min). We know from the guarding condition that !(V 9742 // == Min). This gives us 9743 // 9744 // V `Pred` Min || V == Min && !(V == Min) 9745 // => V `Pred` Min 9746 // 9747 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9748 9749 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9750 return true; 9751 LLVM_FALLTHROUGH; 9752 9753 default: 9754 // No change 9755 break; 9756 } 9757 } 9758 } 9759 9760 // Check whether the actual condition is beyond sufficient. 9761 if (FoundPred == ICmpInst::ICMP_EQ) 9762 if (ICmpInst::isTrueWhenEqual(Pred)) 9763 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9764 return true; 9765 if (Pred == ICmpInst::ICMP_NE) 9766 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9767 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9768 return true; 9769 9770 // Otherwise assume the worst. 9771 return false; 9772 } 9773 9774 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9775 const SCEV *&L, const SCEV *&R, 9776 SCEV::NoWrapFlags &Flags) { 9777 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9778 if (!AE || AE->getNumOperands() != 2) 9779 return false; 9780 9781 L = AE->getOperand(0); 9782 R = AE->getOperand(1); 9783 Flags = AE->getNoWrapFlags(); 9784 return true; 9785 } 9786 9787 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9788 const SCEV *Less) { 9789 // We avoid subtracting expressions here because this function is usually 9790 // fairly deep in the call stack (i.e. is called many times). 9791 9792 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9793 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9794 const auto *MAR = cast<SCEVAddRecExpr>(More); 9795 9796 if (LAR->getLoop() != MAR->getLoop()) 9797 return None; 9798 9799 // We look at affine expressions only; not for correctness but to keep 9800 // getStepRecurrence cheap. 9801 if (!LAR->isAffine() || !MAR->isAffine()) 9802 return None; 9803 9804 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9805 return None; 9806 9807 Less = LAR->getStart(); 9808 More = MAR->getStart(); 9809 9810 // fall through 9811 } 9812 9813 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9814 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9815 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9816 return M - L; 9817 } 9818 9819 SCEV::NoWrapFlags Flags; 9820 const SCEV *LLess = nullptr, *RLess = nullptr; 9821 const SCEV *LMore = nullptr, *RMore = nullptr; 9822 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9823 // Compare (X + C1) vs X. 9824 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9825 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9826 if (RLess == More) 9827 return -(C1->getAPInt()); 9828 9829 // Compare X vs (X + C2). 9830 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9831 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9832 if (RMore == Less) 9833 return C2->getAPInt(); 9834 9835 // Compare (X + C1) vs (X + C2). 9836 if (C1 && C2 && RLess == RMore) 9837 return C2->getAPInt() - C1->getAPInt(); 9838 9839 return None; 9840 } 9841 9842 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9843 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9844 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9845 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9846 return false; 9847 9848 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9849 if (!AddRecLHS) 9850 return false; 9851 9852 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9853 if (!AddRecFoundLHS) 9854 return false; 9855 9856 // We'd like to let SCEV reason about control dependencies, so we constrain 9857 // both the inequalities to be about add recurrences on the same loop. This 9858 // way we can use isLoopEntryGuardedByCond later. 9859 9860 const Loop *L = AddRecFoundLHS->getLoop(); 9861 if (L != AddRecLHS->getLoop()) 9862 return false; 9863 9864 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9865 // 9866 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9867 // ... (2) 9868 // 9869 // Informal proof for (2), assuming (1) [*]: 9870 // 9871 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9872 // 9873 // Then 9874 // 9875 // FoundLHS s< FoundRHS s< INT_MIN - C 9876 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9877 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9878 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9879 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9880 // <=> FoundLHS + C s< FoundRHS + C 9881 // 9882 // [*]: (1) can be proved by ruling out overflow. 9883 // 9884 // [**]: This can be proved by analyzing all the four possibilities: 9885 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9886 // (A s>= 0, B s>= 0). 9887 // 9888 // Note: 9889 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9890 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9891 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9892 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9893 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9894 // C)". 9895 9896 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9897 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9898 if (!LDiff || !RDiff || *LDiff != *RDiff) 9899 return false; 9900 9901 if (LDiff->isMinValue()) 9902 return true; 9903 9904 APInt FoundRHSLimit; 9905 9906 if (Pred == CmpInst::ICMP_ULT) { 9907 FoundRHSLimit = -(*RDiff); 9908 } else { 9909 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9910 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9911 } 9912 9913 // Try to prove (1) or (2), as needed. 9914 return isAvailableAtLoopEntry(FoundRHS, L) && 9915 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9916 getConstant(FoundRHSLimit)); 9917 } 9918 9919 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 9920 const SCEV *LHS, const SCEV *RHS, 9921 const SCEV *FoundLHS, 9922 const SCEV *FoundRHS, unsigned Depth) { 9923 const PHINode *LPhi = nullptr, *RPhi = nullptr; 9924 9925 auto ClearOnExit = make_scope_exit([&]() { 9926 if (LPhi) { 9927 bool Erased = PendingMerges.erase(LPhi); 9928 assert(Erased && "Failed to erase LPhi!"); 9929 (void)Erased; 9930 } 9931 if (RPhi) { 9932 bool Erased = PendingMerges.erase(RPhi); 9933 assert(Erased && "Failed to erase RPhi!"); 9934 (void)Erased; 9935 } 9936 }); 9937 9938 // Find respective Phis and check that they are not being pending. 9939 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 9940 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 9941 if (!PendingMerges.insert(Phi).second) 9942 return false; 9943 LPhi = Phi; 9944 } 9945 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 9946 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 9947 // If we detect a loop of Phi nodes being processed by this method, for 9948 // example: 9949 // 9950 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 9951 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 9952 // 9953 // we don't want to deal with a case that complex, so return conservative 9954 // answer false. 9955 if (!PendingMerges.insert(Phi).second) 9956 return false; 9957 RPhi = Phi; 9958 } 9959 9960 // If none of LHS, RHS is a Phi, nothing to do here. 9961 if (!LPhi && !RPhi) 9962 return false; 9963 9964 // If there is a SCEVUnknown Phi we are interested in, make it left. 9965 if (!LPhi) { 9966 std::swap(LHS, RHS); 9967 std::swap(FoundLHS, FoundRHS); 9968 std::swap(LPhi, RPhi); 9969 Pred = ICmpInst::getSwappedPredicate(Pred); 9970 } 9971 9972 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 9973 const BasicBlock *LBB = LPhi->getParent(); 9974 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 9975 9976 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 9977 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 9978 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 9979 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 9980 }; 9981 9982 if (RPhi && RPhi->getParent() == LBB) { 9983 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 9984 // If we compare two Phis from the same block, and for each entry block 9985 // the predicate is true for incoming values from this block, then the 9986 // predicate is also true for the Phis. 9987 for (const BasicBlock *IncBB : predecessors(LBB)) { 9988 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 9989 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 9990 if (!ProvedEasily(L, R)) 9991 return false; 9992 } 9993 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 9994 // Case two: RHS is also a Phi from the same basic block, and it is an 9995 // AddRec. It means that there is a loop which has both AddRec and Unknown 9996 // PHIs, for it we can compare incoming values of AddRec from above the loop 9997 // and latch with their respective incoming values of LPhi. 9998 // TODO: Generalize to handle loops with many inputs in a header. 9999 if (LPhi->getNumIncomingValues() != 2) return false; 10000 10001 auto *RLoop = RAR->getLoop(); 10002 auto *Predecessor = RLoop->getLoopPredecessor(); 10003 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10004 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10005 if (!ProvedEasily(L1, RAR->getStart())) 10006 return false; 10007 auto *Latch = RLoop->getLoopLatch(); 10008 assert(Latch && "Loop with AddRec with no latch?"); 10009 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10010 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10011 return false; 10012 } else { 10013 // In all other cases go over inputs of LHS and compare each of them to RHS, 10014 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10015 // At this point RHS is either a non-Phi, or it is a Phi from some block 10016 // different from LBB. 10017 for (const BasicBlock *IncBB : predecessors(LBB)) { 10018 // Check that RHS is available in this block. 10019 if (!dominates(RHS, IncBB)) 10020 return false; 10021 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10022 if (!ProvedEasily(L, RHS)) 10023 return false; 10024 } 10025 } 10026 return true; 10027 } 10028 10029 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10030 const SCEV *LHS, const SCEV *RHS, 10031 const SCEV *FoundLHS, 10032 const SCEV *FoundRHS) { 10033 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10034 return true; 10035 10036 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10037 return true; 10038 10039 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10040 FoundLHS, FoundRHS) || 10041 // ~x < ~y --> x > y 10042 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10043 getNotSCEV(FoundRHS), 10044 getNotSCEV(FoundLHS)); 10045 } 10046 10047 /// If Expr computes ~A, return A else return nullptr 10048 static const SCEV *MatchNotExpr(const SCEV *Expr) { 10049 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 10050 if (!Add || Add->getNumOperands() != 2 || 10051 !Add->getOperand(0)->isAllOnesValue()) 10052 return nullptr; 10053 10054 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 10055 if (!AddRHS || AddRHS->getNumOperands() != 2 || 10056 !AddRHS->getOperand(0)->isAllOnesValue()) 10057 return nullptr; 10058 10059 return AddRHS->getOperand(1); 10060 } 10061 10062 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 10063 template<typename MaxExprType> 10064 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 10065 const SCEV *Candidate) { 10066 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 10067 if (!MaxExpr) return false; 10068 10069 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 10070 } 10071 10072 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 10073 template<typename MaxExprType> 10074 static bool IsMinConsistingOf(ScalarEvolution &SE, 10075 const SCEV *MaybeMinExpr, 10076 const SCEV *Candidate) { 10077 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 10078 if (!MaybeMaxExpr) 10079 return false; 10080 10081 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 10082 } 10083 10084 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10085 ICmpInst::Predicate Pred, 10086 const SCEV *LHS, const SCEV *RHS) { 10087 // If both sides are affine addrecs for the same loop, with equal 10088 // steps, and we know the recurrences don't wrap, then we only 10089 // need to check the predicate on the starting values. 10090 10091 if (!ICmpInst::isRelational(Pred)) 10092 return false; 10093 10094 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10095 if (!LAR) 10096 return false; 10097 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10098 if (!RAR) 10099 return false; 10100 if (LAR->getLoop() != RAR->getLoop()) 10101 return false; 10102 if (!LAR->isAffine() || !RAR->isAffine()) 10103 return false; 10104 10105 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10106 return false; 10107 10108 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10109 SCEV::FlagNSW : SCEV::FlagNUW; 10110 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10111 return false; 10112 10113 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10114 } 10115 10116 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10117 /// expression? 10118 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10119 ICmpInst::Predicate Pred, 10120 const SCEV *LHS, const SCEV *RHS) { 10121 switch (Pred) { 10122 default: 10123 return false; 10124 10125 case ICmpInst::ICMP_SGE: 10126 std::swap(LHS, RHS); 10127 LLVM_FALLTHROUGH; 10128 case ICmpInst::ICMP_SLE: 10129 return 10130 // min(A, ...) <= A 10131 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 10132 // A <= max(A, ...) 10133 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10134 10135 case ICmpInst::ICMP_UGE: 10136 std::swap(LHS, RHS); 10137 LLVM_FALLTHROUGH; 10138 case ICmpInst::ICMP_ULE: 10139 return 10140 // min(A, ...) <= A 10141 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 10142 // A <= max(A, ...) 10143 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10144 } 10145 10146 llvm_unreachable("covered switch fell through?!"); 10147 } 10148 10149 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10150 const SCEV *LHS, const SCEV *RHS, 10151 const SCEV *FoundLHS, 10152 const SCEV *FoundRHS, 10153 unsigned Depth) { 10154 assert(getTypeSizeInBits(LHS->getType()) == 10155 getTypeSizeInBits(RHS->getType()) && 10156 "LHS and RHS have different sizes?"); 10157 assert(getTypeSizeInBits(FoundLHS->getType()) == 10158 getTypeSizeInBits(FoundRHS->getType()) && 10159 "FoundLHS and FoundRHS have different sizes?"); 10160 // We want to avoid hurting the compile time with analysis of too big trees. 10161 if (Depth > MaxSCEVOperationsImplicationDepth) 10162 return false; 10163 // We only want to work with ICMP_SGT comparison so far. 10164 // TODO: Extend to ICMP_UGT? 10165 if (Pred == ICmpInst::ICMP_SLT) { 10166 Pred = ICmpInst::ICMP_SGT; 10167 std::swap(LHS, RHS); 10168 std::swap(FoundLHS, FoundRHS); 10169 } 10170 if (Pred != ICmpInst::ICMP_SGT) 10171 return false; 10172 10173 auto GetOpFromSExt = [&](const SCEV *S) { 10174 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10175 return Ext->getOperand(); 10176 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10177 // the constant in some cases. 10178 return S; 10179 }; 10180 10181 // Acquire values from extensions. 10182 auto *OrigLHS = LHS; 10183 auto *OrigFoundLHS = FoundLHS; 10184 LHS = GetOpFromSExt(LHS); 10185 FoundLHS = GetOpFromSExt(FoundLHS); 10186 10187 // Is the SGT predicate can be proved trivially or using the found context. 10188 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10189 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10190 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10191 FoundRHS, Depth + 1); 10192 }; 10193 10194 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10195 // We want to avoid creation of any new non-constant SCEV. Since we are 10196 // going to compare the operands to RHS, we should be certain that we don't 10197 // need any size extensions for this. So let's decline all cases when the 10198 // sizes of types of LHS and RHS do not match. 10199 // TODO: Maybe try to get RHS from sext to catch more cases? 10200 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10201 return false; 10202 10203 // Should not overflow. 10204 if (!LHSAddExpr->hasNoSignedWrap()) 10205 return false; 10206 10207 auto *LL = LHSAddExpr->getOperand(0); 10208 auto *LR = LHSAddExpr->getOperand(1); 10209 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10210 10211 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10212 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10213 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10214 }; 10215 // Try to prove the following rule: 10216 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10217 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10218 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10219 return true; 10220 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10221 Value *LL, *LR; 10222 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10223 10224 using namespace llvm::PatternMatch; 10225 10226 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10227 // Rules for division. 10228 // We are going to perform some comparisons with Denominator and its 10229 // derivative expressions. In general case, creating a SCEV for it may 10230 // lead to a complex analysis of the entire graph, and in particular it 10231 // can request trip count recalculation for the same loop. This would 10232 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10233 // this, we only want to create SCEVs that are constants in this section. 10234 // So we bail if Denominator is not a constant. 10235 if (!isa<ConstantInt>(LR)) 10236 return false; 10237 10238 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10239 10240 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10241 // then a SCEV for the numerator already exists and matches with FoundLHS. 10242 auto *Numerator = getExistingSCEV(LL); 10243 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10244 return false; 10245 10246 // Make sure that the numerator matches with FoundLHS and the denominator 10247 // is positive. 10248 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10249 return false; 10250 10251 auto *DTy = Denominator->getType(); 10252 auto *FRHSTy = FoundRHS->getType(); 10253 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10254 // One of types is a pointer and another one is not. We cannot extend 10255 // them properly to a wider type, so let us just reject this case. 10256 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10257 // to avoid this check. 10258 return false; 10259 10260 // Given that: 10261 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10262 auto *WTy = getWiderType(DTy, FRHSTy); 10263 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10264 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10265 10266 // Try to prove the following rule: 10267 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10268 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10269 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10270 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10271 if (isKnownNonPositive(RHS) && 10272 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10273 return true; 10274 10275 // Try to prove the following rule: 10276 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10277 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10278 // If we divide it by Denominator > 2, then: 10279 // 1. If FoundLHS is negative, then the result is 0. 10280 // 2. If FoundLHS is non-negative, then the result is non-negative. 10281 // Anyways, the result is non-negative. 10282 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10283 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10284 if (isKnownNegative(RHS) && 10285 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10286 return true; 10287 } 10288 } 10289 10290 // If our expression contained SCEVUnknown Phis, and we split it down and now 10291 // need to prove something for them, try to prove the predicate for every 10292 // possible incoming values of those Phis. 10293 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10294 return true; 10295 10296 return false; 10297 } 10298 10299 bool 10300 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10301 const SCEV *LHS, const SCEV *RHS) { 10302 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10303 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10304 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10305 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10306 } 10307 10308 bool 10309 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10310 const SCEV *LHS, const SCEV *RHS, 10311 const SCEV *FoundLHS, 10312 const SCEV *FoundRHS) { 10313 switch (Pred) { 10314 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10315 case ICmpInst::ICMP_EQ: 10316 case ICmpInst::ICMP_NE: 10317 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10318 return true; 10319 break; 10320 case ICmpInst::ICMP_SLT: 10321 case ICmpInst::ICMP_SLE: 10322 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10323 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10324 return true; 10325 break; 10326 case ICmpInst::ICMP_SGT: 10327 case ICmpInst::ICMP_SGE: 10328 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10329 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10330 return true; 10331 break; 10332 case ICmpInst::ICMP_ULT: 10333 case ICmpInst::ICMP_ULE: 10334 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10335 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10336 return true; 10337 break; 10338 case ICmpInst::ICMP_UGT: 10339 case ICmpInst::ICMP_UGE: 10340 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10341 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10342 return true; 10343 break; 10344 } 10345 10346 // Maybe it can be proved via operations? 10347 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10348 return true; 10349 10350 return false; 10351 } 10352 10353 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10354 const SCEV *LHS, 10355 const SCEV *RHS, 10356 const SCEV *FoundLHS, 10357 const SCEV *FoundRHS) { 10358 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10359 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10360 // reduce the compile time impact of this optimization. 10361 return false; 10362 10363 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10364 if (!Addend) 10365 return false; 10366 10367 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10368 10369 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10370 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10371 ConstantRange FoundLHSRange = 10372 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10373 10374 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10375 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10376 10377 // We can also compute the range of values for `LHS` that satisfy the 10378 // consequent, "`LHS` `Pred` `RHS`": 10379 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10380 ConstantRange SatisfyingLHSRange = 10381 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10382 10383 // The antecedent implies the consequent if every value of `LHS` that 10384 // satisfies the antecedent also satisfies the consequent. 10385 return SatisfyingLHSRange.contains(LHSRange); 10386 } 10387 10388 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10389 bool IsSigned, bool NoWrap) { 10390 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10391 10392 if (NoWrap) return false; 10393 10394 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10395 const SCEV *One = getOne(Stride->getType()); 10396 10397 if (IsSigned) { 10398 APInt MaxRHS = getSignedRangeMax(RHS); 10399 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10400 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10401 10402 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10403 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10404 } 10405 10406 APInt MaxRHS = getUnsignedRangeMax(RHS); 10407 APInt MaxValue = APInt::getMaxValue(BitWidth); 10408 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10409 10410 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10411 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10412 } 10413 10414 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10415 bool IsSigned, bool NoWrap) { 10416 if (NoWrap) return false; 10417 10418 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10419 const SCEV *One = getOne(Stride->getType()); 10420 10421 if (IsSigned) { 10422 APInt MinRHS = getSignedRangeMin(RHS); 10423 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10424 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10425 10426 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10427 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10428 } 10429 10430 APInt MinRHS = getUnsignedRangeMin(RHS); 10431 APInt MinValue = APInt::getMinValue(BitWidth); 10432 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10433 10434 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10435 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10436 } 10437 10438 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10439 bool Equality) { 10440 const SCEV *One = getOne(Step->getType()); 10441 Delta = Equality ? getAddExpr(Delta, Step) 10442 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10443 return getUDivExpr(Delta, Step); 10444 } 10445 10446 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10447 const SCEV *Stride, 10448 const SCEV *End, 10449 unsigned BitWidth, 10450 bool IsSigned) { 10451 10452 assert(!isKnownNonPositive(Stride) && 10453 "Stride is expected strictly positive!"); 10454 // Calculate the maximum backedge count based on the range of values 10455 // permitted by Start, End, and Stride. 10456 const SCEV *MaxBECount; 10457 APInt MinStart = 10458 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10459 10460 APInt StrideForMaxBECount = 10461 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10462 10463 // We already know that the stride is positive, so we paper over conservatism 10464 // in our range computation by forcing StrideForMaxBECount to be at least one. 10465 // In theory this is unnecessary, but we expect MaxBECount to be a 10466 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10467 // is nothing to constant fold it to). 10468 APInt One(BitWidth, 1, IsSigned); 10469 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10470 10471 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10472 : APInt::getMaxValue(BitWidth); 10473 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10474 10475 // Although End can be a MAX expression we estimate MaxEnd considering only 10476 // the case End = RHS of the loop termination condition. This is safe because 10477 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10478 // taken count. 10479 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10480 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10481 10482 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10483 getConstant(StrideForMaxBECount) /* Step */, 10484 false /* Equality */); 10485 10486 return MaxBECount; 10487 } 10488 10489 ScalarEvolution::ExitLimit 10490 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10491 const Loop *L, bool IsSigned, 10492 bool ControlsExit, bool AllowPredicates) { 10493 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10494 10495 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10496 bool PredicatedIV = false; 10497 10498 if (!IV && AllowPredicates) { 10499 // Try to make this an AddRec using runtime tests, in the first X 10500 // iterations of this loop, where X is the SCEV expression found by the 10501 // algorithm below. 10502 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10503 PredicatedIV = true; 10504 } 10505 10506 // Avoid weird loops 10507 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10508 return getCouldNotCompute(); 10509 10510 bool NoWrap = ControlsExit && 10511 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10512 10513 const SCEV *Stride = IV->getStepRecurrence(*this); 10514 10515 bool PositiveStride = isKnownPositive(Stride); 10516 10517 // Avoid negative or zero stride values. 10518 if (!PositiveStride) { 10519 // We can compute the correct backedge taken count for loops with unknown 10520 // strides if we can prove that the loop is not an infinite loop with side 10521 // effects. Here's the loop structure we are trying to handle - 10522 // 10523 // i = start 10524 // do { 10525 // A[i] = i; 10526 // i += s; 10527 // } while (i < end); 10528 // 10529 // The backedge taken count for such loops is evaluated as - 10530 // (max(end, start + stride) - start - 1) /u stride 10531 // 10532 // The additional preconditions that we need to check to prove correctness 10533 // of the above formula is as follows - 10534 // 10535 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10536 // NoWrap flag). 10537 // b) loop is single exit with no side effects. 10538 // 10539 // 10540 // Precondition a) implies that if the stride is negative, this is a single 10541 // trip loop. The backedge taken count formula reduces to zero in this case. 10542 // 10543 // Precondition b) implies that the unknown stride cannot be zero otherwise 10544 // we have UB. 10545 // 10546 // The positive stride case is the same as isKnownPositive(Stride) returning 10547 // true (original behavior of the function). 10548 // 10549 // We want to make sure that the stride is truly unknown as there are edge 10550 // cases where ScalarEvolution propagates no wrap flags to the 10551 // post-increment/decrement IV even though the increment/decrement operation 10552 // itself is wrapping. The computed backedge taken count may be wrong in 10553 // such cases. This is prevented by checking that the stride is not known to 10554 // be either positive or non-positive. For example, no wrap flags are 10555 // propagated to the post-increment IV of this loop with a trip count of 2 - 10556 // 10557 // unsigned char i; 10558 // for(i=127; i<128; i+=129) 10559 // A[i] = i; 10560 // 10561 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10562 !loopHasNoSideEffects(L)) 10563 return getCouldNotCompute(); 10564 } else if (!Stride->isOne() && 10565 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10566 // Avoid proven overflow cases: this will ensure that the backedge taken 10567 // count will not generate any unsigned overflow. Relaxed no-overflow 10568 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10569 // undefined behaviors like the case of C language. 10570 return getCouldNotCompute(); 10571 10572 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10573 : ICmpInst::ICMP_ULT; 10574 const SCEV *Start = IV->getStart(); 10575 const SCEV *End = RHS; 10576 // When the RHS is not invariant, we do not know the end bound of the loop and 10577 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10578 // calculate the MaxBECount, given the start, stride and max value for the end 10579 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10580 // checked above). 10581 if (!isLoopInvariant(RHS, L)) { 10582 const SCEV *MaxBECount = computeMaxBECountForLT( 10583 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10584 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10585 false /*MaxOrZero*/, Predicates); 10586 } 10587 // If the backedge is taken at least once, then it will be taken 10588 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10589 // is the LHS value of the less-than comparison the first time it is evaluated 10590 // and End is the RHS. 10591 const SCEV *BECountIfBackedgeTaken = 10592 computeBECount(getMinusSCEV(End, Start), Stride, false); 10593 // If the loop entry is guarded by the result of the backedge test of the 10594 // first loop iteration, then we know the backedge will be taken at least 10595 // once and so the backedge taken count is as above. If not then we use the 10596 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10597 // as if the backedge is taken at least once max(End,Start) is End and so the 10598 // result is as above, and if not max(End,Start) is Start so we get a backedge 10599 // count of zero. 10600 const SCEV *BECount; 10601 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10602 BECount = BECountIfBackedgeTaken; 10603 else { 10604 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10605 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10606 } 10607 10608 const SCEV *MaxBECount; 10609 bool MaxOrZero = false; 10610 if (isa<SCEVConstant>(BECount)) 10611 MaxBECount = BECount; 10612 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10613 // If we know exactly how many times the backedge will be taken if it's 10614 // taken at least once, then the backedge count will either be that or 10615 // zero. 10616 MaxBECount = BECountIfBackedgeTaken; 10617 MaxOrZero = true; 10618 } else { 10619 MaxBECount = computeMaxBECountForLT( 10620 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10621 } 10622 10623 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10624 !isa<SCEVCouldNotCompute>(BECount)) 10625 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10626 10627 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10628 } 10629 10630 ScalarEvolution::ExitLimit 10631 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10632 const Loop *L, bool IsSigned, 10633 bool ControlsExit, bool AllowPredicates) { 10634 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10635 // We handle only IV > Invariant 10636 if (!isLoopInvariant(RHS, L)) 10637 return getCouldNotCompute(); 10638 10639 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10640 if (!IV && AllowPredicates) 10641 // Try to make this an AddRec using runtime tests, in the first X 10642 // iterations of this loop, where X is the SCEV expression found by the 10643 // algorithm below. 10644 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10645 10646 // Avoid weird loops 10647 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10648 return getCouldNotCompute(); 10649 10650 bool NoWrap = ControlsExit && 10651 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10652 10653 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10654 10655 // Avoid negative or zero stride values 10656 if (!isKnownPositive(Stride)) 10657 return getCouldNotCompute(); 10658 10659 // Avoid proven overflow cases: this will ensure that the backedge taken count 10660 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10661 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10662 // behaviors like the case of C language. 10663 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10664 return getCouldNotCompute(); 10665 10666 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10667 : ICmpInst::ICMP_UGT; 10668 10669 const SCEV *Start = IV->getStart(); 10670 const SCEV *End = RHS; 10671 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10672 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10673 10674 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10675 10676 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10677 : getUnsignedRangeMax(Start); 10678 10679 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10680 : getUnsignedRangeMin(Stride); 10681 10682 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10683 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10684 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10685 10686 // Although End can be a MIN expression we estimate MinEnd considering only 10687 // the case End = RHS. This is safe because in the other case (Start - End) 10688 // is zero, leading to a zero maximum backedge taken count. 10689 APInt MinEnd = 10690 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10691 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10692 10693 10694 const SCEV *MaxBECount = getCouldNotCompute(); 10695 if (isa<SCEVConstant>(BECount)) 10696 MaxBECount = BECount; 10697 else 10698 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 10699 getConstant(MinStride), false); 10700 10701 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10702 MaxBECount = BECount; 10703 10704 return ExitLimit(BECount, MaxBECount, false, Predicates); 10705 } 10706 10707 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10708 ScalarEvolution &SE) const { 10709 if (Range.isFullSet()) // Infinite loop. 10710 return SE.getCouldNotCompute(); 10711 10712 // If the start is a non-zero constant, shift the range to simplify things. 10713 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10714 if (!SC->getValue()->isZero()) { 10715 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10716 Operands[0] = SE.getZero(SC->getType()); 10717 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10718 getNoWrapFlags(FlagNW)); 10719 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10720 return ShiftedAddRec->getNumIterationsInRange( 10721 Range.subtract(SC->getAPInt()), SE); 10722 // This is strange and shouldn't happen. 10723 return SE.getCouldNotCompute(); 10724 } 10725 10726 // The only time we can solve this is when we have all constant indices. 10727 // Otherwise, we cannot determine the overflow conditions. 10728 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10729 return SE.getCouldNotCompute(); 10730 10731 // Okay at this point we know that all elements of the chrec are constants and 10732 // that the start element is zero. 10733 10734 // First check to see if the range contains zero. If not, the first 10735 // iteration exits. 10736 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10737 if (!Range.contains(APInt(BitWidth, 0))) 10738 return SE.getZero(getType()); 10739 10740 if (isAffine()) { 10741 // If this is an affine expression then we have this situation: 10742 // Solve {0,+,A} in Range === Ax in Range 10743 10744 // We know that zero is in the range. If A is positive then we know that 10745 // the upper value of the range must be the first possible exit value. 10746 // If A is negative then the lower of the range is the last possible loop 10747 // value. Also note that we already checked for a full range. 10748 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10749 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10750 10751 // The exit value should be (End+A)/A. 10752 APInt ExitVal = (End + A).udiv(A); 10753 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10754 10755 // Evaluate at the exit value. If we really did fall out of the valid 10756 // range, then we computed our trip count, otherwise wrap around or other 10757 // things must have happened. 10758 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10759 if (Range.contains(Val->getValue())) 10760 return SE.getCouldNotCompute(); // Something strange happened 10761 10762 // Ensure that the previous value is in the range. This is a sanity check. 10763 assert(Range.contains( 10764 EvaluateConstantChrecAtConstant(this, 10765 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10766 "Linear scev computation is off in a bad way!"); 10767 return SE.getConstant(ExitValue); 10768 } 10769 10770 if (isQuadratic()) { 10771 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10772 return SE.getConstant(S.getValue()); 10773 } 10774 10775 return SE.getCouldNotCompute(); 10776 } 10777 10778 const SCEVAddRecExpr * 10779 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10780 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10781 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10782 // but in this case we cannot guarantee that the value returned will be an 10783 // AddRec because SCEV does not have a fixed point where it stops 10784 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10785 // may happen if we reach arithmetic depth limit while simplifying. So we 10786 // construct the returned value explicitly. 10787 SmallVector<const SCEV *, 3> Ops; 10788 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10789 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10790 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10791 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10792 // We know that the last operand is not a constant zero (otherwise it would 10793 // have been popped out earlier). This guarantees us that if the result has 10794 // the same last operand, then it will also not be popped out, meaning that 10795 // the returned value will be an AddRec. 10796 const SCEV *Last = getOperand(getNumOperands() - 1); 10797 assert(!Last->isZero() && "Recurrency with zero step?"); 10798 Ops.push_back(Last); 10799 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10800 SCEV::FlagAnyWrap)); 10801 } 10802 10803 // Return true when S contains at least an undef value. 10804 static inline bool containsUndefs(const SCEV *S) { 10805 return SCEVExprContains(S, [](const SCEV *S) { 10806 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10807 return isa<UndefValue>(SU->getValue()); 10808 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 10809 return isa<UndefValue>(SC->getValue()); 10810 return false; 10811 }); 10812 } 10813 10814 namespace { 10815 10816 // Collect all steps of SCEV expressions. 10817 struct SCEVCollectStrides { 10818 ScalarEvolution &SE; 10819 SmallVectorImpl<const SCEV *> &Strides; 10820 10821 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10822 : SE(SE), Strides(S) {} 10823 10824 bool follow(const SCEV *S) { 10825 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10826 Strides.push_back(AR->getStepRecurrence(SE)); 10827 return true; 10828 } 10829 10830 bool isDone() const { return false; } 10831 }; 10832 10833 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10834 struct SCEVCollectTerms { 10835 SmallVectorImpl<const SCEV *> &Terms; 10836 10837 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10838 10839 bool follow(const SCEV *S) { 10840 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10841 isa<SCEVSignExtendExpr>(S)) { 10842 if (!containsUndefs(S)) 10843 Terms.push_back(S); 10844 10845 // Stop recursion: once we collected a term, do not walk its operands. 10846 return false; 10847 } 10848 10849 // Keep looking. 10850 return true; 10851 } 10852 10853 bool isDone() const { return false; } 10854 }; 10855 10856 // Check if a SCEV contains an AddRecExpr. 10857 struct SCEVHasAddRec { 10858 bool &ContainsAddRec; 10859 10860 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10861 ContainsAddRec = false; 10862 } 10863 10864 bool follow(const SCEV *S) { 10865 if (isa<SCEVAddRecExpr>(S)) { 10866 ContainsAddRec = true; 10867 10868 // Stop recursion: once we collected a term, do not walk its operands. 10869 return false; 10870 } 10871 10872 // Keep looking. 10873 return true; 10874 } 10875 10876 bool isDone() const { return false; } 10877 }; 10878 10879 // Find factors that are multiplied with an expression that (possibly as a 10880 // subexpression) contains an AddRecExpr. In the expression: 10881 // 10882 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10883 // 10884 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10885 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10886 // parameters as they form a product with an induction variable. 10887 // 10888 // This collector expects all array size parameters to be in the same MulExpr. 10889 // It might be necessary to later add support for collecting parameters that are 10890 // spread over different nested MulExpr. 10891 struct SCEVCollectAddRecMultiplies { 10892 SmallVectorImpl<const SCEV *> &Terms; 10893 ScalarEvolution &SE; 10894 10895 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10896 : Terms(T), SE(SE) {} 10897 10898 bool follow(const SCEV *S) { 10899 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10900 bool HasAddRec = false; 10901 SmallVector<const SCEV *, 0> Operands; 10902 for (auto Op : Mul->operands()) { 10903 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10904 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10905 Operands.push_back(Op); 10906 } else if (Unknown) { 10907 HasAddRec = true; 10908 } else { 10909 bool ContainsAddRec; 10910 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10911 visitAll(Op, ContiansAddRec); 10912 HasAddRec |= ContainsAddRec; 10913 } 10914 } 10915 if (Operands.size() == 0) 10916 return true; 10917 10918 if (!HasAddRec) 10919 return false; 10920 10921 Terms.push_back(SE.getMulExpr(Operands)); 10922 // Stop recursion: once we collected a term, do not walk its operands. 10923 return false; 10924 } 10925 10926 // Keep looking. 10927 return true; 10928 } 10929 10930 bool isDone() const { return false; } 10931 }; 10932 10933 } // end anonymous namespace 10934 10935 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 10936 /// two places: 10937 /// 1) The strides of AddRec expressions. 10938 /// 2) Unknowns that are multiplied with AddRec expressions. 10939 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 10940 SmallVectorImpl<const SCEV *> &Terms) { 10941 SmallVector<const SCEV *, 4> Strides; 10942 SCEVCollectStrides StrideCollector(*this, Strides); 10943 visitAll(Expr, StrideCollector); 10944 10945 LLVM_DEBUG({ 10946 dbgs() << "Strides:\n"; 10947 for (const SCEV *S : Strides) 10948 dbgs() << *S << "\n"; 10949 }); 10950 10951 for (const SCEV *S : Strides) { 10952 SCEVCollectTerms TermCollector(Terms); 10953 visitAll(S, TermCollector); 10954 } 10955 10956 LLVM_DEBUG({ 10957 dbgs() << "Terms:\n"; 10958 for (const SCEV *T : Terms) 10959 dbgs() << *T << "\n"; 10960 }); 10961 10962 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 10963 visitAll(Expr, MulCollector); 10964 } 10965 10966 static bool findArrayDimensionsRec(ScalarEvolution &SE, 10967 SmallVectorImpl<const SCEV *> &Terms, 10968 SmallVectorImpl<const SCEV *> &Sizes) { 10969 int Last = Terms.size() - 1; 10970 const SCEV *Step = Terms[Last]; 10971 10972 // End of recursion. 10973 if (Last == 0) { 10974 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 10975 SmallVector<const SCEV *, 2> Qs; 10976 for (const SCEV *Op : M->operands()) 10977 if (!isa<SCEVConstant>(Op)) 10978 Qs.push_back(Op); 10979 10980 Step = SE.getMulExpr(Qs); 10981 } 10982 10983 Sizes.push_back(Step); 10984 return true; 10985 } 10986 10987 for (const SCEV *&Term : Terms) { 10988 // Normalize the terms before the next call to findArrayDimensionsRec. 10989 const SCEV *Q, *R; 10990 SCEVDivision::divide(SE, Term, Step, &Q, &R); 10991 10992 // Bail out when GCD does not evenly divide one of the terms. 10993 if (!R->isZero()) 10994 return false; 10995 10996 Term = Q; 10997 } 10998 10999 // Remove all SCEVConstants. 11000 Terms.erase( 11001 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11002 Terms.end()); 11003 11004 if (Terms.size() > 0) 11005 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11006 return false; 11007 11008 Sizes.push_back(Step); 11009 return true; 11010 } 11011 11012 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11013 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11014 for (const SCEV *T : Terms) 11015 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 11016 return true; 11017 return false; 11018 } 11019 11020 // Return the number of product terms in S. 11021 static inline int numberOfTerms(const SCEV *S) { 11022 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11023 return Expr->getNumOperands(); 11024 return 1; 11025 } 11026 11027 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11028 if (isa<SCEVConstant>(T)) 11029 return nullptr; 11030 11031 if (isa<SCEVUnknown>(T)) 11032 return T; 11033 11034 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11035 SmallVector<const SCEV *, 2> Factors; 11036 for (const SCEV *Op : M->operands()) 11037 if (!isa<SCEVConstant>(Op)) 11038 Factors.push_back(Op); 11039 11040 return SE.getMulExpr(Factors); 11041 } 11042 11043 return T; 11044 } 11045 11046 /// Return the size of an element read or written by Inst. 11047 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11048 Type *Ty; 11049 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11050 Ty = Store->getValueOperand()->getType(); 11051 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11052 Ty = Load->getType(); 11053 else 11054 return nullptr; 11055 11056 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11057 return getSizeOfExpr(ETy, Ty); 11058 } 11059 11060 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11061 SmallVectorImpl<const SCEV *> &Sizes, 11062 const SCEV *ElementSize) { 11063 if (Terms.size() < 1 || !ElementSize) 11064 return; 11065 11066 // Early return when Terms do not contain parameters: we do not delinearize 11067 // non parametric SCEVs. 11068 if (!containsParameters(Terms)) 11069 return; 11070 11071 LLVM_DEBUG({ 11072 dbgs() << "Terms:\n"; 11073 for (const SCEV *T : Terms) 11074 dbgs() << *T << "\n"; 11075 }); 11076 11077 // Remove duplicates. 11078 array_pod_sort(Terms.begin(), Terms.end()); 11079 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11080 11081 // Put larger terms first. 11082 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11083 return numberOfTerms(LHS) > numberOfTerms(RHS); 11084 }); 11085 11086 // Try to divide all terms by the element size. If term is not divisible by 11087 // element size, proceed with the original term. 11088 for (const SCEV *&Term : Terms) { 11089 const SCEV *Q, *R; 11090 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11091 if (!Q->isZero()) 11092 Term = Q; 11093 } 11094 11095 SmallVector<const SCEV *, 4> NewTerms; 11096 11097 // Remove constant factors. 11098 for (const SCEV *T : Terms) 11099 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11100 NewTerms.push_back(NewT); 11101 11102 LLVM_DEBUG({ 11103 dbgs() << "Terms after sorting:\n"; 11104 for (const SCEV *T : NewTerms) 11105 dbgs() << *T << "\n"; 11106 }); 11107 11108 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11109 Sizes.clear(); 11110 return; 11111 } 11112 11113 // The last element to be pushed into Sizes is the size of an element. 11114 Sizes.push_back(ElementSize); 11115 11116 LLVM_DEBUG({ 11117 dbgs() << "Sizes:\n"; 11118 for (const SCEV *S : Sizes) 11119 dbgs() << *S << "\n"; 11120 }); 11121 } 11122 11123 void ScalarEvolution::computeAccessFunctions( 11124 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11125 SmallVectorImpl<const SCEV *> &Sizes) { 11126 // Early exit in case this SCEV is not an affine multivariate function. 11127 if (Sizes.empty()) 11128 return; 11129 11130 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11131 if (!AR->isAffine()) 11132 return; 11133 11134 const SCEV *Res = Expr; 11135 int Last = Sizes.size() - 1; 11136 for (int i = Last; i >= 0; i--) { 11137 const SCEV *Q, *R; 11138 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11139 11140 LLVM_DEBUG({ 11141 dbgs() << "Res: " << *Res << "\n"; 11142 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11143 dbgs() << "Res divided by Sizes[i]:\n"; 11144 dbgs() << "Quotient: " << *Q << "\n"; 11145 dbgs() << "Remainder: " << *R << "\n"; 11146 }); 11147 11148 Res = Q; 11149 11150 // Do not record the last subscript corresponding to the size of elements in 11151 // the array. 11152 if (i == Last) { 11153 11154 // Bail out if the remainder is too complex. 11155 if (isa<SCEVAddRecExpr>(R)) { 11156 Subscripts.clear(); 11157 Sizes.clear(); 11158 return; 11159 } 11160 11161 continue; 11162 } 11163 11164 // Record the access function for the current subscript. 11165 Subscripts.push_back(R); 11166 } 11167 11168 // Also push in last position the remainder of the last division: it will be 11169 // the access function of the innermost dimension. 11170 Subscripts.push_back(Res); 11171 11172 std::reverse(Subscripts.begin(), Subscripts.end()); 11173 11174 LLVM_DEBUG({ 11175 dbgs() << "Subscripts:\n"; 11176 for (const SCEV *S : Subscripts) 11177 dbgs() << *S << "\n"; 11178 }); 11179 } 11180 11181 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11182 /// sizes of an array access. Returns the remainder of the delinearization that 11183 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11184 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11185 /// expressions in the stride and base of a SCEV corresponding to the 11186 /// computation of a GCD (greatest common divisor) of base and stride. When 11187 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11188 /// 11189 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11190 /// 11191 /// void foo(long n, long m, long o, double A[n][m][o]) { 11192 /// 11193 /// for (long i = 0; i < n; i++) 11194 /// for (long j = 0; j < m; j++) 11195 /// for (long k = 0; k < o; k++) 11196 /// A[i][j][k] = 1.0; 11197 /// } 11198 /// 11199 /// the delinearization input is the following AddRec SCEV: 11200 /// 11201 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11202 /// 11203 /// From this SCEV, we are able to say that the base offset of the access is %A 11204 /// because it appears as an offset that does not divide any of the strides in 11205 /// the loops: 11206 /// 11207 /// CHECK: Base offset: %A 11208 /// 11209 /// and then SCEV->delinearize determines the size of some of the dimensions of 11210 /// the array as these are the multiples by which the strides are happening: 11211 /// 11212 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11213 /// 11214 /// Note that the outermost dimension remains of UnknownSize because there are 11215 /// no strides that would help identifying the size of the last dimension: when 11216 /// the array has been statically allocated, one could compute the size of that 11217 /// dimension by dividing the overall size of the array by the size of the known 11218 /// dimensions: %m * %o * 8. 11219 /// 11220 /// Finally delinearize provides the access functions for the array reference 11221 /// that does correspond to A[i][j][k] of the above C testcase: 11222 /// 11223 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11224 /// 11225 /// The testcases are checking the output of a function pass: 11226 /// DelinearizationPass that walks through all loads and stores of a function 11227 /// asking for the SCEV of the memory access with respect to all enclosing 11228 /// loops, calling SCEV->delinearize on that and printing the results. 11229 void ScalarEvolution::delinearize(const SCEV *Expr, 11230 SmallVectorImpl<const SCEV *> &Subscripts, 11231 SmallVectorImpl<const SCEV *> &Sizes, 11232 const SCEV *ElementSize) { 11233 // First step: collect parametric terms. 11234 SmallVector<const SCEV *, 4> Terms; 11235 collectParametricTerms(Expr, Terms); 11236 11237 if (Terms.empty()) 11238 return; 11239 11240 // Second step: find subscript sizes. 11241 findArrayDimensions(Terms, Sizes, ElementSize); 11242 11243 if (Sizes.empty()) 11244 return; 11245 11246 // Third step: compute the access functions for each subscript. 11247 computeAccessFunctions(Expr, Subscripts, Sizes); 11248 11249 if (Subscripts.empty()) 11250 return; 11251 11252 LLVM_DEBUG({ 11253 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11254 dbgs() << "ArrayDecl[UnknownSize]"; 11255 for (const SCEV *S : Sizes) 11256 dbgs() << "[" << *S << "]"; 11257 11258 dbgs() << "\nArrayRef"; 11259 for (const SCEV *S : Subscripts) 11260 dbgs() << "[" << *S << "]"; 11261 dbgs() << "\n"; 11262 }); 11263 } 11264 11265 //===----------------------------------------------------------------------===// 11266 // SCEVCallbackVH Class Implementation 11267 //===----------------------------------------------------------------------===// 11268 11269 void ScalarEvolution::SCEVCallbackVH::deleted() { 11270 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11271 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11272 SE->ConstantEvolutionLoopExitValue.erase(PN); 11273 SE->eraseValueFromMap(getValPtr()); 11274 // this now dangles! 11275 } 11276 11277 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11278 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11279 11280 // Forget all the expressions associated with users of the old value, 11281 // so that future queries will recompute the expressions using the new 11282 // value. 11283 Value *Old = getValPtr(); 11284 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11285 SmallPtrSet<User *, 8> Visited; 11286 while (!Worklist.empty()) { 11287 User *U = Worklist.pop_back_val(); 11288 // Deleting the Old value will cause this to dangle. Postpone 11289 // that until everything else is done. 11290 if (U == Old) 11291 continue; 11292 if (!Visited.insert(U).second) 11293 continue; 11294 if (PHINode *PN = dyn_cast<PHINode>(U)) 11295 SE->ConstantEvolutionLoopExitValue.erase(PN); 11296 SE->eraseValueFromMap(U); 11297 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11298 } 11299 // Delete the Old value. 11300 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11301 SE->ConstantEvolutionLoopExitValue.erase(PN); 11302 SE->eraseValueFromMap(Old); 11303 // this now dangles! 11304 } 11305 11306 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11307 : CallbackVH(V), SE(se) {} 11308 11309 //===----------------------------------------------------------------------===// 11310 // ScalarEvolution Class Implementation 11311 //===----------------------------------------------------------------------===// 11312 11313 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11314 AssumptionCache &AC, DominatorTree &DT, 11315 LoopInfo &LI) 11316 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11317 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11318 LoopDispositions(64), BlockDispositions(64) { 11319 // To use guards for proving predicates, we need to scan every instruction in 11320 // relevant basic blocks, and not just terminators. Doing this is a waste of 11321 // time if the IR does not actually contain any calls to 11322 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11323 // 11324 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11325 // to _add_ guards to the module when there weren't any before, and wants 11326 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11327 // efficient in lieu of being smart in that rather obscure case. 11328 11329 auto *GuardDecl = F.getParent()->getFunction( 11330 Intrinsic::getName(Intrinsic::experimental_guard)); 11331 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11332 } 11333 11334 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11335 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11336 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11337 ValueExprMap(std::move(Arg.ValueExprMap)), 11338 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11339 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11340 PendingMerges(std::move(Arg.PendingMerges)), 11341 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11342 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11343 PredicatedBackedgeTakenCounts( 11344 std::move(Arg.PredicatedBackedgeTakenCounts)), 11345 ConstantEvolutionLoopExitValue( 11346 std::move(Arg.ConstantEvolutionLoopExitValue)), 11347 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11348 LoopDispositions(std::move(Arg.LoopDispositions)), 11349 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11350 BlockDispositions(std::move(Arg.BlockDispositions)), 11351 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11352 SignedRanges(std::move(Arg.SignedRanges)), 11353 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11354 UniquePreds(std::move(Arg.UniquePreds)), 11355 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11356 LoopUsers(std::move(Arg.LoopUsers)), 11357 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11358 FirstUnknown(Arg.FirstUnknown) { 11359 Arg.FirstUnknown = nullptr; 11360 } 11361 11362 ScalarEvolution::~ScalarEvolution() { 11363 // Iterate through all the SCEVUnknown instances and call their 11364 // destructors, so that they release their references to their values. 11365 for (SCEVUnknown *U = FirstUnknown; U;) { 11366 SCEVUnknown *Tmp = U; 11367 U = U->Next; 11368 Tmp->~SCEVUnknown(); 11369 } 11370 FirstUnknown = nullptr; 11371 11372 ExprValueMap.clear(); 11373 ValueExprMap.clear(); 11374 HasRecMap.clear(); 11375 11376 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11377 // that a loop had multiple computable exits. 11378 for (auto &BTCI : BackedgeTakenCounts) 11379 BTCI.second.clear(); 11380 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11381 BTCI.second.clear(); 11382 11383 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11384 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11385 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11386 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11387 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11388 } 11389 11390 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11391 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11392 } 11393 11394 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11395 const Loop *L) { 11396 // Print all inner loops first 11397 for (Loop *I : *L) 11398 PrintLoopInfo(OS, SE, I); 11399 11400 OS << "Loop "; 11401 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11402 OS << ": "; 11403 11404 SmallVector<BasicBlock *, 8> ExitBlocks; 11405 L->getExitBlocks(ExitBlocks); 11406 if (ExitBlocks.size() != 1) 11407 OS << "<multiple exits> "; 11408 11409 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11410 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 11411 } else { 11412 OS << "Unpredictable backedge-taken count. "; 11413 } 11414 11415 OS << "\n" 11416 "Loop "; 11417 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11418 OS << ": "; 11419 11420 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 11421 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 11422 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11423 OS << ", actual taken count either this or zero."; 11424 } else { 11425 OS << "Unpredictable max backedge-taken count. "; 11426 } 11427 11428 OS << "\n" 11429 "Loop "; 11430 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11431 OS << ": "; 11432 11433 SCEVUnionPredicate Pred; 11434 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11435 if (!isa<SCEVCouldNotCompute>(PBT)) { 11436 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11437 OS << " Predicates:\n"; 11438 Pred.print(OS, 4); 11439 } else { 11440 OS << "Unpredictable predicated backedge-taken count. "; 11441 } 11442 OS << "\n"; 11443 11444 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11445 OS << "Loop "; 11446 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11447 OS << ": "; 11448 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11449 } 11450 } 11451 11452 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11453 switch (LD) { 11454 case ScalarEvolution::LoopVariant: 11455 return "Variant"; 11456 case ScalarEvolution::LoopInvariant: 11457 return "Invariant"; 11458 case ScalarEvolution::LoopComputable: 11459 return "Computable"; 11460 } 11461 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11462 } 11463 11464 void ScalarEvolution::print(raw_ostream &OS) const { 11465 // ScalarEvolution's implementation of the print method is to print 11466 // out SCEV values of all instructions that are interesting. Doing 11467 // this potentially causes it to create new SCEV objects though, 11468 // which technically conflicts with the const qualifier. This isn't 11469 // observable from outside the class though, so casting away the 11470 // const isn't dangerous. 11471 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11472 11473 OS << "Classifying expressions for: "; 11474 F.printAsOperand(OS, /*PrintType=*/false); 11475 OS << "\n"; 11476 for (Instruction &I : instructions(F)) 11477 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11478 OS << I << '\n'; 11479 OS << " --> "; 11480 const SCEV *SV = SE.getSCEV(&I); 11481 SV->print(OS); 11482 if (!isa<SCEVCouldNotCompute>(SV)) { 11483 OS << " U: "; 11484 SE.getUnsignedRange(SV).print(OS); 11485 OS << " S: "; 11486 SE.getSignedRange(SV).print(OS); 11487 } 11488 11489 const Loop *L = LI.getLoopFor(I.getParent()); 11490 11491 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11492 if (AtUse != SV) { 11493 OS << " --> "; 11494 AtUse->print(OS); 11495 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11496 OS << " U: "; 11497 SE.getUnsignedRange(AtUse).print(OS); 11498 OS << " S: "; 11499 SE.getSignedRange(AtUse).print(OS); 11500 } 11501 } 11502 11503 if (L) { 11504 OS << "\t\t" "Exits: "; 11505 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11506 if (!SE.isLoopInvariant(ExitValue, L)) { 11507 OS << "<<Unknown>>"; 11508 } else { 11509 OS << *ExitValue; 11510 } 11511 11512 bool First = true; 11513 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11514 if (First) { 11515 OS << "\t\t" "LoopDispositions: { "; 11516 First = false; 11517 } else { 11518 OS << ", "; 11519 } 11520 11521 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11522 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11523 } 11524 11525 for (auto *InnerL : depth_first(L)) { 11526 if (InnerL == L) 11527 continue; 11528 if (First) { 11529 OS << "\t\t" "LoopDispositions: { "; 11530 First = false; 11531 } else { 11532 OS << ", "; 11533 } 11534 11535 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11536 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11537 } 11538 11539 OS << " }"; 11540 } 11541 11542 OS << "\n"; 11543 } 11544 11545 OS << "Determining loop execution counts for: "; 11546 F.printAsOperand(OS, /*PrintType=*/false); 11547 OS << "\n"; 11548 for (Loop *I : LI) 11549 PrintLoopInfo(OS, &SE, I); 11550 } 11551 11552 ScalarEvolution::LoopDisposition 11553 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11554 auto &Values = LoopDispositions[S]; 11555 for (auto &V : Values) { 11556 if (V.getPointer() == L) 11557 return V.getInt(); 11558 } 11559 Values.emplace_back(L, LoopVariant); 11560 LoopDisposition D = computeLoopDisposition(S, L); 11561 auto &Values2 = LoopDispositions[S]; 11562 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11563 if (V.getPointer() == L) { 11564 V.setInt(D); 11565 break; 11566 } 11567 } 11568 return D; 11569 } 11570 11571 ScalarEvolution::LoopDisposition 11572 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11573 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11574 case scConstant: 11575 return LoopInvariant; 11576 case scTruncate: 11577 case scZeroExtend: 11578 case scSignExtend: 11579 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11580 case scAddRecExpr: { 11581 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11582 11583 // If L is the addrec's loop, it's computable. 11584 if (AR->getLoop() == L) 11585 return LoopComputable; 11586 11587 // Add recurrences are never invariant in the function-body (null loop). 11588 if (!L) 11589 return LoopVariant; 11590 11591 // Everything that is not defined at loop entry is variant. 11592 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11593 return LoopVariant; 11594 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11595 " dominate the contained loop's header?"); 11596 11597 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11598 if (AR->getLoop()->contains(L)) 11599 return LoopInvariant; 11600 11601 // This recurrence is variant w.r.t. L if any of its operands 11602 // are variant. 11603 for (auto *Op : AR->operands()) 11604 if (!isLoopInvariant(Op, L)) 11605 return LoopVariant; 11606 11607 // Otherwise it's loop-invariant. 11608 return LoopInvariant; 11609 } 11610 case scAddExpr: 11611 case scMulExpr: 11612 case scUMaxExpr: 11613 case scSMaxExpr: { 11614 bool HasVarying = false; 11615 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11616 LoopDisposition D = getLoopDisposition(Op, L); 11617 if (D == LoopVariant) 11618 return LoopVariant; 11619 if (D == LoopComputable) 11620 HasVarying = true; 11621 } 11622 return HasVarying ? LoopComputable : LoopInvariant; 11623 } 11624 case scUDivExpr: { 11625 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11626 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11627 if (LD == LoopVariant) 11628 return LoopVariant; 11629 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11630 if (RD == LoopVariant) 11631 return LoopVariant; 11632 return (LD == LoopInvariant && RD == LoopInvariant) ? 11633 LoopInvariant : LoopComputable; 11634 } 11635 case scUnknown: 11636 // All non-instruction values are loop invariant. All instructions are loop 11637 // invariant if they are not contained in the specified loop. 11638 // Instructions are never considered invariant in the function body 11639 // (null loop) because they are defined within the "loop". 11640 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11641 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11642 return LoopInvariant; 11643 case scCouldNotCompute: 11644 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11645 } 11646 llvm_unreachable("Unknown SCEV kind!"); 11647 } 11648 11649 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11650 return getLoopDisposition(S, L) == LoopInvariant; 11651 } 11652 11653 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11654 return getLoopDisposition(S, L) == LoopComputable; 11655 } 11656 11657 ScalarEvolution::BlockDisposition 11658 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11659 auto &Values = BlockDispositions[S]; 11660 for (auto &V : Values) { 11661 if (V.getPointer() == BB) 11662 return V.getInt(); 11663 } 11664 Values.emplace_back(BB, DoesNotDominateBlock); 11665 BlockDisposition D = computeBlockDisposition(S, BB); 11666 auto &Values2 = BlockDispositions[S]; 11667 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11668 if (V.getPointer() == BB) { 11669 V.setInt(D); 11670 break; 11671 } 11672 } 11673 return D; 11674 } 11675 11676 ScalarEvolution::BlockDisposition 11677 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11678 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11679 case scConstant: 11680 return ProperlyDominatesBlock; 11681 case scTruncate: 11682 case scZeroExtend: 11683 case scSignExtend: 11684 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11685 case scAddRecExpr: { 11686 // This uses a "dominates" query instead of "properly dominates" query 11687 // to test for proper dominance too, because the instruction which 11688 // produces the addrec's value is a PHI, and a PHI effectively properly 11689 // dominates its entire containing block. 11690 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11691 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11692 return DoesNotDominateBlock; 11693 11694 // Fall through into SCEVNAryExpr handling. 11695 LLVM_FALLTHROUGH; 11696 } 11697 case scAddExpr: 11698 case scMulExpr: 11699 case scUMaxExpr: 11700 case scSMaxExpr: { 11701 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11702 bool Proper = true; 11703 for (const SCEV *NAryOp : NAry->operands()) { 11704 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11705 if (D == DoesNotDominateBlock) 11706 return DoesNotDominateBlock; 11707 if (D == DominatesBlock) 11708 Proper = false; 11709 } 11710 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11711 } 11712 case scUDivExpr: { 11713 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11714 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11715 BlockDisposition LD = getBlockDisposition(LHS, BB); 11716 if (LD == DoesNotDominateBlock) 11717 return DoesNotDominateBlock; 11718 BlockDisposition RD = getBlockDisposition(RHS, BB); 11719 if (RD == DoesNotDominateBlock) 11720 return DoesNotDominateBlock; 11721 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11722 ProperlyDominatesBlock : DominatesBlock; 11723 } 11724 case scUnknown: 11725 if (Instruction *I = 11726 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11727 if (I->getParent() == BB) 11728 return DominatesBlock; 11729 if (DT.properlyDominates(I->getParent(), BB)) 11730 return ProperlyDominatesBlock; 11731 return DoesNotDominateBlock; 11732 } 11733 return ProperlyDominatesBlock; 11734 case scCouldNotCompute: 11735 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11736 } 11737 llvm_unreachable("Unknown SCEV kind!"); 11738 } 11739 11740 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11741 return getBlockDisposition(S, BB) >= DominatesBlock; 11742 } 11743 11744 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11745 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11746 } 11747 11748 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11749 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11750 } 11751 11752 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11753 auto IsS = [&](const SCEV *X) { return S == X; }; 11754 auto ContainsS = [&](const SCEV *X) { 11755 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11756 }; 11757 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11758 } 11759 11760 void 11761 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11762 ValuesAtScopes.erase(S); 11763 LoopDispositions.erase(S); 11764 BlockDispositions.erase(S); 11765 UnsignedRanges.erase(S); 11766 SignedRanges.erase(S); 11767 ExprValueMap.erase(S); 11768 HasRecMap.erase(S); 11769 MinTrailingZerosCache.erase(S); 11770 11771 for (auto I = PredicatedSCEVRewrites.begin(); 11772 I != PredicatedSCEVRewrites.end();) { 11773 std::pair<const SCEV *, const Loop *> Entry = I->first; 11774 if (Entry.first == S) 11775 PredicatedSCEVRewrites.erase(I++); 11776 else 11777 ++I; 11778 } 11779 11780 auto RemoveSCEVFromBackedgeMap = 11781 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11782 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11783 BackedgeTakenInfo &BEInfo = I->second; 11784 if (BEInfo.hasOperand(S, this)) { 11785 BEInfo.clear(); 11786 Map.erase(I++); 11787 } else 11788 ++I; 11789 } 11790 }; 11791 11792 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11793 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11794 } 11795 11796 void 11797 ScalarEvolution::getUsedLoops(const SCEV *S, 11798 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11799 struct FindUsedLoops { 11800 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11801 : LoopsUsed(LoopsUsed) {} 11802 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11803 bool follow(const SCEV *S) { 11804 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11805 LoopsUsed.insert(AR->getLoop()); 11806 return true; 11807 } 11808 11809 bool isDone() const { return false; } 11810 }; 11811 11812 FindUsedLoops F(LoopsUsed); 11813 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11814 } 11815 11816 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11817 SmallPtrSet<const Loop *, 8> LoopsUsed; 11818 getUsedLoops(S, LoopsUsed); 11819 for (auto *L : LoopsUsed) 11820 LoopUsers[L].push_back(S); 11821 } 11822 11823 void ScalarEvolution::verify() const { 11824 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11825 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11826 11827 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11828 11829 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11830 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11831 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11832 11833 const SCEV *visitConstant(const SCEVConstant *Constant) { 11834 return SE.getConstant(Constant->getAPInt()); 11835 } 11836 11837 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11838 return SE.getUnknown(Expr->getValue()); 11839 } 11840 11841 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11842 return SE.getCouldNotCompute(); 11843 } 11844 }; 11845 11846 SCEVMapper SCM(SE2); 11847 11848 while (!LoopStack.empty()) { 11849 auto *L = LoopStack.pop_back_val(); 11850 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11851 11852 auto *CurBECount = SCM.visit( 11853 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11854 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11855 11856 if (CurBECount == SE2.getCouldNotCompute() || 11857 NewBECount == SE2.getCouldNotCompute()) { 11858 // NB! This situation is legal, but is very suspicious -- whatever pass 11859 // change the loop to make a trip count go from could not compute to 11860 // computable or vice-versa *should have* invalidated SCEV. However, we 11861 // choose not to assert here (for now) since we don't want false 11862 // positives. 11863 continue; 11864 } 11865 11866 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11867 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11868 // not propagate undef aggressively). This means we can (and do) fail 11869 // verification in cases where a transform makes the trip count of a loop 11870 // go from "undef" to "undef+1" (say). The transform is fine, since in 11871 // both cases the loop iterates "undef" times, but SCEV thinks we 11872 // increased the trip count of the loop by 1 incorrectly. 11873 continue; 11874 } 11875 11876 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11877 SE.getTypeSizeInBits(NewBECount->getType())) 11878 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11879 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11880 SE.getTypeSizeInBits(NewBECount->getType())) 11881 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11882 11883 auto *ConstantDelta = 11884 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 11885 11886 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 11887 dbgs() << "Trip Count Changed!\n"; 11888 dbgs() << "Old: " << *CurBECount << "\n"; 11889 dbgs() << "New: " << *NewBECount << "\n"; 11890 dbgs() << "Delta: " << *ConstantDelta << "\n"; 11891 std::abort(); 11892 } 11893 } 11894 } 11895 11896 bool ScalarEvolution::invalidate( 11897 Function &F, const PreservedAnalyses &PA, 11898 FunctionAnalysisManager::Invalidator &Inv) { 11899 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11900 // of its dependencies is invalidated. 11901 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11902 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11903 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11904 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11905 Inv.invalidate<LoopAnalysis>(F, PA); 11906 } 11907 11908 AnalysisKey ScalarEvolutionAnalysis::Key; 11909 11910 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11911 FunctionAnalysisManager &AM) { 11912 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11913 AM.getResult<AssumptionAnalysis>(F), 11914 AM.getResult<DominatorTreeAnalysis>(F), 11915 AM.getResult<LoopAnalysis>(F)); 11916 } 11917 11918 PreservedAnalyses 11919 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11920 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11921 return PreservedAnalyses::all(); 11922 } 11923 11924 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 11925 "Scalar Evolution Analysis", false, true) 11926 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 11927 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 11928 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 11929 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 11930 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 11931 "Scalar Evolution Analysis", false, true) 11932 11933 char ScalarEvolutionWrapperPass::ID = 0; 11934 11935 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 11936 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 11937 } 11938 11939 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 11940 SE.reset(new ScalarEvolution( 11941 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 11942 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 11943 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 11944 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 11945 return false; 11946 } 11947 11948 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 11949 11950 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 11951 SE->print(OS); 11952 } 11953 11954 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 11955 if (!VerifySCEV) 11956 return; 11957 11958 SE->verify(); 11959 } 11960 11961 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 11962 AU.setPreservesAll(); 11963 AU.addRequiredTransitive<AssumptionCacheTracker>(); 11964 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 11965 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 11966 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 11967 } 11968 11969 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 11970 const SCEV *RHS) { 11971 FoldingSetNodeID ID; 11972 assert(LHS->getType() == RHS->getType() && 11973 "Type mismatch between LHS and RHS"); 11974 // Unique this node based on the arguments 11975 ID.AddInteger(SCEVPredicate::P_Equal); 11976 ID.AddPointer(LHS); 11977 ID.AddPointer(RHS); 11978 void *IP = nullptr; 11979 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11980 return S; 11981 SCEVEqualPredicate *Eq = new (SCEVAllocator) 11982 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 11983 UniquePreds.InsertNode(Eq, IP); 11984 return Eq; 11985 } 11986 11987 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 11988 const SCEVAddRecExpr *AR, 11989 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11990 FoldingSetNodeID ID; 11991 // Unique this node based on the arguments 11992 ID.AddInteger(SCEVPredicate::P_Wrap); 11993 ID.AddPointer(AR); 11994 ID.AddInteger(AddedFlags); 11995 void *IP = nullptr; 11996 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11997 return S; 11998 auto *OF = new (SCEVAllocator) 11999 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12000 UniquePreds.InsertNode(OF, IP); 12001 return OF; 12002 } 12003 12004 namespace { 12005 12006 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12007 public: 12008 12009 /// Rewrites \p S in the context of a loop L and the SCEV predication 12010 /// infrastructure. 12011 /// 12012 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12013 /// equivalences present in \p Pred. 12014 /// 12015 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12016 /// \p NewPreds such that the result will be an AddRecExpr. 12017 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12018 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12019 SCEVUnionPredicate *Pred) { 12020 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12021 return Rewriter.visit(S); 12022 } 12023 12024 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12025 if (Pred) { 12026 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12027 for (auto *Pred : ExprPreds) 12028 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12029 if (IPred->getLHS() == Expr) 12030 return IPred->getRHS(); 12031 } 12032 return convertToAddRecWithPreds(Expr); 12033 } 12034 12035 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12036 const SCEV *Operand = visit(Expr->getOperand()); 12037 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12038 if (AR && AR->getLoop() == L && AR->isAffine()) { 12039 // This couldn't be folded because the operand didn't have the nuw 12040 // flag. Add the nusw flag as an assumption that we could make. 12041 const SCEV *Step = AR->getStepRecurrence(SE); 12042 Type *Ty = Expr->getType(); 12043 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12044 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12045 SE.getSignExtendExpr(Step, Ty), L, 12046 AR->getNoWrapFlags()); 12047 } 12048 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12049 } 12050 12051 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12052 const SCEV *Operand = visit(Expr->getOperand()); 12053 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12054 if (AR && AR->getLoop() == L && AR->isAffine()) { 12055 // This couldn't be folded because the operand didn't have the nsw 12056 // flag. Add the nssw flag as an assumption that we could make. 12057 const SCEV *Step = AR->getStepRecurrence(SE); 12058 Type *Ty = Expr->getType(); 12059 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12060 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12061 SE.getSignExtendExpr(Step, Ty), L, 12062 AR->getNoWrapFlags()); 12063 } 12064 return SE.getSignExtendExpr(Operand, Expr->getType()); 12065 } 12066 12067 private: 12068 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12069 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12070 SCEVUnionPredicate *Pred) 12071 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12072 12073 bool addOverflowAssumption(const SCEVPredicate *P) { 12074 if (!NewPreds) { 12075 // Check if we've already made this assumption. 12076 return Pred && Pred->implies(P); 12077 } 12078 NewPreds->insert(P); 12079 return true; 12080 } 12081 12082 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12083 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12084 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12085 return addOverflowAssumption(A); 12086 } 12087 12088 // If \p Expr represents a PHINode, we try to see if it can be represented 12089 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12090 // to add this predicate as a runtime overflow check, we return the AddRec. 12091 // If \p Expr does not meet these conditions (is not a PHI node, or we 12092 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12093 // return \p Expr. 12094 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12095 if (!isa<PHINode>(Expr->getValue())) 12096 return Expr; 12097 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12098 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12099 if (!PredicatedRewrite) 12100 return Expr; 12101 for (auto *P : PredicatedRewrite->second){ 12102 // Wrap predicates from outer loops are not supported. 12103 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12104 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12105 if (L != AR->getLoop()) 12106 return Expr; 12107 } 12108 if (!addOverflowAssumption(P)) 12109 return Expr; 12110 } 12111 return PredicatedRewrite->first; 12112 } 12113 12114 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12115 SCEVUnionPredicate *Pred; 12116 const Loop *L; 12117 }; 12118 12119 } // end anonymous namespace 12120 12121 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12122 SCEVUnionPredicate &Preds) { 12123 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12124 } 12125 12126 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12127 const SCEV *S, const Loop *L, 12128 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12129 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12130 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12131 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12132 12133 if (!AddRec) 12134 return nullptr; 12135 12136 // Since the transformation was successful, we can now transfer the SCEV 12137 // predicates. 12138 for (auto *P : TransformPreds) 12139 Preds.insert(P); 12140 12141 return AddRec; 12142 } 12143 12144 /// SCEV predicates 12145 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12146 SCEVPredicateKind Kind) 12147 : FastID(ID), Kind(Kind) {} 12148 12149 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12150 const SCEV *LHS, const SCEV *RHS) 12151 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12152 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12153 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12154 } 12155 12156 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12157 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12158 12159 if (!Op) 12160 return false; 12161 12162 return Op->LHS == LHS && Op->RHS == RHS; 12163 } 12164 12165 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12166 12167 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12168 12169 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12170 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12171 } 12172 12173 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12174 const SCEVAddRecExpr *AR, 12175 IncrementWrapFlags Flags) 12176 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12177 12178 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12179 12180 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12181 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12182 12183 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12184 } 12185 12186 bool SCEVWrapPredicate::isAlwaysTrue() const { 12187 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12188 IncrementWrapFlags IFlags = Flags; 12189 12190 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12191 IFlags = clearFlags(IFlags, IncrementNSSW); 12192 12193 return IFlags == IncrementAnyWrap; 12194 } 12195 12196 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12197 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12198 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12199 OS << "<nusw>"; 12200 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12201 OS << "<nssw>"; 12202 OS << "\n"; 12203 } 12204 12205 SCEVWrapPredicate::IncrementWrapFlags 12206 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12207 ScalarEvolution &SE) { 12208 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12209 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12210 12211 // We can safely transfer the NSW flag as NSSW. 12212 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12213 ImpliedFlags = IncrementNSSW; 12214 12215 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12216 // If the increment is positive, the SCEV NUW flag will also imply the 12217 // WrapPredicate NUSW flag. 12218 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12219 if (Step->getValue()->getValue().isNonNegative()) 12220 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12221 } 12222 12223 return ImpliedFlags; 12224 } 12225 12226 /// Union predicates don't get cached so create a dummy set ID for it. 12227 SCEVUnionPredicate::SCEVUnionPredicate() 12228 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12229 12230 bool SCEVUnionPredicate::isAlwaysTrue() const { 12231 return all_of(Preds, 12232 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12233 } 12234 12235 ArrayRef<const SCEVPredicate *> 12236 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12237 auto I = SCEVToPreds.find(Expr); 12238 if (I == SCEVToPreds.end()) 12239 return ArrayRef<const SCEVPredicate *>(); 12240 return I->second; 12241 } 12242 12243 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12244 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12245 return all_of(Set->Preds, 12246 [this](const SCEVPredicate *I) { return this->implies(I); }); 12247 12248 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12249 if (ScevPredsIt == SCEVToPreds.end()) 12250 return false; 12251 auto &SCEVPreds = ScevPredsIt->second; 12252 12253 return any_of(SCEVPreds, 12254 [N](const SCEVPredicate *I) { return I->implies(N); }); 12255 } 12256 12257 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12258 12259 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12260 for (auto Pred : Preds) 12261 Pred->print(OS, Depth); 12262 } 12263 12264 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12265 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12266 for (auto Pred : Set->Preds) 12267 add(Pred); 12268 return; 12269 } 12270 12271 if (implies(N)) 12272 return; 12273 12274 const SCEV *Key = N->getExpr(); 12275 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12276 " associated expression!"); 12277 12278 SCEVToPreds[Key].push_back(N); 12279 Preds.push_back(N); 12280 } 12281 12282 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12283 Loop &L) 12284 : SE(SE), L(L) {} 12285 12286 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12287 const SCEV *Expr = SE.getSCEV(V); 12288 RewriteEntry &Entry = RewriteMap[Expr]; 12289 12290 // If we already have an entry and the version matches, return it. 12291 if (Entry.second && Generation == Entry.first) 12292 return Entry.second; 12293 12294 // We found an entry but it's stale. Rewrite the stale entry 12295 // according to the current predicate. 12296 if (Entry.second) 12297 Expr = Entry.second; 12298 12299 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12300 Entry = {Generation, NewSCEV}; 12301 12302 return NewSCEV; 12303 } 12304 12305 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12306 if (!BackedgeCount) { 12307 SCEVUnionPredicate BackedgePred; 12308 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12309 addPredicate(BackedgePred); 12310 } 12311 return BackedgeCount; 12312 } 12313 12314 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12315 if (Preds.implies(&Pred)) 12316 return; 12317 Preds.add(&Pred); 12318 updateGeneration(); 12319 } 12320 12321 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12322 return Preds; 12323 } 12324 12325 void PredicatedScalarEvolution::updateGeneration() { 12326 // If the generation number wrapped recompute everything. 12327 if (++Generation == 0) { 12328 for (auto &II : RewriteMap) { 12329 const SCEV *Rewritten = II.second.second; 12330 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12331 } 12332 } 12333 } 12334 12335 void PredicatedScalarEvolution::setNoOverflow( 12336 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12337 const SCEV *Expr = getSCEV(V); 12338 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12339 12340 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12341 12342 // Clear the statically implied flags. 12343 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12344 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12345 12346 auto II = FlagsMap.insert({V, Flags}); 12347 if (!II.second) 12348 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12349 } 12350 12351 bool PredicatedScalarEvolution::hasNoOverflow( 12352 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12353 const SCEV *Expr = getSCEV(V); 12354 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12355 12356 Flags = SCEVWrapPredicate::clearFlags( 12357 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12358 12359 auto II = FlagsMap.find(V); 12360 12361 if (II != FlagsMap.end()) 12362 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12363 12364 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12365 } 12366 12367 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12368 const SCEV *Expr = this->getSCEV(V); 12369 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12370 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12371 12372 if (!New) 12373 return nullptr; 12374 12375 for (auto *P : NewPreds) 12376 Preds.add(P); 12377 12378 updateGeneration(); 12379 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12380 return New; 12381 } 12382 12383 PredicatedScalarEvolution::PredicatedScalarEvolution( 12384 const PredicatedScalarEvolution &Init) 12385 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12386 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12387 for (const auto &I : Init.FlagsMap) 12388 FlagsMap.insert(I); 12389 } 12390 12391 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12392 // For each block. 12393 for (auto *BB : L.getBlocks()) 12394 for (auto &I : *BB) { 12395 if (!SE.isSCEVable(I.getType())) 12396 continue; 12397 12398 auto *Expr = SE.getSCEV(&I); 12399 auto II = RewriteMap.find(Expr); 12400 12401 if (II == RewriteMap.end()) 12402 continue; 12403 12404 // Don't print things that are not interesting. 12405 if (II->second.second == Expr) 12406 continue; 12407 12408 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12409 OS.indent(Depth + 2) << *Expr << "\n"; 12410 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12411 } 12412 } 12413 12414 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12415 // arbitrary expressions. 12416 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12417 // 4, A / B becomes X / 8). 12418 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12419 const SCEV *&RHS) { 12420 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12421 if (Add == nullptr || Add->getNumOperands() != 2) 12422 return false; 12423 12424 const SCEV *A = Add->getOperand(1); 12425 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12426 12427 if (Mul == nullptr) 12428 return false; 12429 12430 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12431 // (SomeExpr + (-(SomeExpr / B) * B)). 12432 if (Expr == getURemExpr(A, B)) { 12433 LHS = A; 12434 RHS = B; 12435 return true; 12436 } 12437 return false; 12438 }; 12439 12440 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12441 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12442 return MatchURemWithDivisor(Mul->getOperand(1)) || 12443 MatchURemWithDivisor(Mul->getOperand(2)); 12444 12445 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12446 if (Mul->getNumOperands() == 2) 12447 return MatchURemWithDivisor(Mul->getOperand(1)) || 12448 MatchURemWithDivisor(Mul->getOperand(0)) || 12449 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12450 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12451 return false; 12452 } 12453