1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the implementation of the scalar evolution analysis 11 // engine, which is used primarily to analyze expressions involving induction 12 // variables in loops. 13 // 14 // There are several aspects to this library. First is the representation of 15 // scalar expressions, which are represented as subclasses of the SCEV class. 16 // These classes are used to represent certain types of subexpressions that we 17 // can handle. We only create one SCEV of a particular shape, so 18 // pointer-comparisons for equality are legal. 19 // 20 // One important aspect of the SCEV objects is that they are never cyclic, even 21 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 23 // recurrence) then we represent it directly as a recurrence node, otherwise we 24 // represent it as a SCEVUnknown node. 25 // 26 // In addition to being able to represent expressions of various types, we also 27 // have folders that are used to build the *canonical* representation for a 28 // particular expression. These folders are capable of using a variety of 29 // rewrite rules to simplify the expressions. 30 // 31 // Once the folders are defined, we can implement the more interesting 32 // higher-level code, such as the code that recognizes PHI nodes of various 33 // types, computes the execution count of a loop, etc. 34 // 35 // TODO: We should use these routines and value representations to implement 36 // dependence analysis! 37 // 38 //===----------------------------------------------------------------------===// 39 // 40 // There are several good references for the techniques used in this analysis. 41 // 42 // Chains of recurrences -- a method to expedite the evaluation 43 // of closed-form functions 44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 45 // 46 // On computational properties of chains of recurrences 47 // Eugene V. Zima 48 // 49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 50 // Robert A. van Engelen 51 // 52 // Efficient Symbolic Analysis for Optimizing Compilers 53 // Robert A. van Engelen 54 // 55 // Using the chains of recurrences algebra for data dependence testing and 56 // induction variable substitution 57 // MS Thesis, Johnie Birch 58 // 59 //===----------------------------------------------------------------------===// 60 61 #include "llvm/Analysis/ScalarEvolution.h" 62 #include "llvm/ADT/APInt.h" 63 #include "llvm/ADT/ArrayRef.h" 64 #include "llvm/ADT/DenseMap.h" 65 #include "llvm/ADT/DepthFirstIterator.h" 66 #include "llvm/ADT/EquivalenceClasses.h" 67 #include "llvm/ADT/FoldingSet.h" 68 #include "llvm/ADT/None.h" 69 #include "llvm/ADT/Optional.h" 70 #include "llvm/ADT/STLExtras.h" 71 #include "llvm/ADT/ScopeExit.h" 72 #include "llvm/ADT/Sequence.h" 73 #include "llvm/ADT/SetVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallSet.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/Statistic.h" 78 #include "llvm/ADT/StringRef.h" 79 #include "llvm/Analysis/AssumptionCache.h" 80 #include "llvm/Analysis/ConstantFolding.h" 81 #include "llvm/Analysis/InstructionSimplify.h" 82 #include "llvm/Analysis/LoopInfo.h" 83 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 84 #include "llvm/Analysis/TargetLibraryInfo.h" 85 #include "llvm/Analysis/ValueTracking.h" 86 #include "llvm/IR/Argument.h" 87 #include "llvm/IR/BasicBlock.h" 88 #include "llvm/IR/CFG.h" 89 #include "llvm/IR/CallSite.h" 90 #include "llvm/IR/Constant.h" 91 #include "llvm/IR/ConstantRange.h" 92 #include "llvm/IR/Constants.h" 93 #include "llvm/IR/DataLayout.h" 94 #include "llvm/IR/DerivedTypes.h" 95 #include "llvm/IR/Dominators.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/GlobalAlias.h" 98 #include "llvm/IR/GlobalValue.h" 99 #include "llvm/IR/GlobalVariable.h" 100 #include "llvm/IR/InstIterator.h" 101 #include "llvm/IR/InstrTypes.h" 102 #include "llvm/IR/Instruction.h" 103 #include "llvm/IR/Instructions.h" 104 #include "llvm/IR/IntrinsicInst.h" 105 #include "llvm/IR/Intrinsics.h" 106 #include "llvm/IR/LLVMContext.h" 107 #include "llvm/IR/Metadata.h" 108 #include "llvm/IR/Operator.h" 109 #include "llvm/IR/PatternMatch.h" 110 #include "llvm/IR/Type.h" 111 #include "llvm/IR/Use.h" 112 #include "llvm/IR/User.h" 113 #include "llvm/IR/Value.h" 114 #include "llvm/Pass.h" 115 #include "llvm/Support/Casting.h" 116 #include "llvm/Support/CommandLine.h" 117 #include "llvm/Support/Compiler.h" 118 #include "llvm/Support/Debug.h" 119 #include "llvm/Support/ErrorHandling.h" 120 #include "llvm/Support/KnownBits.h" 121 #include "llvm/Support/SaveAndRestore.h" 122 #include "llvm/Support/raw_ostream.h" 123 #include <algorithm> 124 #include <cassert> 125 #include <climits> 126 #include <cstddef> 127 #include <cstdint> 128 #include <cstdlib> 129 #include <map> 130 #include <memory> 131 #include <tuple> 132 #include <utility> 133 #include <vector> 134 135 using namespace llvm; 136 137 #define DEBUG_TYPE "scalar-evolution" 138 139 STATISTIC(NumArrayLenItCounts, 140 "Number of trip counts computed with array length"); 141 STATISTIC(NumTripCountsComputed, 142 "Number of loops with predictable loop counts"); 143 STATISTIC(NumTripCountsNotComputed, 144 "Number of loops without predictable loop counts"); 145 STATISTIC(NumBruteForceTripCountsComputed, 146 "Number of loops with trip counts computed by force"); 147 148 static cl::opt<unsigned> 149 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 150 cl::desc("Maximum number of iterations SCEV will " 151 "symbolically execute a constant " 152 "derived loop"), 153 cl::init(100)); 154 155 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 156 static cl::opt<bool> VerifySCEV( 157 "verify-scev", cl::Hidden, 158 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 159 static cl::opt<bool> 160 VerifySCEVMap("verify-scev-maps", cl::Hidden, 161 cl::desc("Verify no dangling value in ScalarEvolution's " 162 "ExprValueMap (slow)")); 163 164 static cl::opt<unsigned> MulOpsInlineThreshold( 165 "scev-mulops-inline-threshold", cl::Hidden, 166 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 167 cl::init(32)); 168 169 static cl::opt<unsigned> AddOpsInlineThreshold( 170 "scev-addops-inline-threshold", cl::Hidden, 171 cl::desc("Threshold for inlining addition operands into a SCEV"), 172 cl::init(500)); 173 174 static cl::opt<unsigned> MaxSCEVCompareDepth( 175 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 176 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 177 cl::init(32)); 178 179 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 180 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 181 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 182 cl::init(2)); 183 184 static cl::opt<unsigned> MaxValueCompareDepth( 185 "scalar-evolution-max-value-compare-depth", cl::Hidden, 186 cl::desc("Maximum depth of recursive value complexity comparisons"), 187 cl::init(2)); 188 189 static cl::opt<unsigned> 190 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 191 cl::desc("Maximum depth of recursive arithmetics"), 192 cl::init(32)); 193 194 static cl::opt<unsigned> MaxConstantEvolvingDepth( 195 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 196 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 197 198 static cl::opt<unsigned> 199 MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden, 200 cl::desc("Maximum depth of recursive SExt/ZExt"), 201 cl::init(8)); 202 203 static cl::opt<unsigned> 204 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 205 cl::desc("Max coefficients in AddRec during evolving"), 206 cl::init(16)); 207 208 //===----------------------------------------------------------------------===// 209 // SCEV class definitions 210 //===----------------------------------------------------------------------===// 211 212 //===----------------------------------------------------------------------===// 213 // Implementation of the SCEV class. 214 // 215 216 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 217 LLVM_DUMP_METHOD void SCEV::dump() const { 218 print(dbgs()); 219 dbgs() << '\n'; 220 } 221 #endif 222 223 void SCEV::print(raw_ostream &OS) const { 224 switch (static_cast<SCEVTypes>(getSCEVType())) { 225 case scConstant: 226 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 227 return; 228 case scTruncate: { 229 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 230 const SCEV *Op = Trunc->getOperand(); 231 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 232 << *Trunc->getType() << ")"; 233 return; 234 } 235 case scZeroExtend: { 236 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 237 const SCEV *Op = ZExt->getOperand(); 238 OS << "(zext " << *Op->getType() << " " << *Op << " to " 239 << *ZExt->getType() << ")"; 240 return; 241 } 242 case scSignExtend: { 243 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 244 const SCEV *Op = SExt->getOperand(); 245 OS << "(sext " << *Op->getType() << " " << *Op << " to " 246 << *SExt->getType() << ")"; 247 return; 248 } 249 case scAddRecExpr: { 250 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 251 OS << "{" << *AR->getOperand(0); 252 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 253 OS << ",+," << *AR->getOperand(i); 254 OS << "}<"; 255 if (AR->hasNoUnsignedWrap()) 256 OS << "nuw><"; 257 if (AR->hasNoSignedWrap()) 258 OS << "nsw><"; 259 if (AR->hasNoSelfWrap() && 260 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 261 OS << "nw><"; 262 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 263 OS << ">"; 264 return; 265 } 266 case scAddExpr: 267 case scMulExpr: 268 case scUMaxExpr: 269 case scSMaxExpr: { 270 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 271 const char *OpStr = nullptr; 272 switch (NAry->getSCEVType()) { 273 case scAddExpr: OpStr = " + "; break; 274 case scMulExpr: OpStr = " * "; break; 275 case scUMaxExpr: OpStr = " umax "; break; 276 case scSMaxExpr: OpStr = " smax "; break; 277 } 278 OS << "("; 279 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 280 I != E; ++I) { 281 OS << **I; 282 if (std::next(I) != E) 283 OS << OpStr; 284 } 285 OS << ")"; 286 switch (NAry->getSCEVType()) { 287 case scAddExpr: 288 case scMulExpr: 289 if (NAry->hasNoUnsignedWrap()) 290 OS << "<nuw>"; 291 if (NAry->hasNoSignedWrap()) 292 OS << "<nsw>"; 293 } 294 return; 295 } 296 case scUDivExpr: { 297 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 298 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 299 return; 300 } 301 case scUnknown: { 302 const SCEVUnknown *U = cast<SCEVUnknown>(this); 303 Type *AllocTy; 304 if (U->isSizeOf(AllocTy)) { 305 OS << "sizeof(" << *AllocTy << ")"; 306 return; 307 } 308 if (U->isAlignOf(AllocTy)) { 309 OS << "alignof(" << *AllocTy << ")"; 310 return; 311 } 312 313 Type *CTy; 314 Constant *FieldNo; 315 if (U->isOffsetOf(CTy, FieldNo)) { 316 OS << "offsetof(" << *CTy << ", "; 317 FieldNo->printAsOperand(OS, false); 318 OS << ")"; 319 return; 320 } 321 322 // Otherwise just print it normally. 323 U->getValue()->printAsOperand(OS, false); 324 return; 325 } 326 case scCouldNotCompute: 327 OS << "***COULDNOTCOMPUTE***"; 328 return; 329 } 330 llvm_unreachable("Unknown SCEV kind!"); 331 } 332 333 Type *SCEV::getType() const { 334 switch (static_cast<SCEVTypes>(getSCEVType())) { 335 case scConstant: 336 return cast<SCEVConstant>(this)->getType(); 337 case scTruncate: 338 case scZeroExtend: 339 case scSignExtend: 340 return cast<SCEVCastExpr>(this)->getType(); 341 case scAddRecExpr: 342 case scMulExpr: 343 case scUMaxExpr: 344 case scSMaxExpr: 345 return cast<SCEVNAryExpr>(this)->getType(); 346 case scAddExpr: 347 return cast<SCEVAddExpr>(this)->getType(); 348 case scUDivExpr: 349 return cast<SCEVUDivExpr>(this)->getType(); 350 case scUnknown: 351 return cast<SCEVUnknown>(this)->getType(); 352 case scCouldNotCompute: 353 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 354 } 355 llvm_unreachable("Unknown SCEV kind!"); 356 } 357 358 bool SCEV::isZero() const { 359 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 360 return SC->getValue()->isZero(); 361 return false; 362 } 363 364 bool SCEV::isOne() const { 365 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 366 return SC->getValue()->isOne(); 367 return false; 368 } 369 370 bool SCEV::isAllOnesValue() const { 371 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 372 return SC->getValue()->isMinusOne(); 373 return false; 374 } 375 376 bool SCEV::isNonConstantNegative() const { 377 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 378 if (!Mul) return false; 379 380 // If there is a constant factor, it will be first. 381 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 382 if (!SC) return false; 383 384 // Return true if the value is negative, this matches things like (-42 * V). 385 return SC->getAPInt().isNegative(); 386 } 387 388 SCEVCouldNotCompute::SCEVCouldNotCompute() : 389 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 390 391 bool SCEVCouldNotCompute::classof(const SCEV *S) { 392 return S->getSCEVType() == scCouldNotCompute; 393 } 394 395 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 396 FoldingSetNodeID ID; 397 ID.AddInteger(scConstant); 398 ID.AddPointer(V); 399 void *IP = nullptr; 400 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 401 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 402 UniqueSCEVs.InsertNode(S, IP); 403 return S; 404 } 405 406 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 407 return getConstant(ConstantInt::get(getContext(), Val)); 408 } 409 410 const SCEV * 411 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 412 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 413 return getConstant(ConstantInt::get(ITy, V, isSigned)); 414 } 415 416 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 417 unsigned SCEVTy, const SCEV *op, Type *ty) 418 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 419 420 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 421 const SCEV *op, Type *ty) 422 : SCEVCastExpr(ID, scTruncate, op, ty) { 423 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 424 (Ty->isIntegerTy() || Ty->isPointerTy()) && 425 "Cannot truncate non-integer value!"); 426 } 427 428 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 429 const SCEV *op, Type *ty) 430 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 431 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 432 (Ty->isIntegerTy() || Ty->isPointerTy()) && 433 "Cannot zero extend non-integer value!"); 434 } 435 436 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 437 const SCEV *op, Type *ty) 438 : SCEVCastExpr(ID, scSignExtend, op, ty) { 439 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 440 (Ty->isIntegerTy() || Ty->isPointerTy()) && 441 "Cannot sign extend non-integer value!"); 442 } 443 444 void SCEVUnknown::deleted() { 445 // Clear this SCEVUnknown from various maps. 446 SE->forgetMemoizedResults(this); 447 448 // Remove this SCEVUnknown from the uniquing map. 449 SE->UniqueSCEVs.RemoveNode(this); 450 451 // Release the value. 452 setValPtr(nullptr); 453 } 454 455 void SCEVUnknown::allUsesReplacedWith(Value *New) { 456 // Remove this SCEVUnknown from the uniquing map. 457 SE->UniqueSCEVs.RemoveNode(this); 458 459 // Update this SCEVUnknown to point to the new value. This is needed 460 // because there may still be outstanding SCEVs which still point to 461 // this SCEVUnknown. 462 setValPtr(New); 463 } 464 465 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 466 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 467 if (VCE->getOpcode() == Instruction::PtrToInt) 468 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 469 if (CE->getOpcode() == Instruction::GetElementPtr && 470 CE->getOperand(0)->isNullValue() && 471 CE->getNumOperands() == 2) 472 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 473 if (CI->isOne()) { 474 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 475 ->getElementType(); 476 return true; 477 } 478 479 return false; 480 } 481 482 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 483 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 484 if (VCE->getOpcode() == Instruction::PtrToInt) 485 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 486 if (CE->getOpcode() == Instruction::GetElementPtr && 487 CE->getOperand(0)->isNullValue()) { 488 Type *Ty = 489 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 490 if (StructType *STy = dyn_cast<StructType>(Ty)) 491 if (!STy->isPacked() && 492 CE->getNumOperands() == 3 && 493 CE->getOperand(1)->isNullValue()) { 494 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 495 if (CI->isOne() && 496 STy->getNumElements() == 2 && 497 STy->getElementType(0)->isIntegerTy(1)) { 498 AllocTy = STy->getElementType(1); 499 return true; 500 } 501 } 502 } 503 504 return false; 505 } 506 507 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 508 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 509 if (VCE->getOpcode() == Instruction::PtrToInt) 510 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 511 if (CE->getOpcode() == Instruction::GetElementPtr && 512 CE->getNumOperands() == 3 && 513 CE->getOperand(0)->isNullValue() && 514 CE->getOperand(1)->isNullValue()) { 515 Type *Ty = 516 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 517 // Ignore vector types here so that ScalarEvolutionExpander doesn't 518 // emit getelementptrs that index into vectors. 519 if (Ty->isStructTy() || Ty->isArrayTy()) { 520 CTy = Ty; 521 FieldNo = CE->getOperand(2); 522 return true; 523 } 524 } 525 526 return false; 527 } 528 529 //===----------------------------------------------------------------------===// 530 // SCEV Utilities 531 //===----------------------------------------------------------------------===// 532 533 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 534 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 535 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 536 /// have been previously deemed to be "equally complex" by this routine. It is 537 /// intended to avoid exponential time complexity in cases like: 538 /// 539 /// %a = f(%x, %y) 540 /// %b = f(%a, %a) 541 /// %c = f(%b, %b) 542 /// 543 /// %d = f(%x, %y) 544 /// %e = f(%d, %d) 545 /// %f = f(%e, %e) 546 /// 547 /// CompareValueComplexity(%f, %c) 548 /// 549 /// Since we do not continue running this routine on expression trees once we 550 /// have seen unequal values, there is no need to track them in the cache. 551 static int 552 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 553 const LoopInfo *const LI, Value *LV, Value *RV, 554 unsigned Depth) { 555 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 556 return 0; 557 558 // Order pointer values after integer values. This helps SCEVExpander form 559 // GEPs. 560 bool LIsPointer = LV->getType()->isPointerTy(), 561 RIsPointer = RV->getType()->isPointerTy(); 562 if (LIsPointer != RIsPointer) 563 return (int)LIsPointer - (int)RIsPointer; 564 565 // Compare getValueID values. 566 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 567 if (LID != RID) 568 return (int)LID - (int)RID; 569 570 // Sort arguments by their position. 571 if (const auto *LA = dyn_cast<Argument>(LV)) { 572 const auto *RA = cast<Argument>(RV); 573 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 574 return (int)LArgNo - (int)RArgNo; 575 } 576 577 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 578 const auto *RGV = cast<GlobalValue>(RV); 579 580 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 581 auto LT = GV->getLinkage(); 582 return !(GlobalValue::isPrivateLinkage(LT) || 583 GlobalValue::isInternalLinkage(LT)); 584 }; 585 586 // Use the names to distinguish the two values, but only if the 587 // names are semantically important. 588 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 589 return LGV->getName().compare(RGV->getName()); 590 } 591 592 // For instructions, compare their loop depth, and their operand count. This 593 // is pretty loose. 594 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 595 const auto *RInst = cast<Instruction>(RV); 596 597 // Compare loop depths. 598 const BasicBlock *LParent = LInst->getParent(), 599 *RParent = RInst->getParent(); 600 if (LParent != RParent) { 601 unsigned LDepth = LI->getLoopDepth(LParent), 602 RDepth = LI->getLoopDepth(RParent); 603 if (LDepth != RDepth) 604 return (int)LDepth - (int)RDepth; 605 } 606 607 // Compare the number of operands. 608 unsigned LNumOps = LInst->getNumOperands(), 609 RNumOps = RInst->getNumOperands(); 610 if (LNumOps != RNumOps) 611 return (int)LNumOps - (int)RNumOps; 612 613 for (unsigned Idx : seq(0u, LNumOps)) { 614 int Result = 615 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 616 RInst->getOperand(Idx), Depth + 1); 617 if (Result != 0) 618 return Result; 619 } 620 } 621 622 EqCacheValue.unionSets(LV, RV); 623 return 0; 624 } 625 626 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 627 // than RHS, respectively. A three-way result allows recursive comparisons to be 628 // more efficient. 629 static int CompareSCEVComplexity( 630 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 631 EquivalenceClasses<const Value *> &EqCacheValue, 632 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 633 DominatorTree &DT, unsigned Depth = 0) { 634 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 635 if (LHS == RHS) 636 return 0; 637 638 // Primarily, sort the SCEVs by their getSCEVType(). 639 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 640 if (LType != RType) 641 return (int)LType - (int)RType; 642 643 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 644 return 0; 645 // Aside from the getSCEVType() ordering, the particular ordering 646 // isn't very important except that it's beneficial to be consistent, 647 // so that (a + b) and (b + a) don't end up as different expressions. 648 switch (static_cast<SCEVTypes>(LType)) { 649 case scUnknown: { 650 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 651 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 652 653 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 654 RU->getValue(), Depth + 1); 655 if (X == 0) 656 EqCacheSCEV.unionSets(LHS, RHS); 657 return X; 658 } 659 660 case scConstant: { 661 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 662 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 663 664 // Compare constant values. 665 const APInt &LA = LC->getAPInt(); 666 const APInt &RA = RC->getAPInt(); 667 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 668 if (LBitWidth != RBitWidth) 669 return (int)LBitWidth - (int)RBitWidth; 670 return LA.ult(RA) ? -1 : 1; 671 } 672 673 case scAddRecExpr: { 674 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 675 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 676 677 // There is always a dominance between two recs that are used by one SCEV, 678 // so we can safely sort recs by loop header dominance. We require such 679 // order in getAddExpr. 680 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 681 if (LLoop != RLoop) { 682 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 683 assert(LHead != RHead && "Two loops share the same header?"); 684 if (DT.dominates(LHead, RHead)) 685 return 1; 686 else 687 assert(DT.dominates(RHead, LHead) && 688 "No dominance between recurrences used by one SCEV?"); 689 return -1; 690 } 691 692 // Addrec complexity grows with operand count. 693 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 694 if (LNumOps != RNumOps) 695 return (int)LNumOps - (int)RNumOps; 696 697 // Compare NoWrap flags. 698 if (LA->getNoWrapFlags() != RA->getNoWrapFlags()) 699 return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags(); 700 701 // Lexicographically compare. 702 for (unsigned i = 0; i != LNumOps; ++i) { 703 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 704 LA->getOperand(i), RA->getOperand(i), DT, 705 Depth + 1); 706 if (X != 0) 707 return X; 708 } 709 EqCacheSCEV.unionSets(LHS, RHS); 710 return 0; 711 } 712 713 case scAddExpr: 714 case scMulExpr: 715 case scSMaxExpr: 716 case scUMaxExpr: { 717 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 718 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 719 720 // Lexicographically compare n-ary expressions. 721 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 722 if (LNumOps != RNumOps) 723 return (int)LNumOps - (int)RNumOps; 724 725 // Compare NoWrap flags. 726 if (LC->getNoWrapFlags() != RC->getNoWrapFlags()) 727 return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags(); 728 729 for (unsigned i = 0; i != LNumOps; ++i) { 730 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 731 LC->getOperand(i), RC->getOperand(i), DT, 732 Depth + 1); 733 if (X != 0) 734 return X; 735 } 736 EqCacheSCEV.unionSets(LHS, RHS); 737 return 0; 738 } 739 740 case scUDivExpr: { 741 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 742 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 743 744 // Lexicographically compare udiv expressions. 745 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 746 RC->getLHS(), DT, Depth + 1); 747 if (X != 0) 748 return X; 749 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 750 RC->getRHS(), DT, Depth + 1); 751 if (X == 0) 752 EqCacheSCEV.unionSets(LHS, RHS); 753 return X; 754 } 755 756 case scTruncate: 757 case scZeroExtend: 758 case scSignExtend: { 759 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 760 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 761 762 // Compare cast expressions by operand. 763 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 764 LC->getOperand(), RC->getOperand(), DT, 765 Depth + 1); 766 if (X == 0) 767 EqCacheSCEV.unionSets(LHS, RHS); 768 return X; 769 } 770 771 case scCouldNotCompute: 772 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 773 } 774 llvm_unreachable("Unknown SCEV kind!"); 775 } 776 777 /// Given a list of SCEV objects, order them by their complexity, and group 778 /// objects of the same complexity together by value. When this routine is 779 /// finished, we know that any duplicates in the vector are consecutive and that 780 /// complexity is monotonically increasing. 781 /// 782 /// Note that we go take special precautions to ensure that we get deterministic 783 /// results from this routine. In other words, we don't want the results of 784 /// this to depend on where the addresses of various SCEV objects happened to 785 /// land in memory. 786 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 787 LoopInfo *LI, DominatorTree &DT) { 788 if (Ops.size() < 2) return; // Noop 789 790 EquivalenceClasses<const SCEV *> EqCacheSCEV; 791 EquivalenceClasses<const Value *> EqCacheValue; 792 if (Ops.size() == 2) { 793 // This is the common case, which also happens to be trivially simple. 794 // Special case it. 795 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 796 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 797 std::swap(LHS, RHS); 798 return; 799 } 800 801 // Do the rough sort by complexity. 802 std::stable_sort(Ops.begin(), Ops.end(), 803 [&](const SCEV *LHS, const SCEV *RHS) { 804 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 805 LHS, RHS, DT) < 0; 806 }); 807 808 // Now that we are sorted by complexity, group elements of the same 809 // complexity. Note that this is, at worst, N^2, but the vector is likely to 810 // be extremely short in practice. Note that we take this approach because we 811 // do not want to depend on the addresses of the objects we are grouping. 812 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 813 const SCEV *S = Ops[i]; 814 unsigned Complexity = S->getSCEVType(); 815 816 // If there are any objects of the same complexity and same value as this 817 // one, group them. 818 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 819 if (Ops[j] == S) { // Found a duplicate. 820 // Move it to immediately after i'th element. 821 std::swap(Ops[i+1], Ops[j]); 822 ++i; // no need to rescan it. 823 if (i == e-2) return; // Done! 824 } 825 } 826 } 827 } 828 829 // Returns the size of the SCEV S. 830 static inline int sizeOfSCEV(const SCEV *S) { 831 struct FindSCEVSize { 832 int Size = 0; 833 834 FindSCEVSize() = default; 835 836 bool follow(const SCEV *S) { 837 ++Size; 838 // Keep looking at all operands of S. 839 return true; 840 } 841 842 bool isDone() const { 843 return false; 844 } 845 }; 846 847 FindSCEVSize F; 848 SCEVTraversal<FindSCEVSize> ST(F); 849 ST.visitAll(S); 850 return F.Size; 851 } 852 853 namespace { 854 855 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 856 public: 857 // Computes the Quotient and Remainder of the division of Numerator by 858 // Denominator. 859 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 860 const SCEV *Denominator, const SCEV **Quotient, 861 const SCEV **Remainder) { 862 assert(Numerator && Denominator && "Uninitialized SCEV"); 863 864 SCEVDivision D(SE, Numerator, Denominator); 865 866 // Check for the trivial case here to avoid having to check for it in the 867 // rest of the code. 868 if (Numerator == Denominator) { 869 *Quotient = D.One; 870 *Remainder = D.Zero; 871 return; 872 } 873 874 if (Numerator->isZero()) { 875 *Quotient = D.Zero; 876 *Remainder = D.Zero; 877 return; 878 } 879 880 // A simple case when N/1. The quotient is N. 881 if (Denominator->isOne()) { 882 *Quotient = Numerator; 883 *Remainder = D.Zero; 884 return; 885 } 886 887 // Split the Denominator when it is a product. 888 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 889 const SCEV *Q, *R; 890 *Quotient = Numerator; 891 for (const SCEV *Op : T->operands()) { 892 divide(SE, *Quotient, Op, &Q, &R); 893 *Quotient = Q; 894 895 // Bail out when the Numerator is not divisible by one of the terms of 896 // the Denominator. 897 if (!R->isZero()) { 898 *Quotient = D.Zero; 899 *Remainder = Numerator; 900 return; 901 } 902 } 903 *Remainder = D.Zero; 904 return; 905 } 906 907 D.visit(Numerator); 908 *Quotient = D.Quotient; 909 *Remainder = D.Remainder; 910 } 911 912 // Except in the trivial case described above, we do not know how to divide 913 // Expr by Denominator for the following functions with empty implementation. 914 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 915 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 916 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 917 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 918 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 919 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 920 void visitUnknown(const SCEVUnknown *Numerator) {} 921 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 922 923 void visitConstant(const SCEVConstant *Numerator) { 924 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 925 APInt NumeratorVal = Numerator->getAPInt(); 926 APInt DenominatorVal = D->getAPInt(); 927 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 928 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 929 930 if (NumeratorBW > DenominatorBW) 931 DenominatorVal = DenominatorVal.sext(NumeratorBW); 932 else if (NumeratorBW < DenominatorBW) 933 NumeratorVal = NumeratorVal.sext(DenominatorBW); 934 935 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 936 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 937 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 938 Quotient = SE.getConstant(QuotientVal); 939 Remainder = SE.getConstant(RemainderVal); 940 return; 941 } 942 } 943 944 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 945 const SCEV *StartQ, *StartR, *StepQ, *StepR; 946 if (!Numerator->isAffine()) 947 return cannotDivide(Numerator); 948 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 949 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 950 // Bail out if the types do not match. 951 Type *Ty = Denominator->getType(); 952 if (Ty != StartQ->getType() || Ty != StartR->getType() || 953 Ty != StepQ->getType() || Ty != StepR->getType()) 954 return cannotDivide(Numerator); 955 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 956 Numerator->getNoWrapFlags()); 957 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 958 Numerator->getNoWrapFlags()); 959 } 960 961 void visitAddExpr(const SCEVAddExpr *Numerator) { 962 SmallVector<const SCEV *, 2> Qs, Rs; 963 Type *Ty = Denominator->getType(); 964 965 for (const SCEV *Op : Numerator->operands()) { 966 const SCEV *Q, *R; 967 divide(SE, Op, Denominator, &Q, &R); 968 969 // Bail out if types do not match. 970 if (Ty != Q->getType() || Ty != R->getType()) 971 return cannotDivide(Numerator); 972 973 Qs.push_back(Q); 974 Rs.push_back(R); 975 } 976 977 if (Qs.size() == 1) { 978 Quotient = Qs[0]; 979 Remainder = Rs[0]; 980 return; 981 } 982 983 Quotient = SE.getAddExpr(Qs); 984 Remainder = SE.getAddExpr(Rs); 985 } 986 987 void visitMulExpr(const SCEVMulExpr *Numerator) { 988 SmallVector<const SCEV *, 2> Qs; 989 Type *Ty = Denominator->getType(); 990 991 bool FoundDenominatorTerm = false; 992 for (const SCEV *Op : Numerator->operands()) { 993 // Bail out if types do not match. 994 if (Ty != Op->getType()) 995 return cannotDivide(Numerator); 996 997 if (FoundDenominatorTerm) { 998 Qs.push_back(Op); 999 continue; 1000 } 1001 1002 // Check whether Denominator divides one of the product operands. 1003 const SCEV *Q, *R; 1004 divide(SE, Op, Denominator, &Q, &R); 1005 if (!R->isZero()) { 1006 Qs.push_back(Op); 1007 continue; 1008 } 1009 1010 // Bail out if types do not match. 1011 if (Ty != Q->getType()) 1012 return cannotDivide(Numerator); 1013 1014 FoundDenominatorTerm = true; 1015 Qs.push_back(Q); 1016 } 1017 1018 if (FoundDenominatorTerm) { 1019 Remainder = Zero; 1020 if (Qs.size() == 1) 1021 Quotient = Qs[0]; 1022 else 1023 Quotient = SE.getMulExpr(Qs); 1024 return; 1025 } 1026 1027 if (!isa<SCEVUnknown>(Denominator)) 1028 return cannotDivide(Numerator); 1029 1030 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1031 ValueToValueMap RewriteMap; 1032 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1033 cast<SCEVConstant>(Zero)->getValue(); 1034 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1035 1036 if (Remainder->isZero()) { 1037 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1038 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1039 cast<SCEVConstant>(One)->getValue(); 1040 Quotient = 1041 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1042 return; 1043 } 1044 1045 // Quotient is (Numerator - Remainder) divided by Denominator. 1046 const SCEV *Q, *R; 1047 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1048 // This SCEV does not seem to simplify: fail the division here. 1049 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1050 return cannotDivide(Numerator); 1051 divide(SE, Diff, Denominator, &Q, &R); 1052 if (R != Zero) 1053 return cannotDivide(Numerator); 1054 Quotient = Q; 1055 } 1056 1057 private: 1058 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1059 const SCEV *Denominator) 1060 : SE(S), Denominator(Denominator) { 1061 Zero = SE.getZero(Denominator->getType()); 1062 One = SE.getOne(Denominator->getType()); 1063 1064 // We generally do not know how to divide Expr by Denominator. We 1065 // initialize the division to a "cannot divide" state to simplify the rest 1066 // of the code. 1067 cannotDivide(Numerator); 1068 } 1069 1070 // Convenience function for giving up on the division. We set the quotient to 1071 // be equal to zero and the remainder to be equal to the numerator. 1072 void cannotDivide(const SCEV *Numerator) { 1073 Quotient = Zero; 1074 Remainder = Numerator; 1075 } 1076 1077 ScalarEvolution &SE; 1078 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1079 }; 1080 1081 } // end anonymous namespace 1082 1083 //===----------------------------------------------------------------------===// 1084 // Simple SCEV method implementations 1085 //===----------------------------------------------------------------------===// 1086 1087 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1088 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1089 ScalarEvolution &SE, 1090 Type *ResultTy) { 1091 // Handle the simplest case efficiently. 1092 if (K == 1) 1093 return SE.getTruncateOrZeroExtend(It, ResultTy); 1094 1095 // We are using the following formula for BC(It, K): 1096 // 1097 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1098 // 1099 // Suppose, W is the bitwidth of the return value. We must be prepared for 1100 // overflow. Hence, we must assure that the result of our computation is 1101 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1102 // safe in modular arithmetic. 1103 // 1104 // However, this code doesn't use exactly that formula; the formula it uses 1105 // is something like the following, where T is the number of factors of 2 in 1106 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1107 // exponentiation: 1108 // 1109 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1110 // 1111 // This formula is trivially equivalent to the previous formula. However, 1112 // this formula can be implemented much more efficiently. The trick is that 1113 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1114 // arithmetic. To do exact division in modular arithmetic, all we have 1115 // to do is multiply by the inverse. Therefore, this step can be done at 1116 // width W. 1117 // 1118 // The next issue is how to safely do the division by 2^T. The way this 1119 // is done is by doing the multiplication step at a width of at least W + T 1120 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1121 // when we perform the division by 2^T (which is equivalent to a right shift 1122 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1123 // truncated out after the division by 2^T. 1124 // 1125 // In comparison to just directly using the first formula, this technique 1126 // is much more efficient; using the first formula requires W * K bits, 1127 // but this formula less than W + K bits. Also, the first formula requires 1128 // a division step, whereas this formula only requires multiplies and shifts. 1129 // 1130 // It doesn't matter whether the subtraction step is done in the calculation 1131 // width or the input iteration count's width; if the subtraction overflows, 1132 // the result must be zero anyway. We prefer here to do it in the width of 1133 // the induction variable because it helps a lot for certain cases; CodeGen 1134 // isn't smart enough to ignore the overflow, which leads to much less 1135 // efficient code if the width of the subtraction is wider than the native 1136 // register width. 1137 // 1138 // (It's possible to not widen at all by pulling out factors of 2 before 1139 // the multiplication; for example, K=2 can be calculated as 1140 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1141 // extra arithmetic, so it's not an obvious win, and it gets 1142 // much more complicated for K > 3.) 1143 1144 // Protection from insane SCEVs; this bound is conservative, 1145 // but it probably doesn't matter. 1146 if (K > 1000) 1147 return SE.getCouldNotCompute(); 1148 1149 unsigned W = SE.getTypeSizeInBits(ResultTy); 1150 1151 // Calculate K! / 2^T and T; we divide out the factors of two before 1152 // multiplying for calculating K! / 2^T to avoid overflow. 1153 // Other overflow doesn't matter because we only care about the bottom 1154 // W bits of the result. 1155 APInt OddFactorial(W, 1); 1156 unsigned T = 1; 1157 for (unsigned i = 3; i <= K; ++i) { 1158 APInt Mult(W, i); 1159 unsigned TwoFactors = Mult.countTrailingZeros(); 1160 T += TwoFactors; 1161 Mult.lshrInPlace(TwoFactors); 1162 OddFactorial *= Mult; 1163 } 1164 1165 // We need at least W + T bits for the multiplication step 1166 unsigned CalculationBits = W + T; 1167 1168 // Calculate 2^T, at width T+W. 1169 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1170 1171 // Calculate the multiplicative inverse of K! / 2^T; 1172 // this multiplication factor will perform the exact division by 1173 // K! / 2^T. 1174 APInt Mod = APInt::getSignedMinValue(W+1); 1175 APInt MultiplyFactor = OddFactorial.zext(W+1); 1176 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1177 MultiplyFactor = MultiplyFactor.trunc(W); 1178 1179 // Calculate the product, at width T+W 1180 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1181 CalculationBits); 1182 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1183 for (unsigned i = 1; i != K; ++i) { 1184 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1185 Dividend = SE.getMulExpr(Dividend, 1186 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1187 } 1188 1189 // Divide by 2^T 1190 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1191 1192 // Truncate the result, and divide by K! / 2^T. 1193 1194 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1195 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1196 } 1197 1198 /// Return the value of this chain of recurrences at the specified iteration 1199 /// number. We can evaluate this recurrence by multiplying each element in the 1200 /// chain by the binomial coefficient corresponding to it. In other words, we 1201 /// can evaluate {A,+,B,+,C,+,D} as: 1202 /// 1203 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1204 /// 1205 /// where BC(It, k) stands for binomial coefficient. 1206 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1207 ScalarEvolution &SE) const { 1208 const SCEV *Result = getStart(); 1209 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1210 // The computation is correct in the face of overflow provided that the 1211 // multiplication is performed _after_ the evaluation of the binomial 1212 // coefficient. 1213 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1214 if (isa<SCEVCouldNotCompute>(Coeff)) 1215 return Coeff; 1216 1217 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1218 } 1219 return Result; 1220 } 1221 1222 //===----------------------------------------------------------------------===// 1223 // SCEV Expression folder implementations 1224 //===----------------------------------------------------------------------===// 1225 1226 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1227 Type *Ty) { 1228 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1229 "This is not a truncating conversion!"); 1230 assert(isSCEVable(Ty) && 1231 "This is not a conversion to a SCEVable type!"); 1232 Ty = getEffectiveSCEVType(Ty); 1233 1234 FoldingSetNodeID ID; 1235 ID.AddInteger(scTruncate); 1236 ID.AddPointer(Op); 1237 ID.AddPointer(Ty); 1238 void *IP = nullptr; 1239 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1240 1241 // Fold if the operand is constant. 1242 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1243 return getConstant( 1244 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1245 1246 // trunc(trunc(x)) --> trunc(x) 1247 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1248 return getTruncateExpr(ST->getOperand(), Ty); 1249 1250 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1251 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1252 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1253 1254 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1255 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1256 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1257 1258 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can 1259 // eliminate all the truncates, or we replace other casts with truncates. 1260 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { 1261 SmallVector<const SCEV *, 4> Operands; 1262 bool hasTrunc = false; 1263 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { 1264 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); 1265 if (!isa<SCEVCastExpr>(SA->getOperand(i))) 1266 hasTrunc = isa<SCEVTruncateExpr>(S); 1267 Operands.push_back(S); 1268 } 1269 if (!hasTrunc) 1270 return getAddExpr(Operands); 1271 // In spite we checked in the beginning that ID is not in the cache, 1272 // it is possible that during recursion and different modification 1273 // ID came to cache, so if we found it, just return it. 1274 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1275 return S; 1276 } 1277 1278 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can 1279 // eliminate all the truncates, or we replace other casts with truncates. 1280 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { 1281 SmallVector<const SCEV *, 4> Operands; 1282 bool hasTrunc = false; 1283 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { 1284 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); 1285 if (!isa<SCEVCastExpr>(SM->getOperand(i))) 1286 hasTrunc = isa<SCEVTruncateExpr>(S); 1287 Operands.push_back(S); 1288 } 1289 if (!hasTrunc) 1290 return getMulExpr(Operands); 1291 // In spite we checked in the beginning that ID is not in the cache, 1292 // it is possible that during recursion and different modification 1293 // ID came to cache, so if we found it, just return it. 1294 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1295 return S; 1296 } 1297 1298 // If the input value is a chrec scev, truncate the chrec's operands. 1299 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1300 SmallVector<const SCEV *, 4> Operands; 1301 for (const SCEV *Op : AddRec->operands()) 1302 Operands.push_back(getTruncateExpr(Op, Ty)); 1303 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1304 } 1305 1306 // The cast wasn't folded; create an explicit cast node. We can reuse 1307 // the existing insert position since if we get here, we won't have 1308 // made any changes which would invalidate it. 1309 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1310 Op, Ty); 1311 UniqueSCEVs.InsertNode(S, IP); 1312 addToLoopUseLists(S); 1313 return S; 1314 } 1315 1316 // Get the limit of a recurrence such that incrementing by Step cannot cause 1317 // signed overflow as long as the value of the recurrence within the 1318 // loop does not exceed this limit before incrementing. 1319 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1320 ICmpInst::Predicate *Pred, 1321 ScalarEvolution *SE) { 1322 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1323 if (SE->isKnownPositive(Step)) { 1324 *Pred = ICmpInst::ICMP_SLT; 1325 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1326 SE->getSignedRangeMax(Step)); 1327 } 1328 if (SE->isKnownNegative(Step)) { 1329 *Pred = ICmpInst::ICMP_SGT; 1330 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1331 SE->getSignedRangeMin(Step)); 1332 } 1333 return nullptr; 1334 } 1335 1336 // Get the limit of a recurrence such that incrementing by Step cannot cause 1337 // unsigned overflow as long as the value of the recurrence within the loop does 1338 // not exceed this limit before incrementing. 1339 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1340 ICmpInst::Predicate *Pred, 1341 ScalarEvolution *SE) { 1342 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1343 *Pred = ICmpInst::ICMP_ULT; 1344 1345 return SE->getConstant(APInt::getMinValue(BitWidth) - 1346 SE->getUnsignedRangeMax(Step)); 1347 } 1348 1349 namespace { 1350 1351 struct ExtendOpTraitsBase { 1352 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1353 unsigned); 1354 }; 1355 1356 // Used to make code generic over signed and unsigned overflow. 1357 template <typename ExtendOp> struct ExtendOpTraits { 1358 // Members present: 1359 // 1360 // static const SCEV::NoWrapFlags WrapType; 1361 // 1362 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1363 // 1364 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1365 // ICmpInst::Predicate *Pred, 1366 // ScalarEvolution *SE); 1367 }; 1368 1369 template <> 1370 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1371 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1372 1373 static const GetExtendExprTy GetExtendExpr; 1374 1375 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1376 ICmpInst::Predicate *Pred, 1377 ScalarEvolution *SE) { 1378 return getSignedOverflowLimitForStep(Step, Pred, SE); 1379 } 1380 }; 1381 1382 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1383 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1384 1385 template <> 1386 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1387 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1388 1389 static const GetExtendExprTy GetExtendExpr; 1390 1391 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1392 ICmpInst::Predicate *Pred, 1393 ScalarEvolution *SE) { 1394 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1395 } 1396 }; 1397 1398 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1399 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1400 1401 } // end anonymous namespace 1402 1403 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1404 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1405 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1406 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1407 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1408 // expression "Step + sext/zext(PreIncAR)" is congruent with 1409 // "sext/zext(PostIncAR)" 1410 template <typename ExtendOpTy> 1411 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1412 ScalarEvolution *SE, unsigned Depth) { 1413 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1414 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1415 1416 const Loop *L = AR->getLoop(); 1417 const SCEV *Start = AR->getStart(); 1418 const SCEV *Step = AR->getStepRecurrence(*SE); 1419 1420 // Check for a simple looking step prior to loop entry. 1421 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1422 if (!SA) 1423 return nullptr; 1424 1425 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1426 // subtraction is expensive. For this purpose, perform a quick and dirty 1427 // difference, by checking for Step in the operand list. 1428 SmallVector<const SCEV *, 4> DiffOps; 1429 for (const SCEV *Op : SA->operands()) 1430 if (Op != Step) 1431 DiffOps.push_back(Op); 1432 1433 if (DiffOps.size() == SA->getNumOperands()) 1434 return nullptr; 1435 1436 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1437 // `Step`: 1438 1439 // 1. NSW/NUW flags on the step increment. 1440 auto PreStartFlags = 1441 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1442 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1443 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1444 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1445 1446 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1447 // "S+X does not sign/unsign-overflow". 1448 // 1449 1450 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1451 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1452 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1453 return PreStart; 1454 1455 // 2. Direct overflow check on the step operation's expression. 1456 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1457 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1458 const SCEV *OperandExtendedStart = 1459 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1460 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1461 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1462 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1463 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1464 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1465 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1466 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1467 } 1468 return PreStart; 1469 } 1470 1471 // 3. Loop precondition. 1472 ICmpInst::Predicate Pred; 1473 const SCEV *OverflowLimit = 1474 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1475 1476 if (OverflowLimit && 1477 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1478 return PreStart; 1479 1480 return nullptr; 1481 } 1482 1483 // Get the normalized zero or sign extended expression for this AddRec's Start. 1484 template <typename ExtendOpTy> 1485 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1486 ScalarEvolution *SE, 1487 unsigned Depth) { 1488 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1489 1490 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1491 if (!PreStart) 1492 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1493 1494 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1495 Depth), 1496 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1497 } 1498 1499 // Try to prove away overflow by looking at "nearby" add recurrences. A 1500 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1501 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1502 // 1503 // Formally: 1504 // 1505 // {S,+,X} == {S-T,+,X} + T 1506 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1507 // 1508 // If ({S-T,+,X} + T) does not overflow ... (1) 1509 // 1510 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1511 // 1512 // If {S-T,+,X} does not overflow ... (2) 1513 // 1514 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1515 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1516 // 1517 // If (S-T)+T does not overflow ... (3) 1518 // 1519 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1520 // == {Ext(S),+,Ext(X)} == LHS 1521 // 1522 // Thus, if (1), (2) and (3) are true for some T, then 1523 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1524 // 1525 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1526 // does not overflow" restricted to the 0th iteration. Therefore we only need 1527 // to check for (1) and (2). 1528 // 1529 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1530 // is `Delta` (defined below). 1531 template <typename ExtendOpTy> 1532 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1533 const SCEV *Step, 1534 const Loop *L) { 1535 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1536 1537 // We restrict `Start` to a constant to prevent SCEV from spending too much 1538 // time here. It is correct (but more expensive) to continue with a 1539 // non-constant `Start` and do a general SCEV subtraction to compute 1540 // `PreStart` below. 1541 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1542 if (!StartC) 1543 return false; 1544 1545 APInt StartAI = StartC->getAPInt(); 1546 1547 for (unsigned Delta : {-2, -1, 1, 2}) { 1548 const SCEV *PreStart = getConstant(StartAI - Delta); 1549 1550 FoldingSetNodeID ID; 1551 ID.AddInteger(scAddRecExpr); 1552 ID.AddPointer(PreStart); 1553 ID.AddPointer(Step); 1554 ID.AddPointer(L); 1555 void *IP = nullptr; 1556 const auto *PreAR = 1557 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1558 1559 // Give up if we don't already have the add recurrence we need because 1560 // actually constructing an add recurrence is relatively expensive. 1561 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1562 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1563 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1564 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1565 DeltaS, &Pred, this); 1566 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1567 return true; 1568 } 1569 } 1570 1571 return false; 1572 } 1573 1574 const SCEV * 1575 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1576 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1577 "This is not an extending conversion!"); 1578 assert(isSCEVable(Ty) && 1579 "This is not a conversion to a SCEVable type!"); 1580 Ty = getEffectiveSCEVType(Ty); 1581 1582 // Fold if the operand is constant. 1583 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1584 return getConstant( 1585 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1586 1587 // zext(zext(x)) --> zext(x) 1588 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1589 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1590 1591 // Before doing any expensive analysis, check to see if we've already 1592 // computed a SCEV for this Op and Ty. 1593 FoldingSetNodeID ID; 1594 ID.AddInteger(scZeroExtend); 1595 ID.AddPointer(Op); 1596 ID.AddPointer(Ty); 1597 void *IP = nullptr; 1598 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1599 if (Depth > MaxExtDepth) { 1600 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1601 Op, Ty); 1602 UniqueSCEVs.InsertNode(S, IP); 1603 addToLoopUseLists(S); 1604 return S; 1605 } 1606 1607 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1608 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1609 // It's possible the bits taken off by the truncate were all zero bits. If 1610 // so, we should be able to simplify this further. 1611 const SCEV *X = ST->getOperand(); 1612 ConstantRange CR = getUnsignedRange(X); 1613 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1614 unsigned NewBits = getTypeSizeInBits(Ty); 1615 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1616 CR.zextOrTrunc(NewBits))) 1617 return getTruncateOrZeroExtend(X, Ty); 1618 } 1619 1620 // If the input value is a chrec scev, and we can prove that the value 1621 // did not overflow the old, smaller, value, we can zero extend all of the 1622 // operands (often constants). This allows analysis of something like 1623 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1624 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1625 if (AR->isAffine()) { 1626 const SCEV *Start = AR->getStart(); 1627 const SCEV *Step = AR->getStepRecurrence(*this); 1628 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1629 const Loop *L = AR->getLoop(); 1630 1631 if (!AR->hasNoUnsignedWrap()) { 1632 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1633 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1634 } 1635 1636 // If we have special knowledge that this addrec won't overflow, 1637 // we don't need to do any further analysis. 1638 if (AR->hasNoUnsignedWrap()) 1639 return getAddRecExpr( 1640 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1641 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1642 1643 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1644 // Note that this serves two purposes: It filters out loops that are 1645 // simply not analyzable, and it covers the case where this code is 1646 // being called from within backedge-taken count analysis, such that 1647 // attempting to ask for the backedge-taken count would likely result 1648 // in infinite recursion. In the later case, the analysis code will 1649 // cope with a conservative value, and it will take care to purge 1650 // that value once it has finished. 1651 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1652 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1653 // Manually compute the final value for AR, checking for 1654 // overflow. 1655 1656 // Check whether the backedge-taken count can be losslessly casted to 1657 // the addrec's type. The count is always unsigned. 1658 const SCEV *CastedMaxBECount = 1659 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1660 const SCEV *RecastedMaxBECount = 1661 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1662 if (MaxBECount == RecastedMaxBECount) { 1663 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1664 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1665 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1666 SCEV::FlagAnyWrap, Depth + 1); 1667 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1668 SCEV::FlagAnyWrap, 1669 Depth + 1), 1670 WideTy, Depth + 1); 1671 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1672 const SCEV *WideMaxBECount = 1673 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1674 const SCEV *OperandExtendedAdd = 1675 getAddExpr(WideStart, 1676 getMulExpr(WideMaxBECount, 1677 getZeroExtendExpr(Step, WideTy, Depth + 1), 1678 SCEV::FlagAnyWrap, Depth + 1), 1679 SCEV::FlagAnyWrap, Depth + 1); 1680 if (ZAdd == OperandExtendedAdd) { 1681 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1682 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1683 // Return the expression with the addrec on the outside. 1684 return getAddRecExpr( 1685 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1686 Depth + 1), 1687 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1688 AR->getNoWrapFlags()); 1689 } 1690 // Similar to above, only this time treat the step value as signed. 1691 // This covers loops that count down. 1692 OperandExtendedAdd = 1693 getAddExpr(WideStart, 1694 getMulExpr(WideMaxBECount, 1695 getSignExtendExpr(Step, WideTy, Depth + 1), 1696 SCEV::FlagAnyWrap, Depth + 1), 1697 SCEV::FlagAnyWrap, Depth + 1); 1698 if (ZAdd == OperandExtendedAdd) { 1699 // Cache knowledge of AR NW, which is propagated to this AddRec. 1700 // Negative step causes unsigned wrap, but it still can't self-wrap. 1701 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1702 // Return the expression with the addrec on the outside. 1703 return getAddRecExpr( 1704 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1705 Depth + 1), 1706 getSignExtendExpr(Step, Ty, Depth + 1), L, 1707 AR->getNoWrapFlags()); 1708 } 1709 } 1710 } 1711 1712 // Normally, in the cases we can prove no-overflow via a 1713 // backedge guarding condition, we can also compute a backedge 1714 // taken count for the loop. The exceptions are assumptions and 1715 // guards present in the loop -- SCEV is not great at exploiting 1716 // these to compute max backedge taken counts, but can still use 1717 // these to prove lack of overflow. Use this fact to avoid 1718 // doing extra work that may not pay off. 1719 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1720 !AC.assumptions().empty()) { 1721 // If the backedge is guarded by a comparison with the pre-inc 1722 // value the addrec is safe. Also, if the entry is guarded by 1723 // a comparison with the start value and the backedge is 1724 // guarded by a comparison with the post-inc value, the addrec 1725 // is safe. 1726 if (isKnownPositive(Step)) { 1727 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1728 getUnsignedRangeMax(Step)); 1729 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1730 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1731 // Cache knowledge of AR NUW, which is propagated to this 1732 // AddRec. 1733 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1734 // Return the expression with the addrec on the outside. 1735 return getAddRecExpr( 1736 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1737 Depth + 1), 1738 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1739 AR->getNoWrapFlags()); 1740 } 1741 } else if (isKnownNegative(Step)) { 1742 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1743 getSignedRangeMin(Step)); 1744 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1745 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1746 // Cache knowledge of AR NW, which is propagated to this 1747 // AddRec. Negative step causes unsigned wrap, but it 1748 // still can't self-wrap. 1749 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1750 // Return the expression with the addrec on the outside. 1751 return getAddRecExpr( 1752 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1753 Depth + 1), 1754 getSignExtendExpr(Step, Ty, Depth + 1), L, 1755 AR->getNoWrapFlags()); 1756 } 1757 } 1758 } 1759 1760 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1761 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1762 return getAddRecExpr( 1763 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1764 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1765 } 1766 } 1767 1768 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1769 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1770 if (SA->hasNoUnsignedWrap()) { 1771 // If the addition does not unsign overflow then we can, by definition, 1772 // commute the zero extension with the addition operation. 1773 SmallVector<const SCEV *, 4> Ops; 1774 for (const auto *Op : SA->operands()) 1775 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1776 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1777 } 1778 } 1779 1780 // The cast wasn't folded; create an explicit cast node. 1781 // Recompute the insert position, as it may have been invalidated. 1782 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1783 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1784 Op, Ty); 1785 UniqueSCEVs.InsertNode(S, IP); 1786 addToLoopUseLists(S); 1787 return S; 1788 } 1789 1790 const SCEV * 1791 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1792 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1793 "This is not an extending conversion!"); 1794 assert(isSCEVable(Ty) && 1795 "This is not a conversion to a SCEVable type!"); 1796 Ty = getEffectiveSCEVType(Ty); 1797 1798 // Fold if the operand is constant. 1799 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1800 return getConstant( 1801 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1802 1803 // sext(sext(x)) --> sext(x) 1804 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1805 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1806 1807 // sext(zext(x)) --> zext(x) 1808 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1809 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1810 1811 // Before doing any expensive analysis, check to see if we've already 1812 // computed a SCEV for this Op and Ty. 1813 FoldingSetNodeID ID; 1814 ID.AddInteger(scSignExtend); 1815 ID.AddPointer(Op); 1816 ID.AddPointer(Ty); 1817 void *IP = nullptr; 1818 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1819 // Limit recursion depth. 1820 if (Depth > MaxExtDepth) { 1821 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1822 Op, Ty); 1823 UniqueSCEVs.InsertNode(S, IP); 1824 addToLoopUseLists(S); 1825 return S; 1826 } 1827 1828 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1829 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1830 // It's possible the bits taken off by the truncate were all sign bits. If 1831 // so, we should be able to simplify this further. 1832 const SCEV *X = ST->getOperand(); 1833 ConstantRange CR = getSignedRange(X); 1834 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1835 unsigned NewBits = getTypeSizeInBits(Ty); 1836 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1837 CR.sextOrTrunc(NewBits))) 1838 return getTruncateOrSignExtend(X, Ty); 1839 } 1840 1841 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1842 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1843 if (SA->getNumOperands() == 2) { 1844 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1845 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1846 if (SMul && SC1) { 1847 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1848 const APInt &C1 = SC1->getAPInt(); 1849 const APInt &C2 = SC2->getAPInt(); 1850 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1851 C2.ugt(C1) && C2.isPowerOf2()) 1852 return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1), 1853 getSignExtendExpr(SMul, Ty, Depth + 1), 1854 SCEV::FlagAnyWrap, Depth + 1); 1855 } 1856 } 1857 } 1858 1859 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1860 if (SA->hasNoSignedWrap()) { 1861 // If the addition does not sign overflow then we can, by definition, 1862 // commute the sign extension with the addition operation. 1863 SmallVector<const SCEV *, 4> Ops; 1864 for (const auto *Op : SA->operands()) 1865 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1866 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1867 } 1868 } 1869 // If the input value is a chrec scev, and we can prove that the value 1870 // did not overflow the old, smaller, value, we can sign extend all of the 1871 // operands (often constants). This allows analysis of something like 1872 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1873 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1874 if (AR->isAffine()) { 1875 const SCEV *Start = AR->getStart(); 1876 const SCEV *Step = AR->getStepRecurrence(*this); 1877 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1878 const Loop *L = AR->getLoop(); 1879 1880 if (!AR->hasNoSignedWrap()) { 1881 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1882 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1883 } 1884 1885 // If we have special knowledge that this addrec won't overflow, 1886 // we don't need to do any further analysis. 1887 if (AR->hasNoSignedWrap()) 1888 return getAddRecExpr( 1889 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1890 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1891 1892 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1893 // Note that this serves two purposes: It filters out loops that are 1894 // simply not analyzable, and it covers the case where this code is 1895 // being called from within backedge-taken count analysis, such that 1896 // attempting to ask for the backedge-taken count would likely result 1897 // in infinite recursion. In the later case, the analysis code will 1898 // cope with a conservative value, and it will take care to purge 1899 // that value once it has finished. 1900 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1901 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1902 // Manually compute the final value for AR, checking for 1903 // overflow. 1904 1905 // Check whether the backedge-taken count can be losslessly casted to 1906 // the addrec's type. The count is always unsigned. 1907 const SCEV *CastedMaxBECount = 1908 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1909 const SCEV *RecastedMaxBECount = 1910 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1911 if (MaxBECount == RecastedMaxBECount) { 1912 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1913 // Check whether Start+Step*MaxBECount has no signed overflow. 1914 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 1915 SCEV::FlagAnyWrap, Depth + 1); 1916 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 1917 SCEV::FlagAnyWrap, 1918 Depth + 1), 1919 WideTy, Depth + 1); 1920 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 1921 const SCEV *WideMaxBECount = 1922 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1923 const SCEV *OperandExtendedAdd = 1924 getAddExpr(WideStart, 1925 getMulExpr(WideMaxBECount, 1926 getSignExtendExpr(Step, WideTy, Depth + 1), 1927 SCEV::FlagAnyWrap, Depth + 1), 1928 SCEV::FlagAnyWrap, Depth + 1); 1929 if (SAdd == OperandExtendedAdd) { 1930 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1931 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1932 // Return the expression with the addrec on the outside. 1933 return getAddRecExpr( 1934 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1935 Depth + 1), 1936 getSignExtendExpr(Step, Ty, Depth + 1), L, 1937 AR->getNoWrapFlags()); 1938 } 1939 // Similar to above, only this time treat the step value as unsigned. 1940 // This covers loops that count up with an unsigned step. 1941 OperandExtendedAdd = 1942 getAddExpr(WideStart, 1943 getMulExpr(WideMaxBECount, 1944 getZeroExtendExpr(Step, WideTy, Depth + 1), 1945 SCEV::FlagAnyWrap, Depth + 1), 1946 SCEV::FlagAnyWrap, Depth + 1); 1947 if (SAdd == OperandExtendedAdd) { 1948 // If AR wraps around then 1949 // 1950 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1951 // => SAdd != OperandExtendedAdd 1952 // 1953 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1954 // (SAdd == OperandExtendedAdd => AR is NW) 1955 1956 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1957 1958 // Return the expression with the addrec on the outside. 1959 return getAddRecExpr( 1960 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1961 Depth + 1), 1962 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1963 AR->getNoWrapFlags()); 1964 } 1965 } 1966 } 1967 1968 // Normally, in the cases we can prove no-overflow via a 1969 // backedge guarding condition, we can also compute a backedge 1970 // taken count for the loop. The exceptions are assumptions and 1971 // guards present in the loop -- SCEV is not great at exploiting 1972 // these to compute max backedge taken counts, but can still use 1973 // these to prove lack of overflow. Use this fact to avoid 1974 // doing extra work that may not pay off. 1975 1976 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1977 !AC.assumptions().empty()) { 1978 // If the backedge is guarded by a comparison with the pre-inc 1979 // value the addrec is safe. Also, if the entry is guarded by 1980 // a comparison with the start value and the backedge is 1981 // guarded by a comparison with the post-inc value, the addrec 1982 // is safe. 1983 ICmpInst::Predicate Pred; 1984 const SCEV *OverflowLimit = 1985 getSignedOverflowLimitForStep(Step, &Pred, this); 1986 if (OverflowLimit && 1987 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1988 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 1989 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1990 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1991 return getAddRecExpr( 1992 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1993 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1994 } 1995 } 1996 1997 // If Start and Step are constants, check if we can apply this 1998 // transformation: 1999 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 2000 auto *SC1 = dyn_cast<SCEVConstant>(Start); 2001 auto *SC2 = dyn_cast<SCEVConstant>(Step); 2002 if (SC1 && SC2) { 2003 const APInt &C1 = SC1->getAPInt(); 2004 const APInt &C2 = SC2->getAPInt(); 2005 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 2006 C2.isPowerOf2()) { 2007 Start = getSignExtendExpr(Start, Ty, Depth + 1); 2008 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 2009 AR->getNoWrapFlags()); 2010 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1), 2011 SCEV::FlagAnyWrap, Depth + 1); 2012 } 2013 } 2014 2015 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2016 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2017 return getAddRecExpr( 2018 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2019 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2020 } 2021 } 2022 2023 // If the input value is provably positive and we could not simplify 2024 // away the sext build a zext instead. 2025 if (isKnownNonNegative(Op)) 2026 return getZeroExtendExpr(Op, Ty, Depth + 1); 2027 2028 // The cast wasn't folded; create an explicit cast node. 2029 // Recompute the insert position, as it may have been invalidated. 2030 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2031 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2032 Op, Ty); 2033 UniqueSCEVs.InsertNode(S, IP); 2034 addToLoopUseLists(S); 2035 return S; 2036 } 2037 2038 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2039 /// unspecified bits out to the given type. 2040 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2041 Type *Ty) { 2042 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2043 "This is not an extending conversion!"); 2044 assert(isSCEVable(Ty) && 2045 "This is not a conversion to a SCEVable type!"); 2046 Ty = getEffectiveSCEVType(Ty); 2047 2048 // Sign-extend negative constants. 2049 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2050 if (SC->getAPInt().isNegative()) 2051 return getSignExtendExpr(Op, Ty); 2052 2053 // Peel off a truncate cast. 2054 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2055 const SCEV *NewOp = T->getOperand(); 2056 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2057 return getAnyExtendExpr(NewOp, Ty); 2058 return getTruncateOrNoop(NewOp, Ty); 2059 } 2060 2061 // Next try a zext cast. If the cast is folded, use it. 2062 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2063 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2064 return ZExt; 2065 2066 // Next try a sext cast. If the cast is folded, use it. 2067 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2068 if (!isa<SCEVSignExtendExpr>(SExt)) 2069 return SExt; 2070 2071 // Force the cast to be folded into the operands of an addrec. 2072 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2073 SmallVector<const SCEV *, 4> Ops; 2074 for (const SCEV *Op : AR->operands()) 2075 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2076 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2077 } 2078 2079 // If the expression is obviously signed, use the sext cast value. 2080 if (isa<SCEVSMaxExpr>(Op)) 2081 return SExt; 2082 2083 // Absent any other information, use the zext cast value. 2084 return ZExt; 2085 } 2086 2087 /// Process the given Ops list, which is a list of operands to be added under 2088 /// the given scale, update the given map. This is a helper function for 2089 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2090 /// that would form an add expression like this: 2091 /// 2092 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2093 /// 2094 /// where A and B are constants, update the map with these values: 2095 /// 2096 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2097 /// 2098 /// and add 13 + A*B*29 to AccumulatedConstant. 2099 /// This will allow getAddRecExpr to produce this: 2100 /// 2101 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2102 /// 2103 /// This form often exposes folding opportunities that are hidden in 2104 /// the original operand list. 2105 /// 2106 /// Return true iff it appears that any interesting folding opportunities 2107 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2108 /// the common case where no interesting opportunities are present, and 2109 /// is also used as a check to avoid infinite recursion. 2110 static bool 2111 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2112 SmallVectorImpl<const SCEV *> &NewOps, 2113 APInt &AccumulatedConstant, 2114 const SCEV *const *Ops, size_t NumOperands, 2115 const APInt &Scale, 2116 ScalarEvolution &SE) { 2117 bool Interesting = false; 2118 2119 // Iterate over the add operands. They are sorted, with constants first. 2120 unsigned i = 0; 2121 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2122 ++i; 2123 // Pull a buried constant out to the outside. 2124 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2125 Interesting = true; 2126 AccumulatedConstant += Scale * C->getAPInt(); 2127 } 2128 2129 // Next comes everything else. We're especially interested in multiplies 2130 // here, but they're in the middle, so just visit the rest with one loop. 2131 for (; i != NumOperands; ++i) { 2132 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2133 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2134 APInt NewScale = 2135 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2136 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2137 // A multiplication of a constant with another add; recurse. 2138 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2139 Interesting |= 2140 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2141 Add->op_begin(), Add->getNumOperands(), 2142 NewScale, SE); 2143 } else { 2144 // A multiplication of a constant with some other value. Update 2145 // the map. 2146 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2147 const SCEV *Key = SE.getMulExpr(MulOps); 2148 auto Pair = M.insert({Key, NewScale}); 2149 if (Pair.second) { 2150 NewOps.push_back(Pair.first->first); 2151 } else { 2152 Pair.first->second += NewScale; 2153 // The map already had an entry for this value, which may indicate 2154 // a folding opportunity. 2155 Interesting = true; 2156 } 2157 } 2158 } else { 2159 // An ordinary operand. Update the map. 2160 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2161 M.insert({Ops[i], Scale}); 2162 if (Pair.second) { 2163 NewOps.push_back(Pair.first->first); 2164 } else { 2165 Pair.first->second += Scale; 2166 // The map already had an entry for this value, which may indicate 2167 // a folding opportunity. 2168 Interesting = true; 2169 } 2170 } 2171 } 2172 2173 return Interesting; 2174 } 2175 2176 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2177 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2178 // can't-overflow flags for the operation if possible. 2179 static SCEV::NoWrapFlags 2180 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2181 const SmallVectorImpl<const SCEV *> &Ops, 2182 SCEV::NoWrapFlags Flags) { 2183 using namespace std::placeholders; 2184 2185 using OBO = OverflowingBinaryOperator; 2186 2187 bool CanAnalyze = 2188 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2189 (void)CanAnalyze; 2190 assert(CanAnalyze && "don't call from other places!"); 2191 2192 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2193 SCEV::NoWrapFlags SignOrUnsignWrap = 2194 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2195 2196 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2197 auto IsKnownNonNegative = [&](const SCEV *S) { 2198 return SE->isKnownNonNegative(S); 2199 }; 2200 2201 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2202 Flags = 2203 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2204 2205 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2206 2207 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 2208 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 2209 2210 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 2211 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 2212 2213 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2214 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2215 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2216 Instruction::Add, C, OBO::NoSignedWrap); 2217 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2218 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2219 } 2220 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2221 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2222 Instruction::Add, C, OBO::NoUnsignedWrap); 2223 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2224 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2225 } 2226 } 2227 2228 return Flags; 2229 } 2230 2231 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2232 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2233 } 2234 2235 /// Get a canonical add expression, or something simpler if possible. 2236 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2237 SCEV::NoWrapFlags Flags, 2238 unsigned Depth) { 2239 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2240 "only nuw or nsw allowed"); 2241 assert(!Ops.empty() && "Cannot get empty add!"); 2242 if (Ops.size() == 1) return Ops[0]; 2243 #ifndef NDEBUG 2244 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2245 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2246 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2247 "SCEVAddExpr operand types don't match!"); 2248 #endif 2249 2250 // Sort by complexity, this groups all similar expression types together. 2251 GroupByComplexity(Ops, &LI, DT); 2252 2253 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2254 2255 // If there are any constants, fold them together. 2256 unsigned Idx = 0; 2257 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2258 ++Idx; 2259 assert(Idx < Ops.size()); 2260 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2261 // We found two constants, fold them together! 2262 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2263 if (Ops.size() == 2) return Ops[0]; 2264 Ops.erase(Ops.begin()+1); // Erase the folded element 2265 LHSC = cast<SCEVConstant>(Ops[0]); 2266 } 2267 2268 // If we are left with a constant zero being added, strip it off. 2269 if (LHSC->getValue()->isZero()) { 2270 Ops.erase(Ops.begin()); 2271 --Idx; 2272 } 2273 2274 if (Ops.size() == 1) return Ops[0]; 2275 } 2276 2277 // Limit recursion calls depth. 2278 if (Depth > MaxArithDepth) 2279 return getOrCreateAddExpr(Ops, Flags); 2280 2281 // Okay, check to see if the same value occurs in the operand list more than 2282 // once. If so, merge them together into an multiply expression. Since we 2283 // sorted the list, these values are required to be adjacent. 2284 Type *Ty = Ops[0]->getType(); 2285 bool FoundMatch = false; 2286 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2287 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2288 // Scan ahead to count how many equal operands there are. 2289 unsigned Count = 2; 2290 while (i+Count != e && Ops[i+Count] == Ops[i]) 2291 ++Count; 2292 // Merge the values into a multiply. 2293 const SCEV *Scale = getConstant(Ty, Count); 2294 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2295 if (Ops.size() == Count) 2296 return Mul; 2297 Ops[i] = Mul; 2298 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2299 --i; e -= Count - 1; 2300 FoundMatch = true; 2301 } 2302 if (FoundMatch) 2303 return getAddExpr(Ops, Flags, Depth + 1); 2304 2305 // Check for truncates. If all the operands are truncated from the same 2306 // type, see if factoring out the truncate would permit the result to be 2307 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2308 // if the contents of the resulting outer trunc fold to something simple. 2309 auto FindTruncSrcType = [&]() -> Type * { 2310 // We're ultimately looking to fold an addrec of truncs and muls of only 2311 // constants and truncs, so if we find any other types of SCEV 2312 // as operands of the addrec then we bail and return nullptr here. 2313 // Otherwise, we return the type of the operand of a trunc that we find. 2314 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2315 return T->getOperand()->getType(); 2316 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2317 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2318 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2319 return T->getOperand()->getType(); 2320 } 2321 return nullptr; 2322 }; 2323 if (auto *SrcType = FindTruncSrcType()) { 2324 SmallVector<const SCEV *, 8> LargeOps; 2325 bool Ok = true; 2326 // Check all the operands to see if they can be represented in the 2327 // source type of the truncate. 2328 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2329 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2330 if (T->getOperand()->getType() != SrcType) { 2331 Ok = false; 2332 break; 2333 } 2334 LargeOps.push_back(T->getOperand()); 2335 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2336 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2337 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2338 SmallVector<const SCEV *, 8> LargeMulOps; 2339 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2340 if (const SCEVTruncateExpr *T = 2341 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2342 if (T->getOperand()->getType() != SrcType) { 2343 Ok = false; 2344 break; 2345 } 2346 LargeMulOps.push_back(T->getOperand()); 2347 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2348 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2349 } else { 2350 Ok = false; 2351 break; 2352 } 2353 } 2354 if (Ok) 2355 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2356 } else { 2357 Ok = false; 2358 break; 2359 } 2360 } 2361 if (Ok) { 2362 // Evaluate the expression in the larger type. 2363 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1); 2364 // If it folds to something simple, use it. Otherwise, don't. 2365 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2366 return getTruncateExpr(Fold, Ty); 2367 } 2368 } 2369 2370 // Skip past any other cast SCEVs. 2371 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2372 ++Idx; 2373 2374 // If there are add operands they would be next. 2375 if (Idx < Ops.size()) { 2376 bool DeletedAdd = false; 2377 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2378 if (Ops.size() > AddOpsInlineThreshold || 2379 Add->getNumOperands() > AddOpsInlineThreshold) 2380 break; 2381 // If we have an add, expand the add operands onto the end of the operands 2382 // list. 2383 Ops.erase(Ops.begin()+Idx); 2384 Ops.append(Add->op_begin(), Add->op_end()); 2385 DeletedAdd = true; 2386 } 2387 2388 // If we deleted at least one add, we added operands to the end of the list, 2389 // and they are not necessarily sorted. Recurse to resort and resimplify 2390 // any operands we just acquired. 2391 if (DeletedAdd) 2392 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2393 } 2394 2395 // Skip over the add expression until we get to a multiply. 2396 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2397 ++Idx; 2398 2399 // Check to see if there are any folding opportunities present with 2400 // operands multiplied by constant values. 2401 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2402 uint64_t BitWidth = getTypeSizeInBits(Ty); 2403 DenseMap<const SCEV *, APInt> M; 2404 SmallVector<const SCEV *, 8> NewOps; 2405 APInt AccumulatedConstant(BitWidth, 0); 2406 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2407 Ops.data(), Ops.size(), 2408 APInt(BitWidth, 1), *this)) { 2409 struct APIntCompare { 2410 bool operator()(const APInt &LHS, const APInt &RHS) const { 2411 return LHS.ult(RHS); 2412 } 2413 }; 2414 2415 // Some interesting folding opportunity is present, so its worthwhile to 2416 // re-generate the operands list. Group the operands by constant scale, 2417 // to avoid multiplying by the same constant scale multiple times. 2418 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2419 for (const SCEV *NewOp : NewOps) 2420 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2421 // Re-generate the operands list. 2422 Ops.clear(); 2423 if (AccumulatedConstant != 0) 2424 Ops.push_back(getConstant(AccumulatedConstant)); 2425 for (auto &MulOp : MulOpLists) 2426 if (MulOp.first != 0) 2427 Ops.push_back(getMulExpr( 2428 getConstant(MulOp.first), 2429 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2430 SCEV::FlagAnyWrap, Depth + 1)); 2431 if (Ops.empty()) 2432 return getZero(Ty); 2433 if (Ops.size() == 1) 2434 return Ops[0]; 2435 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2436 } 2437 } 2438 2439 // If we are adding something to a multiply expression, make sure the 2440 // something is not already an operand of the multiply. If so, merge it into 2441 // the multiply. 2442 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2443 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2444 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2445 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2446 if (isa<SCEVConstant>(MulOpSCEV)) 2447 continue; 2448 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2449 if (MulOpSCEV == Ops[AddOp]) { 2450 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2451 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2452 if (Mul->getNumOperands() != 2) { 2453 // If the multiply has more than two operands, we must get the 2454 // Y*Z term. 2455 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2456 Mul->op_begin()+MulOp); 2457 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2458 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2459 } 2460 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2461 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2462 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2463 SCEV::FlagAnyWrap, Depth + 1); 2464 if (Ops.size() == 2) return OuterMul; 2465 if (AddOp < Idx) { 2466 Ops.erase(Ops.begin()+AddOp); 2467 Ops.erase(Ops.begin()+Idx-1); 2468 } else { 2469 Ops.erase(Ops.begin()+Idx); 2470 Ops.erase(Ops.begin()+AddOp-1); 2471 } 2472 Ops.push_back(OuterMul); 2473 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2474 } 2475 2476 // Check this multiply against other multiplies being added together. 2477 for (unsigned OtherMulIdx = Idx+1; 2478 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2479 ++OtherMulIdx) { 2480 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2481 // If MulOp occurs in OtherMul, we can fold the two multiplies 2482 // together. 2483 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2484 OMulOp != e; ++OMulOp) 2485 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2486 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2487 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2488 if (Mul->getNumOperands() != 2) { 2489 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2490 Mul->op_begin()+MulOp); 2491 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2492 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2493 } 2494 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2495 if (OtherMul->getNumOperands() != 2) { 2496 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2497 OtherMul->op_begin()+OMulOp); 2498 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2499 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2500 } 2501 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2502 const SCEV *InnerMulSum = 2503 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2504 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2505 SCEV::FlagAnyWrap, Depth + 1); 2506 if (Ops.size() == 2) return OuterMul; 2507 Ops.erase(Ops.begin()+Idx); 2508 Ops.erase(Ops.begin()+OtherMulIdx-1); 2509 Ops.push_back(OuterMul); 2510 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2511 } 2512 } 2513 } 2514 } 2515 2516 // If there are any add recurrences in the operands list, see if any other 2517 // added values are loop invariant. If so, we can fold them into the 2518 // recurrence. 2519 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2520 ++Idx; 2521 2522 // Scan over all recurrences, trying to fold loop invariants into them. 2523 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2524 // Scan all of the other operands to this add and add them to the vector if 2525 // they are loop invariant w.r.t. the recurrence. 2526 SmallVector<const SCEV *, 8> LIOps; 2527 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2528 const Loop *AddRecLoop = AddRec->getLoop(); 2529 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2530 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2531 LIOps.push_back(Ops[i]); 2532 Ops.erase(Ops.begin()+i); 2533 --i; --e; 2534 } 2535 2536 // If we found some loop invariants, fold them into the recurrence. 2537 if (!LIOps.empty()) { 2538 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2539 LIOps.push_back(AddRec->getStart()); 2540 2541 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2542 AddRec->op_end()); 2543 // This follows from the fact that the no-wrap flags on the outer add 2544 // expression are applicable on the 0th iteration, when the add recurrence 2545 // will be equal to its start value. 2546 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2547 2548 // Build the new addrec. Propagate the NUW and NSW flags if both the 2549 // outer add and the inner addrec are guaranteed to have no overflow. 2550 // Always propagate NW. 2551 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2552 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2553 2554 // If all of the other operands were loop invariant, we are done. 2555 if (Ops.size() == 1) return NewRec; 2556 2557 // Otherwise, add the folded AddRec by the non-invariant parts. 2558 for (unsigned i = 0;; ++i) 2559 if (Ops[i] == AddRec) { 2560 Ops[i] = NewRec; 2561 break; 2562 } 2563 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2564 } 2565 2566 // Okay, if there weren't any loop invariants to be folded, check to see if 2567 // there are multiple AddRec's with the same loop induction variable being 2568 // added together. If so, we can fold them. 2569 for (unsigned OtherIdx = Idx+1; 2570 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2571 ++OtherIdx) { 2572 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2573 // so that the 1st found AddRecExpr is dominated by all others. 2574 assert(DT.dominates( 2575 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2576 AddRec->getLoop()->getHeader()) && 2577 "AddRecExprs are not sorted in reverse dominance order?"); 2578 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2579 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2580 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2581 AddRec->op_end()); 2582 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2583 ++OtherIdx) { 2584 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2585 if (OtherAddRec->getLoop() == AddRecLoop) { 2586 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2587 i != e; ++i) { 2588 if (i >= AddRecOps.size()) { 2589 AddRecOps.append(OtherAddRec->op_begin()+i, 2590 OtherAddRec->op_end()); 2591 break; 2592 } 2593 SmallVector<const SCEV *, 2> TwoOps = { 2594 AddRecOps[i], OtherAddRec->getOperand(i)}; 2595 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2596 } 2597 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2598 } 2599 } 2600 // Step size has changed, so we cannot guarantee no self-wraparound. 2601 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2602 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2603 } 2604 } 2605 2606 // Otherwise couldn't fold anything into this recurrence. Move onto the 2607 // next one. 2608 } 2609 2610 // Okay, it looks like we really DO need an add expr. Check to see if we 2611 // already have one, otherwise create a new one. 2612 return getOrCreateAddExpr(Ops, Flags); 2613 } 2614 2615 const SCEV * 2616 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2617 SCEV::NoWrapFlags Flags) { 2618 FoldingSetNodeID ID; 2619 ID.AddInteger(scAddExpr); 2620 for (const SCEV *Op : Ops) 2621 ID.AddPointer(Op); 2622 void *IP = nullptr; 2623 SCEVAddExpr *S = 2624 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2625 if (!S) { 2626 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2627 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2628 S = new (SCEVAllocator) 2629 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2630 UniqueSCEVs.InsertNode(S, IP); 2631 addToLoopUseLists(S); 2632 } 2633 S->setNoWrapFlags(Flags); 2634 return S; 2635 } 2636 2637 const SCEV * 2638 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2639 SCEV::NoWrapFlags Flags) { 2640 FoldingSetNodeID ID; 2641 ID.AddInteger(scMulExpr); 2642 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2643 ID.AddPointer(Ops[i]); 2644 void *IP = nullptr; 2645 SCEVMulExpr *S = 2646 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2647 if (!S) { 2648 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2649 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2650 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2651 O, Ops.size()); 2652 UniqueSCEVs.InsertNode(S, IP); 2653 addToLoopUseLists(S); 2654 } 2655 S->setNoWrapFlags(Flags); 2656 return S; 2657 } 2658 2659 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2660 uint64_t k = i*j; 2661 if (j > 1 && k / j != i) Overflow = true; 2662 return k; 2663 } 2664 2665 /// Compute the result of "n choose k", the binomial coefficient. If an 2666 /// intermediate computation overflows, Overflow will be set and the return will 2667 /// be garbage. Overflow is not cleared on absence of overflow. 2668 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2669 // We use the multiplicative formula: 2670 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2671 // At each iteration, we take the n-th term of the numeral and divide by the 2672 // (k-n)th term of the denominator. This division will always produce an 2673 // integral result, and helps reduce the chance of overflow in the 2674 // intermediate computations. However, we can still overflow even when the 2675 // final result would fit. 2676 2677 if (n == 0 || n == k) return 1; 2678 if (k > n) return 0; 2679 2680 if (k > n/2) 2681 k = n-k; 2682 2683 uint64_t r = 1; 2684 for (uint64_t i = 1; i <= k; ++i) { 2685 r = umul_ov(r, n-(i-1), Overflow); 2686 r /= i; 2687 } 2688 return r; 2689 } 2690 2691 /// Determine if any of the operands in this SCEV are a constant or if 2692 /// any of the add or multiply expressions in this SCEV contain a constant. 2693 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2694 struct FindConstantInAddMulChain { 2695 bool FoundConstant = false; 2696 2697 bool follow(const SCEV *S) { 2698 FoundConstant |= isa<SCEVConstant>(S); 2699 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2700 } 2701 2702 bool isDone() const { 2703 return FoundConstant; 2704 } 2705 }; 2706 2707 FindConstantInAddMulChain F; 2708 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2709 ST.visitAll(StartExpr); 2710 return F.FoundConstant; 2711 } 2712 2713 /// Get a canonical multiply expression, or something simpler if possible. 2714 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2715 SCEV::NoWrapFlags Flags, 2716 unsigned Depth) { 2717 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2718 "only nuw or nsw allowed"); 2719 assert(!Ops.empty() && "Cannot get empty mul!"); 2720 if (Ops.size() == 1) return Ops[0]; 2721 #ifndef NDEBUG 2722 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2723 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2724 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2725 "SCEVMulExpr operand types don't match!"); 2726 #endif 2727 2728 // Sort by complexity, this groups all similar expression types together. 2729 GroupByComplexity(Ops, &LI, DT); 2730 2731 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2732 2733 // Limit recursion calls depth. 2734 if (Depth > MaxArithDepth) 2735 return getOrCreateMulExpr(Ops, Flags); 2736 2737 // If there are any constants, fold them together. 2738 unsigned Idx = 0; 2739 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2740 2741 // C1*(C2+V) -> C1*C2 + C1*V 2742 if (Ops.size() == 2) 2743 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2744 // If any of Add's ops are Adds or Muls with a constant, 2745 // apply this transformation as well. 2746 if (Add->getNumOperands() == 2) 2747 // TODO: There are some cases where this transformation is not 2748 // profitable, for example: 2749 // Add = (C0 + X) * Y + Z. 2750 // Maybe the scope of this transformation should be narrowed down. 2751 if (containsConstantInAddMulChain(Add)) 2752 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2753 SCEV::FlagAnyWrap, Depth + 1), 2754 getMulExpr(LHSC, Add->getOperand(1), 2755 SCEV::FlagAnyWrap, Depth + 1), 2756 SCEV::FlagAnyWrap, Depth + 1); 2757 2758 ++Idx; 2759 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2760 // We found two constants, fold them together! 2761 ConstantInt *Fold = 2762 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2763 Ops[0] = getConstant(Fold); 2764 Ops.erase(Ops.begin()+1); // Erase the folded element 2765 if (Ops.size() == 1) return Ops[0]; 2766 LHSC = cast<SCEVConstant>(Ops[0]); 2767 } 2768 2769 // If we are left with a constant one being multiplied, strip it off. 2770 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2771 Ops.erase(Ops.begin()); 2772 --Idx; 2773 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2774 // If we have a multiply of zero, it will always be zero. 2775 return Ops[0]; 2776 } else if (Ops[0]->isAllOnesValue()) { 2777 // If we have a mul by -1 of an add, try distributing the -1 among the 2778 // add operands. 2779 if (Ops.size() == 2) { 2780 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2781 SmallVector<const SCEV *, 4> NewOps; 2782 bool AnyFolded = false; 2783 for (const SCEV *AddOp : Add->operands()) { 2784 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2785 Depth + 1); 2786 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2787 NewOps.push_back(Mul); 2788 } 2789 if (AnyFolded) 2790 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2791 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2792 // Negation preserves a recurrence's no self-wrap property. 2793 SmallVector<const SCEV *, 4> Operands; 2794 for (const SCEV *AddRecOp : AddRec->operands()) 2795 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2796 Depth + 1)); 2797 2798 return getAddRecExpr(Operands, AddRec->getLoop(), 2799 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2800 } 2801 } 2802 } 2803 2804 if (Ops.size() == 1) 2805 return Ops[0]; 2806 } 2807 2808 // Skip over the add expression until we get to a multiply. 2809 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2810 ++Idx; 2811 2812 // If there are mul operands inline them all into this expression. 2813 if (Idx < Ops.size()) { 2814 bool DeletedMul = false; 2815 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2816 if (Ops.size() > MulOpsInlineThreshold) 2817 break; 2818 // If we have an mul, expand the mul operands onto the end of the 2819 // operands list. 2820 Ops.erase(Ops.begin()+Idx); 2821 Ops.append(Mul->op_begin(), Mul->op_end()); 2822 DeletedMul = true; 2823 } 2824 2825 // If we deleted at least one mul, we added operands to the end of the 2826 // list, and they are not necessarily sorted. Recurse to resort and 2827 // resimplify any operands we just acquired. 2828 if (DeletedMul) 2829 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2830 } 2831 2832 // If there are any add recurrences in the operands list, see if any other 2833 // added values are loop invariant. If so, we can fold them into the 2834 // recurrence. 2835 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2836 ++Idx; 2837 2838 // Scan over all recurrences, trying to fold loop invariants into them. 2839 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2840 // Scan all of the other operands to this mul and add them to the vector 2841 // if they are loop invariant w.r.t. the recurrence. 2842 SmallVector<const SCEV *, 8> LIOps; 2843 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2844 const Loop *AddRecLoop = AddRec->getLoop(); 2845 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2846 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2847 LIOps.push_back(Ops[i]); 2848 Ops.erase(Ops.begin()+i); 2849 --i; --e; 2850 } 2851 2852 // If we found some loop invariants, fold them into the recurrence. 2853 if (!LIOps.empty()) { 2854 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2855 SmallVector<const SCEV *, 4> NewOps; 2856 NewOps.reserve(AddRec->getNumOperands()); 2857 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2858 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2859 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2860 SCEV::FlagAnyWrap, Depth + 1)); 2861 2862 // Build the new addrec. Propagate the NUW and NSW flags if both the 2863 // outer mul and the inner addrec are guaranteed to have no overflow. 2864 // 2865 // No self-wrap cannot be guaranteed after changing the step size, but 2866 // will be inferred if either NUW or NSW is true. 2867 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2868 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2869 2870 // If all of the other operands were loop invariant, we are done. 2871 if (Ops.size() == 1) return NewRec; 2872 2873 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2874 for (unsigned i = 0;; ++i) 2875 if (Ops[i] == AddRec) { 2876 Ops[i] = NewRec; 2877 break; 2878 } 2879 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2880 } 2881 2882 // Okay, if there weren't any loop invariants to be folded, check to see 2883 // if there are multiple AddRec's with the same loop induction variable 2884 // being multiplied together. If so, we can fold them. 2885 2886 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2887 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2888 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2889 // ]]],+,...up to x=2n}. 2890 // Note that the arguments to choose() are always integers with values 2891 // known at compile time, never SCEV objects. 2892 // 2893 // The implementation avoids pointless extra computations when the two 2894 // addrec's are of different length (mathematically, it's equivalent to 2895 // an infinite stream of zeros on the right). 2896 bool OpsModified = false; 2897 for (unsigned OtherIdx = Idx+1; 2898 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2899 ++OtherIdx) { 2900 const SCEVAddRecExpr *OtherAddRec = 2901 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2902 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2903 continue; 2904 2905 // Limit max number of arguments to avoid creation of unreasonably big 2906 // SCEVAddRecs with very complex operands. 2907 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 2908 MaxAddRecSize) 2909 continue; 2910 2911 bool Overflow = false; 2912 Type *Ty = AddRec->getType(); 2913 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2914 SmallVector<const SCEV*, 7> AddRecOps; 2915 for (int x = 0, xe = AddRec->getNumOperands() + 2916 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2917 const SCEV *Term = getZero(Ty); 2918 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2919 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2920 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2921 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2922 z < ze && !Overflow; ++z) { 2923 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2924 uint64_t Coeff; 2925 if (LargerThan64Bits) 2926 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2927 else 2928 Coeff = Coeff1*Coeff2; 2929 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2930 const SCEV *Term1 = AddRec->getOperand(y-z); 2931 const SCEV *Term2 = OtherAddRec->getOperand(z); 2932 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2, 2933 SCEV::FlagAnyWrap, Depth + 1), 2934 SCEV::FlagAnyWrap, Depth + 1); 2935 } 2936 } 2937 AddRecOps.push_back(Term); 2938 } 2939 if (!Overflow) { 2940 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2941 SCEV::FlagAnyWrap); 2942 if (Ops.size() == 2) return NewAddRec; 2943 Ops[Idx] = NewAddRec; 2944 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2945 OpsModified = true; 2946 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2947 if (!AddRec) 2948 break; 2949 } 2950 } 2951 if (OpsModified) 2952 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2953 2954 // Otherwise couldn't fold anything into this recurrence. Move onto the 2955 // next one. 2956 } 2957 2958 // Okay, it looks like we really DO need an mul expr. Check to see if we 2959 // already have one, otherwise create a new one. 2960 return getOrCreateMulExpr(Ops, Flags); 2961 } 2962 2963 /// Represents an unsigned remainder expression based on unsigned division. 2964 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 2965 const SCEV *RHS) { 2966 assert(getEffectiveSCEVType(LHS->getType()) == 2967 getEffectiveSCEVType(RHS->getType()) && 2968 "SCEVURemExpr operand types don't match!"); 2969 2970 // Short-circuit easy cases 2971 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2972 // If constant is one, the result is trivial 2973 if (RHSC->getValue()->isOne()) 2974 return getZero(LHS->getType()); // X urem 1 --> 0 2975 2976 // If constant is a power of two, fold into a zext(trunc(LHS)). 2977 if (RHSC->getAPInt().isPowerOf2()) { 2978 Type *FullTy = LHS->getType(); 2979 Type *TruncTy = 2980 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 2981 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 2982 } 2983 } 2984 2985 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 2986 const SCEV *UDiv = getUDivExpr(LHS, RHS); 2987 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 2988 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 2989 } 2990 2991 /// Get a canonical unsigned division expression, or something simpler if 2992 /// possible. 2993 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2994 const SCEV *RHS) { 2995 assert(getEffectiveSCEVType(LHS->getType()) == 2996 getEffectiveSCEVType(RHS->getType()) && 2997 "SCEVUDivExpr operand types don't match!"); 2998 2999 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3000 if (RHSC->getValue()->isOne()) 3001 return LHS; // X udiv 1 --> x 3002 // If the denominator is zero, the result of the udiv is undefined. Don't 3003 // try to analyze it, because the resolution chosen here may differ from 3004 // the resolution chosen in other parts of the compiler. 3005 if (!RHSC->getValue()->isZero()) { 3006 // Determine if the division can be folded into the operands of 3007 // its operands. 3008 // TODO: Generalize this to non-constants by using known-bits information. 3009 Type *Ty = LHS->getType(); 3010 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3011 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3012 // For non-power-of-two values, effectively round the value up to the 3013 // nearest power of two. 3014 if (!RHSC->getAPInt().isPowerOf2()) 3015 ++MaxShiftAmt; 3016 IntegerType *ExtTy = 3017 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3018 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3019 if (const SCEVConstant *Step = 3020 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3021 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3022 const APInt &StepInt = Step->getAPInt(); 3023 const APInt &DivInt = RHSC->getAPInt(); 3024 if (!StepInt.urem(DivInt) && 3025 getZeroExtendExpr(AR, ExtTy) == 3026 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3027 getZeroExtendExpr(Step, ExtTy), 3028 AR->getLoop(), SCEV::FlagAnyWrap)) { 3029 SmallVector<const SCEV *, 4> Operands; 3030 for (const SCEV *Op : AR->operands()) 3031 Operands.push_back(getUDivExpr(Op, RHS)); 3032 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3033 } 3034 /// Get a canonical UDivExpr for a recurrence. 3035 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3036 // We can currently only fold X%N if X is constant. 3037 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3038 if (StartC && !DivInt.urem(StepInt) && 3039 getZeroExtendExpr(AR, ExtTy) == 3040 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3041 getZeroExtendExpr(Step, ExtTy), 3042 AR->getLoop(), SCEV::FlagAnyWrap)) { 3043 const APInt &StartInt = StartC->getAPInt(); 3044 const APInt &StartRem = StartInt.urem(StepInt); 3045 if (StartRem != 0) 3046 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3047 AR->getLoop(), SCEV::FlagNW); 3048 } 3049 } 3050 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3051 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3052 SmallVector<const SCEV *, 4> Operands; 3053 for (const SCEV *Op : M->operands()) 3054 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3055 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3056 // Find an operand that's safely divisible. 3057 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3058 const SCEV *Op = M->getOperand(i); 3059 const SCEV *Div = getUDivExpr(Op, RHSC); 3060 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3061 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3062 M->op_end()); 3063 Operands[i] = Div; 3064 return getMulExpr(Operands); 3065 } 3066 } 3067 } 3068 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3069 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3070 SmallVector<const SCEV *, 4> Operands; 3071 for (const SCEV *Op : A->operands()) 3072 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3073 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3074 Operands.clear(); 3075 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3076 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3077 if (isa<SCEVUDivExpr>(Op) || 3078 getMulExpr(Op, RHS) != A->getOperand(i)) 3079 break; 3080 Operands.push_back(Op); 3081 } 3082 if (Operands.size() == A->getNumOperands()) 3083 return getAddExpr(Operands); 3084 } 3085 } 3086 3087 // Fold if both operands are constant. 3088 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3089 Constant *LHSCV = LHSC->getValue(); 3090 Constant *RHSCV = RHSC->getValue(); 3091 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3092 RHSCV))); 3093 } 3094 } 3095 } 3096 3097 FoldingSetNodeID ID; 3098 ID.AddInteger(scUDivExpr); 3099 ID.AddPointer(LHS); 3100 ID.AddPointer(RHS); 3101 void *IP = nullptr; 3102 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3103 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3104 LHS, RHS); 3105 UniqueSCEVs.InsertNode(S, IP); 3106 addToLoopUseLists(S); 3107 return S; 3108 } 3109 3110 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3111 APInt A = C1->getAPInt().abs(); 3112 APInt B = C2->getAPInt().abs(); 3113 uint32_t ABW = A.getBitWidth(); 3114 uint32_t BBW = B.getBitWidth(); 3115 3116 if (ABW > BBW) 3117 B = B.zext(ABW); 3118 else if (ABW < BBW) 3119 A = A.zext(BBW); 3120 3121 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3122 } 3123 3124 /// Get a canonical unsigned division expression, or something simpler if 3125 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3126 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3127 /// it's not exact because the udiv may be clearing bits. 3128 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3129 const SCEV *RHS) { 3130 // TODO: we could try to find factors in all sorts of things, but for now we 3131 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3132 // end of this file for inspiration. 3133 3134 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3135 if (!Mul || !Mul->hasNoUnsignedWrap()) 3136 return getUDivExpr(LHS, RHS); 3137 3138 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3139 // If the mulexpr multiplies by a constant, then that constant must be the 3140 // first element of the mulexpr. 3141 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3142 if (LHSCst == RHSCst) { 3143 SmallVector<const SCEV *, 2> Operands; 3144 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3145 return getMulExpr(Operands); 3146 } 3147 3148 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3149 // that there's a factor provided by one of the other terms. We need to 3150 // check. 3151 APInt Factor = gcd(LHSCst, RHSCst); 3152 if (!Factor.isIntN(1)) { 3153 LHSCst = 3154 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3155 RHSCst = 3156 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3157 SmallVector<const SCEV *, 2> Operands; 3158 Operands.push_back(LHSCst); 3159 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3160 LHS = getMulExpr(Operands); 3161 RHS = RHSCst; 3162 Mul = dyn_cast<SCEVMulExpr>(LHS); 3163 if (!Mul) 3164 return getUDivExactExpr(LHS, RHS); 3165 } 3166 } 3167 } 3168 3169 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3170 if (Mul->getOperand(i) == RHS) { 3171 SmallVector<const SCEV *, 2> Operands; 3172 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3173 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3174 return getMulExpr(Operands); 3175 } 3176 } 3177 3178 return getUDivExpr(LHS, RHS); 3179 } 3180 3181 /// Get an add recurrence expression for the specified loop. Simplify the 3182 /// expression as much as possible. 3183 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3184 const Loop *L, 3185 SCEV::NoWrapFlags Flags) { 3186 SmallVector<const SCEV *, 4> Operands; 3187 Operands.push_back(Start); 3188 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3189 if (StepChrec->getLoop() == L) { 3190 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3191 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3192 } 3193 3194 Operands.push_back(Step); 3195 return getAddRecExpr(Operands, L, Flags); 3196 } 3197 3198 /// Get an add recurrence expression for the specified loop. Simplify the 3199 /// expression as much as possible. 3200 const SCEV * 3201 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3202 const Loop *L, SCEV::NoWrapFlags Flags) { 3203 if (Operands.size() == 1) return Operands[0]; 3204 #ifndef NDEBUG 3205 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3206 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3207 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3208 "SCEVAddRecExpr operand types don't match!"); 3209 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3210 assert(isLoopInvariant(Operands[i], L) && 3211 "SCEVAddRecExpr operand is not loop-invariant!"); 3212 #endif 3213 3214 if (Operands.back()->isZero()) { 3215 Operands.pop_back(); 3216 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3217 } 3218 3219 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3220 // use that information to infer NUW and NSW flags. However, computing a 3221 // BE count requires calling getAddRecExpr, so we may not yet have a 3222 // meaningful BE count at this point (and if we don't, we'd be stuck 3223 // with a SCEVCouldNotCompute as the cached BE count). 3224 3225 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3226 3227 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3228 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3229 const Loop *NestedLoop = NestedAR->getLoop(); 3230 if (L->contains(NestedLoop) 3231 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3232 : (!NestedLoop->contains(L) && 3233 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3234 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3235 NestedAR->op_end()); 3236 Operands[0] = NestedAR->getStart(); 3237 // AddRecs require their operands be loop-invariant with respect to their 3238 // loops. Don't perform this transformation if it would break this 3239 // requirement. 3240 bool AllInvariant = all_of( 3241 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3242 3243 if (AllInvariant) { 3244 // Create a recurrence for the outer loop with the same step size. 3245 // 3246 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3247 // inner recurrence has the same property. 3248 SCEV::NoWrapFlags OuterFlags = 3249 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3250 3251 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3252 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3253 return isLoopInvariant(Op, NestedLoop); 3254 }); 3255 3256 if (AllInvariant) { 3257 // Ok, both add recurrences are valid after the transformation. 3258 // 3259 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3260 // the outer recurrence has the same property. 3261 SCEV::NoWrapFlags InnerFlags = 3262 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3263 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3264 } 3265 } 3266 // Reset Operands to its original state. 3267 Operands[0] = NestedAR; 3268 } 3269 } 3270 3271 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3272 // already have one, otherwise create a new one. 3273 FoldingSetNodeID ID; 3274 ID.AddInteger(scAddRecExpr); 3275 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3276 ID.AddPointer(Operands[i]); 3277 ID.AddPointer(L); 3278 void *IP = nullptr; 3279 SCEVAddRecExpr *S = 3280 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 3281 if (!S) { 3282 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 3283 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 3284 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 3285 O, Operands.size(), L); 3286 UniqueSCEVs.InsertNode(S, IP); 3287 addToLoopUseLists(S); 3288 } 3289 S->setNoWrapFlags(Flags); 3290 return S; 3291 } 3292 3293 const SCEV * 3294 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3295 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3296 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3297 // getSCEV(Base)->getType() has the same address space as Base->getType() 3298 // because SCEV::getType() preserves the address space. 3299 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3300 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3301 // instruction to its SCEV, because the Instruction may be guarded by control 3302 // flow and the no-overflow bits may not be valid for the expression in any 3303 // context. This can be fixed similarly to how these flags are handled for 3304 // adds. 3305 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3306 : SCEV::FlagAnyWrap; 3307 3308 const SCEV *TotalOffset = getZero(IntPtrTy); 3309 // The array size is unimportant. The first thing we do on CurTy is getting 3310 // its element type. 3311 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3312 for (const SCEV *IndexExpr : IndexExprs) { 3313 // Compute the (potentially symbolic) offset in bytes for this index. 3314 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3315 // For a struct, add the member offset. 3316 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3317 unsigned FieldNo = Index->getZExtValue(); 3318 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3319 3320 // Add the field offset to the running total offset. 3321 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3322 3323 // Update CurTy to the type of the field at Index. 3324 CurTy = STy->getTypeAtIndex(Index); 3325 } else { 3326 // Update CurTy to its element type. 3327 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3328 // For an array, add the element offset, explicitly scaled. 3329 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3330 // Getelementptr indices are signed. 3331 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3332 3333 // Multiply the index by the element size to compute the element offset. 3334 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3335 3336 // Add the element offset to the running total offset. 3337 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3338 } 3339 } 3340 3341 // Add the total offset from all the GEP indices to the base. 3342 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3343 } 3344 3345 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3346 const SCEV *RHS) { 3347 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3348 return getSMaxExpr(Ops); 3349 } 3350 3351 const SCEV * 3352 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3353 assert(!Ops.empty() && "Cannot get empty smax!"); 3354 if (Ops.size() == 1) return Ops[0]; 3355 #ifndef NDEBUG 3356 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3357 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3358 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3359 "SCEVSMaxExpr operand types don't match!"); 3360 #endif 3361 3362 // Sort by complexity, this groups all similar expression types together. 3363 GroupByComplexity(Ops, &LI, DT); 3364 3365 // If there are any constants, fold them together. 3366 unsigned Idx = 0; 3367 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3368 ++Idx; 3369 assert(Idx < Ops.size()); 3370 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3371 // We found two constants, fold them together! 3372 ConstantInt *Fold = ConstantInt::get( 3373 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3374 Ops[0] = getConstant(Fold); 3375 Ops.erase(Ops.begin()+1); // Erase the folded element 3376 if (Ops.size() == 1) return Ops[0]; 3377 LHSC = cast<SCEVConstant>(Ops[0]); 3378 } 3379 3380 // If we are left with a constant minimum-int, strip it off. 3381 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3382 Ops.erase(Ops.begin()); 3383 --Idx; 3384 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3385 // If we have an smax with a constant maximum-int, it will always be 3386 // maximum-int. 3387 return Ops[0]; 3388 } 3389 3390 if (Ops.size() == 1) return Ops[0]; 3391 } 3392 3393 // Find the first SMax 3394 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3395 ++Idx; 3396 3397 // Check to see if one of the operands is an SMax. If so, expand its operands 3398 // onto our operand list, and recurse to simplify. 3399 if (Idx < Ops.size()) { 3400 bool DeletedSMax = false; 3401 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3402 Ops.erase(Ops.begin()+Idx); 3403 Ops.append(SMax->op_begin(), SMax->op_end()); 3404 DeletedSMax = true; 3405 } 3406 3407 if (DeletedSMax) 3408 return getSMaxExpr(Ops); 3409 } 3410 3411 // Okay, check to see if the same value occurs in the operand list twice. If 3412 // so, delete one. Since we sorted the list, these values are required to 3413 // be adjacent. 3414 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3415 // X smax Y smax Y --> X smax Y 3416 // X smax Y --> X, if X is always greater than Y 3417 if (Ops[i] == Ops[i+1] || 3418 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3419 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3420 --i; --e; 3421 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3422 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3423 --i; --e; 3424 } 3425 3426 if (Ops.size() == 1) return Ops[0]; 3427 3428 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3429 3430 // Okay, it looks like we really DO need an smax expr. Check to see if we 3431 // already have one, otherwise create a new one. 3432 FoldingSetNodeID ID; 3433 ID.AddInteger(scSMaxExpr); 3434 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3435 ID.AddPointer(Ops[i]); 3436 void *IP = nullptr; 3437 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3438 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3439 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3440 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3441 O, Ops.size()); 3442 UniqueSCEVs.InsertNode(S, IP); 3443 addToLoopUseLists(S); 3444 return S; 3445 } 3446 3447 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3448 const SCEV *RHS) { 3449 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3450 return getUMaxExpr(Ops); 3451 } 3452 3453 const SCEV * 3454 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3455 assert(!Ops.empty() && "Cannot get empty umax!"); 3456 if (Ops.size() == 1) return Ops[0]; 3457 #ifndef NDEBUG 3458 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3459 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3460 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3461 "SCEVUMaxExpr operand types don't match!"); 3462 #endif 3463 3464 // Sort by complexity, this groups all similar expression types together. 3465 GroupByComplexity(Ops, &LI, DT); 3466 3467 // If there are any constants, fold them together. 3468 unsigned Idx = 0; 3469 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3470 ++Idx; 3471 assert(Idx < Ops.size()); 3472 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3473 // We found two constants, fold them together! 3474 ConstantInt *Fold = ConstantInt::get( 3475 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3476 Ops[0] = getConstant(Fold); 3477 Ops.erase(Ops.begin()+1); // Erase the folded element 3478 if (Ops.size() == 1) return Ops[0]; 3479 LHSC = cast<SCEVConstant>(Ops[0]); 3480 } 3481 3482 // If we are left with a constant minimum-int, strip it off. 3483 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3484 Ops.erase(Ops.begin()); 3485 --Idx; 3486 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3487 // If we have an umax with a constant maximum-int, it will always be 3488 // maximum-int. 3489 return Ops[0]; 3490 } 3491 3492 if (Ops.size() == 1) return Ops[0]; 3493 } 3494 3495 // Find the first UMax 3496 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3497 ++Idx; 3498 3499 // Check to see if one of the operands is a UMax. If so, expand its operands 3500 // onto our operand list, and recurse to simplify. 3501 if (Idx < Ops.size()) { 3502 bool DeletedUMax = false; 3503 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3504 Ops.erase(Ops.begin()+Idx); 3505 Ops.append(UMax->op_begin(), UMax->op_end()); 3506 DeletedUMax = true; 3507 } 3508 3509 if (DeletedUMax) 3510 return getUMaxExpr(Ops); 3511 } 3512 3513 // Okay, check to see if the same value occurs in the operand list twice. If 3514 // so, delete one. Since we sorted the list, these values are required to 3515 // be adjacent. 3516 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3517 // X umax Y umax Y --> X umax Y 3518 // X umax Y --> X, if X is always greater than Y 3519 if (Ops[i] == Ops[i+1] || 3520 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3521 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3522 --i; --e; 3523 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3524 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3525 --i; --e; 3526 } 3527 3528 if (Ops.size() == 1) return Ops[0]; 3529 3530 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3531 3532 // Okay, it looks like we really DO need a umax expr. Check to see if we 3533 // already have one, otherwise create a new one. 3534 FoldingSetNodeID ID; 3535 ID.AddInteger(scUMaxExpr); 3536 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3537 ID.AddPointer(Ops[i]); 3538 void *IP = nullptr; 3539 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3540 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3541 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3542 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3543 O, Ops.size()); 3544 UniqueSCEVs.InsertNode(S, IP); 3545 addToLoopUseLists(S); 3546 return S; 3547 } 3548 3549 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3550 const SCEV *RHS) { 3551 // ~smax(~x, ~y) == smin(x, y). 3552 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3553 } 3554 3555 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3556 const SCEV *RHS) { 3557 // ~umax(~x, ~y) == umin(x, y) 3558 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3559 } 3560 3561 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3562 // We can bypass creating a target-independent 3563 // constant expression and then folding it back into a ConstantInt. 3564 // This is just a compile-time optimization. 3565 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3566 } 3567 3568 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3569 StructType *STy, 3570 unsigned FieldNo) { 3571 // We can bypass creating a target-independent 3572 // constant expression and then folding it back into a ConstantInt. 3573 // This is just a compile-time optimization. 3574 return getConstant( 3575 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3576 } 3577 3578 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3579 // Don't attempt to do anything other than create a SCEVUnknown object 3580 // here. createSCEV only calls getUnknown after checking for all other 3581 // interesting possibilities, and any other code that calls getUnknown 3582 // is doing so in order to hide a value from SCEV canonicalization. 3583 3584 FoldingSetNodeID ID; 3585 ID.AddInteger(scUnknown); 3586 ID.AddPointer(V); 3587 void *IP = nullptr; 3588 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3589 assert(cast<SCEVUnknown>(S)->getValue() == V && 3590 "Stale SCEVUnknown in uniquing map!"); 3591 return S; 3592 } 3593 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3594 FirstUnknown); 3595 FirstUnknown = cast<SCEVUnknown>(S); 3596 UniqueSCEVs.InsertNode(S, IP); 3597 return S; 3598 } 3599 3600 //===----------------------------------------------------------------------===// 3601 // Basic SCEV Analysis and PHI Idiom Recognition Code 3602 // 3603 3604 /// Test if values of the given type are analyzable within the SCEV 3605 /// framework. This primarily includes integer types, and it can optionally 3606 /// include pointer types if the ScalarEvolution class has access to 3607 /// target-specific information. 3608 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3609 // Integers and pointers are always SCEVable. 3610 return Ty->isIntegerTy() || Ty->isPointerTy(); 3611 } 3612 3613 /// Return the size in bits of the specified type, for which isSCEVable must 3614 /// return true. 3615 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3616 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3617 if (Ty->isPointerTy()) 3618 return getDataLayout().getIndexTypeSizeInBits(Ty); 3619 return getDataLayout().getTypeSizeInBits(Ty); 3620 } 3621 3622 /// Return a type with the same bitwidth as the given type and which represents 3623 /// how SCEV will treat the given type, for which isSCEVable must return 3624 /// true. For pointer types, this is the pointer-sized integer type. 3625 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3626 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3627 3628 if (Ty->isIntegerTy()) 3629 return Ty; 3630 3631 // The only other support type is pointer. 3632 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3633 return getDataLayout().getIntPtrType(Ty); 3634 } 3635 3636 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3637 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3638 } 3639 3640 const SCEV *ScalarEvolution::getCouldNotCompute() { 3641 return CouldNotCompute.get(); 3642 } 3643 3644 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3645 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3646 auto *SU = dyn_cast<SCEVUnknown>(S); 3647 return SU && SU->getValue() == nullptr; 3648 }); 3649 3650 return !ContainsNulls; 3651 } 3652 3653 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3654 HasRecMapType::iterator I = HasRecMap.find(S); 3655 if (I != HasRecMap.end()) 3656 return I->second; 3657 3658 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3659 HasRecMap.insert({S, FoundAddRec}); 3660 return FoundAddRec; 3661 } 3662 3663 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3664 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3665 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3666 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3667 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3668 if (!Add) 3669 return {S, nullptr}; 3670 3671 if (Add->getNumOperands() != 2) 3672 return {S, nullptr}; 3673 3674 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3675 if (!ConstOp) 3676 return {S, nullptr}; 3677 3678 return {Add->getOperand(1), ConstOp->getValue()}; 3679 } 3680 3681 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3682 /// by the value and offset from any ValueOffsetPair in the set. 3683 SetVector<ScalarEvolution::ValueOffsetPair> * 3684 ScalarEvolution::getSCEVValues(const SCEV *S) { 3685 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3686 if (SI == ExprValueMap.end()) 3687 return nullptr; 3688 #ifndef NDEBUG 3689 if (VerifySCEVMap) { 3690 // Check there is no dangling Value in the set returned. 3691 for (const auto &VE : SI->second) 3692 assert(ValueExprMap.count(VE.first)); 3693 } 3694 #endif 3695 return &SI->second; 3696 } 3697 3698 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3699 /// cannot be used separately. eraseValueFromMap should be used to remove 3700 /// V from ValueExprMap and ExprValueMap at the same time. 3701 void ScalarEvolution::eraseValueFromMap(Value *V) { 3702 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3703 if (I != ValueExprMap.end()) { 3704 const SCEV *S = I->second; 3705 // Remove {V, 0} from the set of ExprValueMap[S] 3706 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3707 SV->remove({V, nullptr}); 3708 3709 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3710 const SCEV *Stripped; 3711 ConstantInt *Offset; 3712 std::tie(Stripped, Offset) = splitAddExpr(S); 3713 if (Offset != nullptr) { 3714 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3715 SV->remove({V, Offset}); 3716 } 3717 ValueExprMap.erase(V); 3718 } 3719 } 3720 3721 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3722 /// TODO: In reality it is better to check the poison recursevely 3723 /// but this is better than nothing. 3724 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3725 if (auto *I = dyn_cast<Instruction>(V)) { 3726 if (isa<OverflowingBinaryOperator>(I)) { 3727 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3728 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3729 return true; 3730 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3731 return true; 3732 } 3733 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3734 return true; 3735 } 3736 return false; 3737 } 3738 3739 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3740 /// create a new one. 3741 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3742 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3743 3744 const SCEV *S = getExistingSCEV(V); 3745 if (S == nullptr) { 3746 S = createSCEV(V); 3747 // During PHI resolution, it is possible to create two SCEVs for the same 3748 // V, so it is needed to double check whether V->S is inserted into 3749 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3750 std::pair<ValueExprMapType::iterator, bool> Pair = 3751 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3752 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3753 ExprValueMap[S].insert({V, nullptr}); 3754 3755 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3756 // ExprValueMap. 3757 const SCEV *Stripped = S; 3758 ConstantInt *Offset = nullptr; 3759 std::tie(Stripped, Offset) = splitAddExpr(S); 3760 // If stripped is SCEVUnknown, don't bother to save 3761 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3762 // increase the complexity of the expansion code. 3763 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3764 // because it may generate add/sub instead of GEP in SCEV expansion. 3765 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3766 !isa<GetElementPtrInst>(V)) 3767 ExprValueMap[Stripped].insert({V, Offset}); 3768 } 3769 } 3770 return S; 3771 } 3772 3773 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3774 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3775 3776 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3777 if (I != ValueExprMap.end()) { 3778 const SCEV *S = I->second; 3779 if (checkValidity(S)) 3780 return S; 3781 eraseValueFromMap(V); 3782 forgetMemoizedResults(S); 3783 } 3784 return nullptr; 3785 } 3786 3787 /// Return a SCEV corresponding to -V = -1*V 3788 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3789 SCEV::NoWrapFlags Flags) { 3790 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3791 return getConstant( 3792 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3793 3794 Type *Ty = V->getType(); 3795 Ty = getEffectiveSCEVType(Ty); 3796 return getMulExpr( 3797 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3798 } 3799 3800 /// Return a SCEV corresponding to ~V = -1-V 3801 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3802 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3803 return getConstant( 3804 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3805 3806 Type *Ty = V->getType(); 3807 Ty = getEffectiveSCEVType(Ty); 3808 const SCEV *AllOnes = 3809 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3810 return getMinusSCEV(AllOnes, V); 3811 } 3812 3813 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3814 SCEV::NoWrapFlags Flags, 3815 unsigned Depth) { 3816 // Fast path: X - X --> 0. 3817 if (LHS == RHS) 3818 return getZero(LHS->getType()); 3819 3820 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3821 // makes it so that we cannot make much use of NUW. 3822 auto AddFlags = SCEV::FlagAnyWrap; 3823 const bool RHSIsNotMinSigned = 3824 !getSignedRangeMin(RHS).isMinSignedValue(); 3825 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3826 // Let M be the minimum representable signed value. Then (-1)*RHS 3827 // signed-wraps if and only if RHS is M. That can happen even for 3828 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3829 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3830 // (-1)*RHS, we need to prove that RHS != M. 3831 // 3832 // If LHS is non-negative and we know that LHS - RHS does not 3833 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3834 // either by proving that RHS > M or that LHS >= 0. 3835 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3836 AddFlags = SCEV::FlagNSW; 3837 } 3838 } 3839 3840 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3841 // RHS is NSW and LHS >= 0. 3842 // 3843 // The difficulty here is that the NSW flag may have been proven 3844 // relative to a loop that is to be found in a recurrence in LHS and 3845 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3846 // larger scope than intended. 3847 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3848 3849 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 3850 } 3851 3852 const SCEV * 3853 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3854 Type *SrcTy = V->getType(); 3855 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3856 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3857 "Cannot truncate or zero extend with non-integer arguments!"); 3858 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3859 return V; // No conversion 3860 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3861 return getTruncateExpr(V, Ty); 3862 return getZeroExtendExpr(V, Ty); 3863 } 3864 3865 const SCEV * 3866 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3867 Type *Ty) { 3868 Type *SrcTy = V->getType(); 3869 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3870 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3871 "Cannot truncate or zero extend with non-integer arguments!"); 3872 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3873 return V; // No conversion 3874 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3875 return getTruncateExpr(V, Ty); 3876 return getSignExtendExpr(V, Ty); 3877 } 3878 3879 const SCEV * 3880 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3881 Type *SrcTy = V->getType(); 3882 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3883 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3884 "Cannot noop or zero extend with non-integer arguments!"); 3885 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3886 "getNoopOrZeroExtend cannot truncate!"); 3887 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3888 return V; // No conversion 3889 return getZeroExtendExpr(V, Ty); 3890 } 3891 3892 const SCEV * 3893 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3894 Type *SrcTy = V->getType(); 3895 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3896 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3897 "Cannot noop or sign extend with non-integer arguments!"); 3898 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3899 "getNoopOrSignExtend cannot truncate!"); 3900 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3901 return V; // No conversion 3902 return getSignExtendExpr(V, Ty); 3903 } 3904 3905 const SCEV * 3906 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3907 Type *SrcTy = V->getType(); 3908 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3909 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3910 "Cannot noop or any extend with non-integer arguments!"); 3911 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3912 "getNoopOrAnyExtend cannot truncate!"); 3913 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3914 return V; // No conversion 3915 return getAnyExtendExpr(V, Ty); 3916 } 3917 3918 const SCEV * 3919 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3920 Type *SrcTy = V->getType(); 3921 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3922 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3923 "Cannot truncate or noop with non-integer arguments!"); 3924 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3925 "getTruncateOrNoop cannot extend!"); 3926 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3927 return V; // No conversion 3928 return getTruncateExpr(V, Ty); 3929 } 3930 3931 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3932 const SCEV *RHS) { 3933 const SCEV *PromotedLHS = LHS; 3934 const SCEV *PromotedRHS = RHS; 3935 3936 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3937 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3938 else 3939 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3940 3941 return getUMaxExpr(PromotedLHS, PromotedRHS); 3942 } 3943 3944 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3945 const SCEV *RHS) { 3946 const SCEV *PromotedLHS = LHS; 3947 const SCEV *PromotedRHS = RHS; 3948 3949 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3950 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3951 else 3952 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3953 3954 return getUMinExpr(PromotedLHS, PromotedRHS); 3955 } 3956 3957 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3958 // A pointer operand may evaluate to a nonpointer expression, such as null. 3959 if (!V->getType()->isPointerTy()) 3960 return V; 3961 3962 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3963 return getPointerBase(Cast->getOperand()); 3964 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3965 const SCEV *PtrOp = nullptr; 3966 for (const SCEV *NAryOp : NAry->operands()) { 3967 if (NAryOp->getType()->isPointerTy()) { 3968 // Cannot find the base of an expression with multiple pointer operands. 3969 if (PtrOp) 3970 return V; 3971 PtrOp = NAryOp; 3972 } 3973 } 3974 if (!PtrOp) 3975 return V; 3976 return getPointerBase(PtrOp); 3977 } 3978 return V; 3979 } 3980 3981 /// Push users of the given Instruction onto the given Worklist. 3982 static void 3983 PushDefUseChildren(Instruction *I, 3984 SmallVectorImpl<Instruction *> &Worklist) { 3985 // Push the def-use children onto the Worklist stack. 3986 for (User *U : I->users()) 3987 Worklist.push_back(cast<Instruction>(U)); 3988 } 3989 3990 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3991 SmallVector<Instruction *, 16> Worklist; 3992 PushDefUseChildren(PN, Worklist); 3993 3994 SmallPtrSet<Instruction *, 8> Visited; 3995 Visited.insert(PN); 3996 while (!Worklist.empty()) { 3997 Instruction *I = Worklist.pop_back_val(); 3998 if (!Visited.insert(I).second) 3999 continue; 4000 4001 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4002 if (It != ValueExprMap.end()) { 4003 const SCEV *Old = It->second; 4004 4005 // Short-circuit the def-use traversal if the symbolic name 4006 // ceases to appear in expressions. 4007 if (Old != SymName && !hasOperand(Old, SymName)) 4008 continue; 4009 4010 // SCEVUnknown for a PHI either means that it has an unrecognized 4011 // structure, it's a PHI that's in the progress of being computed 4012 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4013 // additional loop trip count information isn't going to change anything. 4014 // In the second case, createNodeForPHI will perform the necessary 4015 // updates on its own when it gets to that point. In the third, we do 4016 // want to forget the SCEVUnknown. 4017 if (!isa<PHINode>(I) || 4018 !isa<SCEVUnknown>(Old) || 4019 (I != PN && Old == SymName)) { 4020 eraseValueFromMap(It->first); 4021 forgetMemoizedResults(Old); 4022 } 4023 } 4024 4025 PushDefUseChildren(I, Worklist); 4026 } 4027 } 4028 4029 namespace { 4030 4031 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4032 /// expression in case its Loop is L. If it is not L then 4033 /// if IgnoreOtherLoops is true then use AddRec itself 4034 /// otherwise rewrite cannot be done. 4035 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4036 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4037 public: 4038 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4039 bool IgnoreOtherLoops = true) { 4040 SCEVInitRewriter Rewriter(L, SE); 4041 const SCEV *Result = Rewriter.visit(S); 4042 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4043 return SE.getCouldNotCompute(); 4044 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4045 ? SE.getCouldNotCompute() 4046 : Result; 4047 } 4048 4049 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4050 if (!SE.isLoopInvariant(Expr, L)) 4051 SeenLoopVariantSCEVUnknown = true; 4052 return Expr; 4053 } 4054 4055 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4056 // Only re-write AddRecExprs for this loop. 4057 if (Expr->getLoop() == L) 4058 return Expr->getStart(); 4059 SeenOtherLoops = true; 4060 return Expr; 4061 } 4062 4063 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4064 4065 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4066 4067 private: 4068 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4069 : SCEVRewriteVisitor(SE), L(L) {} 4070 4071 const Loop *L; 4072 bool SeenLoopVariantSCEVUnknown = false; 4073 bool SeenOtherLoops = false; 4074 }; 4075 4076 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4077 /// increment expression in case its Loop is L. If it is not L then 4078 /// use AddRec itself. 4079 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4080 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4081 public: 4082 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4083 SCEVPostIncRewriter Rewriter(L, SE); 4084 const SCEV *Result = Rewriter.visit(S); 4085 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4086 ? SE.getCouldNotCompute() 4087 : Result; 4088 } 4089 4090 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4091 if (!SE.isLoopInvariant(Expr, L)) 4092 SeenLoopVariantSCEVUnknown = true; 4093 return Expr; 4094 } 4095 4096 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4097 // Only re-write AddRecExprs for this loop. 4098 if (Expr->getLoop() == L) 4099 return Expr->getPostIncExpr(SE); 4100 SeenOtherLoops = true; 4101 return Expr; 4102 } 4103 4104 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4105 4106 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4107 4108 private: 4109 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4110 : SCEVRewriteVisitor(SE), L(L) {} 4111 4112 const Loop *L; 4113 bool SeenLoopVariantSCEVUnknown = false; 4114 bool SeenOtherLoops = false; 4115 }; 4116 4117 /// This class evaluates the compare condition by matching it against the 4118 /// condition of loop latch. If there is a match we assume a true value 4119 /// for the condition while building SCEV nodes. 4120 class SCEVBackedgeConditionFolder 4121 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4122 public: 4123 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4124 ScalarEvolution &SE) { 4125 bool IsPosBECond = false; 4126 Value *BECond = nullptr; 4127 if (BasicBlock *Latch = L->getLoopLatch()) { 4128 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4129 if (BI && BI->isConditional()) { 4130 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4131 "Both outgoing branches should not target same header!"); 4132 BECond = BI->getCondition(); 4133 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4134 } else { 4135 return S; 4136 } 4137 } 4138 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4139 return Rewriter.visit(S); 4140 } 4141 4142 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4143 const SCEV *Result = Expr; 4144 bool InvariantF = SE.isLoopInvariant(Expr, L); 4145 4146 if (!InvariantF) { 4147 Instruction *I = cast<Instruction>(Expr->getValue()); 4148 switch (I->getOpcode()) { 4149 case Instruction::Select: { 4150 SelectInst *SI = cast<SelectInst>(I); 4151 Optional<const SCEV *> Res = 4152 compareWithBackedgeCondition(SI->getCondition()); 4153 if (Res.hasValue()) { 4154 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4155 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4156 } 4157 break; 4158 } 4159 default: { 4160 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4161 if (Res.hasValue()) 4162 Result = Res.getValue(); 4163 break; 4164 } 4165 } 4166 } 4167 return Result; 4168 } 4169 4170 private: 4171 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4172 bool IsPosBECond, ScalarEvolution &SE) 4173 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4174 IsPositiveBECond(IsPosBECond) {} 4175 4176 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4177 4178 const Loop *L; 4179 /// Loop back condition. 4180 Value *BackedgeCond = nullptr; 4181 /// Set to true if loop back is on positive branch condition. 4182 bool IsPositiveBECond; 4183 }; 4184 4185 Optional<const SCEV *> 4186 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4187 4188 // If value matches the backedge condition for loop latch, 4189 // then return a constant evolution node based on loopback 4190 // branch taken. 4191 if (BackedgeCond == IC) 4192 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4193 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4194 return None; 4195 } 4196 4197 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4198 public: 4199 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4200 ScalarEvolution &SE) { 4201 SCEVShiftRewriter Rewriter(L, SE); 4202 const SCEV *Result = Rewriter.visit(S); 4203 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4204 } 4205 4206 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4207 // Only allow AddRecExprs for this loop. 4208 if (!SE.isLoopInvariant(Expr, L)) 4209 Valid = false; 4210 return Expr; 4211 } 4212 4213 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4214 if (Expr->getLoop() == L && Expr->isAffine()) 4215 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4216 Valid = false; 4217 return Expr; 4218 } 4219 4220 bool isValid() { return Valid; } 4221 4222 private: 4223 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4224 : SCEVRewriteVisitor(SE), L(L) {} 4225 4226 const Loop *L; 4227 bool Valid = true; 4228 }; 4229 4230 } // end anonymous namespace 4231 4232 SCEV::NoWrapFlags 4233 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4234 if (!AR->isAffine()) 4235 return SCEV::FlagAnyWrap; 4236 4237 using OBO = OverflowingBinaryOperator; 4238 4239 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4240 4241 if (!AR->hasNoSignedWrap()) { 4242 ConstantRange AddRecRange = getSignedRange(AR); 4243 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4244 4245 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4246 Instruction::Add, IncRange, OBO::NoSignedWrap); 4247 if (NSWRegion.contains(AddRecRange)) 4248 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4249 } 4250 4251 if (!AR->hasNoUnsignedWrap()) { 4252 ConstantRange AddRecRange = getUnsignedRange(AR); 4253 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4254 4255 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4256 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4257 if (NUWRegion.contains(AddRecRange)) 4258 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4259 } 4260 4261 return Result; 4262 } 4263 4264 namespace { 4265 4266 /// Represents an abstract binary operation. This may exist as a 4267 /// normal instruction or constant expression, or may have been 4268 /// derived from an expression tree. 4269 struct BinaryOp { 4270 unsigned Opcode; 4271 Value *LHS; 4272 Value *RHS; 4273 bool IsNSW = false; 4274 bool IsNUW = false; 4275 4276 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4277 /// constant expression. 4278 Operator *Op = nullptr; 4279 4280 explicit BinaryOp(Operator *Op) 4281 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4282 Op(Op) { 4283 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4284 IsNSW = OBO->hasNoSignedWrap(); 4285 IsNUW = OBO->hasNoUnsignedWrap(); 4286 } 4287 } 4288 4289 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4290 bool IsNUW = false) 4291 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4292 }; 4293 4294 } // end anonymous namespace 4295 4296 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4297 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4298 auto *Op = dyn_cast<Operator>(V); 4299 if (!Op) 4300 return None; 4301 4302 // Implementation detail: all the cleverness here should happen without 4303 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4304 // SCEV expressions when possible, and we should not break that. 4305 4306 switch (Op->getOpcode()) { 4307 case Instruction::Add: 4308 case Instruction::Sub: 4309 case Instruction::Mul: 4310 case Instruction::UDiv: 4311 case Instruction::URem: 4312 case Instruction::And: 4313 case Instruction::Or: 4314 case Instruction::AShr: 4315 case Instruction::Shl: 4316 return BinaryOp(Op); 4317 4318 case Instruction::Xor: 4319 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4320 // If the RHS of the xor is a signmask, then this is just an add. 4321 // Instcombine turns add of signmask into xor as a strength reduction step. 4322 if (RHSC->getValue().isSignMask()) 4323 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4324 return BinaryOp(Op); 4325 4326 case Instruction::LShr: 4327 // Turn logical shift right of a constant into a unsigned divide. 4328 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4329 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4330 4331 // If the shift count is not less than the bitwidth, the result of 4332 // the shift is undefined. Don't try to analyze it, because the 4333 // resolution chosen here may differ from the resolution chosen in 4334 // other parts of the compiler. 4335 if (SA->getValue().ult(BitWidth)) { 4336 Constant *X = 4337 ConstantInt::get(SA->getContext(), 4338 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4339 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4340 } 4341 } 4342 return BinaryOp(Op); 4343 4344 case Instruction::ExtractValue: { 4345 auto *EVI = cast<ExtractValueInst>(Op); 4346 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4347 break; 4348 4349 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 4350 if (!CI) 4351 break; 4352 4353 if (auto *F = CI->getCalledFunction()) 4354 switch (F->getIntrinsicID()) { 4355 case Intrinsic::sadd_with_overflow: 4356 case Intrinsic::uadd_with_overflow: 4357 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4358 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4359 CI->getArgOperand(1)); 4360 4361 // Now that we know that all uses of the arithmetic-result component of 4362 // CI are guarded by the overflow check, we can go ahead and pretend 4363 // that the arithmetic is non-overflowing. 4364 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 4365 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4366 CI->getArgOperand(1), /* IsNSW = */ true, 4367 /* IsNUW = */ false); 4368 else 4369 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4370 CI->getArgOperand(1), /* IsNSW = */ false, 4371 /* IsNUW*/ true); 4372 case Intrinsic::ssub_with_overflow: 4373 case Intrinsic::usub_with_overflow: 4374 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4375 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4376 CI->getArgOperand(1)); 4377 4378 // The same reasoning as sadd/uadd above. 4379 if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow) 4380 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4381 CI->getArgOperand(1), /* IsNSW = */ true, 4382 /* IsNUW = */ false); 4383 else 4384 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4385 CI->getArgOperand(1), /* IsNSW = */ false, 4386 /* IsNUW = */ true); 4387 case Intrinsic::smul_with_overflow: 4388 case Intrinsic::umul_with_overflow: 4389 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4390 CI->getArgOperand(1)); 4391 default: 4392 break; 4393 } 4394 break; 4395 } 4396 4397 default: 4398 break; 4399 } 4400 4401 return None; 4402 } 4403 4404 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4405 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4406 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4407 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4408 /// follows one of the following patterns: 4409 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4410 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4411 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4412 /// we return the type of the truncation operation, and indicate whether the 4413 /// truncated type should be treated as signed/unsigned by setting 4414 /// \p Signed to true/false, respectively. 4415 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4416 bool &Signed, ScalarEvolution &SE) { 4417 // The case where Op == SymbolicPHI (that is, with no type conversions on 4418 // the way) is handled by the regular add recurrence creating logic and 4419 // would have already been triggered in createAddRecForPHI. Reaching it here 4420 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4421 // because one of the other operands of the SCEVAddExpr updating this PHI is 4422 // not invariant). 4423 // 4424 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4425 // this case predicates that allow us to prove that Op == SymbolicPHI will 4426 // be added. 4427 if (Op == SymbolicPHI) 4428 return nullptr; 4429 4430 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4431 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4432 if (SourceBits != NewBits) 4433 return nullptr; 4434 4435 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4436 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4437 if (!SExt && !ZExt) 4438 return nullptr; 4439 const SCEVTruncateExpr *Trunc = 4440 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4441 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4442 if (!Trunc) 4443 return nullptr; 4444 const SCEV *X = Trunc->getOperand(); 4445 if (X != SymbolicPHI) 4446 return nullptr; 4447 Signed = SExt != nullptr; 4448 return Trunc->getType(); 4449 } 4450 4451 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4452 if (!PN->getType()->isIntegerTy()) 4453 return nullptr; 4454 const Loop *L = LI.getLoopFor(PN->getParent()); 4455 if (!L || L->getHeader() != PN->getParent()) 4456 return nullptr; 4457 return L; 4458 } 4459 4460 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4461 // computation that updates the phi follows the following pattern: 4462 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4463 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4464 // If so, try to see if it can be rewritten as an AddRecExpr under some 4465 // Predicates. If successful, return them as a pair. Also cache the results 4466 // of the analysis. 4467 // 4468 // Example usage scenario: 4469 // Say the Rewriter is called for the following SCEV: 4470 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4471 // where: 4472 // %X = phi i64 (%Start, %BEValue) 4473 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4474 // and call this function with %SymbolicPHI = %X. 4475 // 4476 // The analysis will find that the value coming around the backedge has 4477 // the following SCEV: 4478 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4479 // Upon concluding that this matches the desired pattern, the function 4480 // will return the pair {NewAddRec, SmallPredsVec} where: 4481 // NewAddRec = {%Start,+,%Step} 4482 // SmallPredsVec = {P1, P2, P3} as follows: 4483 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4484 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4485 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4486 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4487 // under the predicates {P1,P2,P3}. 4488 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4489 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4490 // 4491 // TODO's: 4492 // 4493 // 1) Extend the Induction descriptor to also support inductions that involve 4494 // casts: When needed (namely, when we are called in the context of the 4495 // vectorizer induction analysis), a Set of cast instructions will be 4496 // populated by this method, and provided back to isInductionPHI. This is 4497 // needed to allow the vectorizer to properly record them to be ignored by 4498 // the cost model and to avoid vectorizing them (otherwise these casts, 4499 // which are redundant under the runtime overflow checks, will be 4500 // vectorized, which can be costly). 4501 // 4502 // 2) Support additional induction/PHISCEV patterns: We also want to support 4503 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4504 // after the induction update operation (the induction increment): 4505 // 4506 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4507 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4508 // 4509 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4510 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4511 // 4512 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4513 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4514 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4515 SmallVector<const SCEVPredicate *, 3> Predicates; 4516 4517 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4518 // return an AddRec expression under some predicate. 4519 4520 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4521 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4522 assert(L && "Expecting an integer loop header phi"); 4523 4524 // The loop may have multiple entrances or multiple exits; we can analyze 4525 // this phi as an addrec if it has a unique entry value and a unique 4526 // backedge value. 4527 Value *BEValueV = nullptr, *StartValueV = nullptr; 4528 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4529 Value *V = PN->getIncomingValue(i); 4530 if (L->contains(PN->getIncomingBlock(i))) { 4531 if (!BEValueV) { 4532 BEValueV = V; 4533 } else if (BEValueV != V) { 4534 BEValueV = nullptr; 4535 break; 4536 } 4537 } else if (!StartValueV) { 4538 StartValueV = V; 4539 } else if (StartValueV != V) { 4540 StartValueV = nullptr; 4541 break; 4542 } 4543 } 4544 if (!BEValueV || !StartValueV) 4545 return None; 4546 4547 const SCEV *BEValue = getSCEV(BEValueV); 4548 4549 // If the value coming around the backedge is an add with the symbolic 4550 // value we just inserted, possibly with casts that we can ignore under 4551 // an appropriate runtime guard, then we found a simple induction variable! 4552 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4553 if (!Add) 4554 return None; 4555 4556 // If there is a single occurrence of the symbolic value, possibly 4557 // casted, replace it with a recurrence. 4558 unsigned FoundIndex = Add->getNumOperands(); 4559 Type *TruncTy = nullptr; 4560 bool Signed; 4561 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4562 if ((TruncTy = 4563 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4564 if (FoundIndex == e) { 4565 FoundIndex = i; 4566 break; 4567 } 4568 4569 if (FoundIndex == Add->getNumOperands()) 4570 return None; 4571 4572 // Create an add with everything but the specified operand. 4573 SmallVector<const SCEV *, 8> Ops; 4574 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4575 if (i != FoundIndex) 4576 Ops.push_back(Add->getOperand(i)); 4577 const SCEV *Accum = getAddExpr(Ops); 4578 4579 // The runtime checks will not be valid if the step amount is 4580 // varying inside the loop. 4581 if (!isLoopInvariant(Accum, L)) 4582 return None; 4583 4584 // *** Part2: Create the predicates 4585 4586 // Analysis was successful: we have a phi-with-cast pattern for which we 4587 // can return an AddRec expression under the following predicates: 4588 // 4589 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4590 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4591 // P2: An Equal predicate that guarantees that 4592 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4593 // P3: An Equal predicate that guarantees that 4594 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4595 // 4596 // As we next prove, the above predicates guarantee that: 4597 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4598 // 4599 // 4600 // More formally, we want to prove that: 4601 // Expr(i+1) = Start + (i+1) * Accum 4602 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4603 // 4604 // Given that: 4605 // 1) Expr(0) = Start 4606 // 2) Expr(1) = Start + Accum 4607 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4608 // 3) Induction hypothesis (step i): 4609 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4610 // 4611 // Proof: 4612 // Expr(i+1) = 4613 // = Start + (i+1)*Accum 4614 // = (Start + i*Accum) + Accum 4615 // = Expr(i) + Accum 4616 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4617 // :: from step i 4618 // 4619 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4620 // 4621 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4622 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4623 // + Accum :: from P3 4624 // 4625 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4626 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4627 // 4628 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4629 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4630 // 4631 // By induction, the same applies to all iterations 1<=i<n: 4632 // 4633 4634 // Create a truncated addrec for which we will add a no overflow check (P1). 4635 const SCEV *StartVal = getSCEV(StartValueV); 4636 const SCEV *PHISCEV = 4637 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4638 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4639 4640 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4641 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4642 // will be constant. 4643 // 4644 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4645 // add P1. 4646 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4647 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4648 Signed ? SCEVWrapPredicate::IncrementNSSW 4649 : SCEVWrapPredicate::IncrementNUSW; 4650 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4651 Predicates.push_back(AddRecPred); 4652 } 4653 4654 // Create the Equal Predicates P2,P3: 4655 4656 // It is possible that the predicates P2 and/or P3 are computable at 4657 // compile time due to StartVal and/or Accum being constants. 4658 // If either one is, then we can check that now and escape if either P2 4659 // or P3 is false. 4660 4661 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4662 // for each of StartVal and Accum 4663 auto getExtendedExpr = [&](const SCEV *Expr, 4664 bool CreateSignExtend) -> const SCEV * { 4665 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4666 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4667 const SCEV *ExtendedExpr = 4668 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4669 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4670 return ExtendedExpr; 4671 }; 4672 4673 // Given: 4674 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4675 // = getExtendedExpr(Expr) 4676 // Determine whether the predicate P: Expr == ExtendedExpr 4677 // is known to be false at compile time 4678 auto PredIsKnownFalse = [&](const SCEV *Expr, 4679 const SCEV *ExtendedExpr) -> bool { 4680 return Expr != ExtendedExpr && 4681 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4682 }; 4683 4684 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4685 if (PredIsKnownFalse(StartVal, StartExtended)) { 4686 DEBUG(dbgs() << "P2 is compile-time false\n";); 4687 return None; 4688 } 4689 4690 // The Step is always Signed (because the overflow checks are either 4691 // NSSW or NUSW) 4692 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4693 if (PredIsKnownFalse(Accum, AccumExtended)) { 4694 DEBUG(dbgs() << "P3 is compile-time false\n";); 4695 return None; 4696 } 4697 4698 auto AppendPredicate = [&](const SCEV *Expr, 4699 const SCEV *ExtendedExpr) -> void { 4700 if (Expr != ExtendedExpr && 4701 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4702 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4703 DEBUG (dbgs() << "Added Predicate: " << *Pred); 4704 Predicates.push_back(Pred); 4705 } 4706 }; 4707 4708 AppendPredicate(StartVal, StartExtended); 4709 AppendPredicate(Accum, AccumExtended); 4710 4711 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4712 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4713 // into NewAR if it will also add the runtime overflow checks specified in 4714 // Predicates. 4715 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4716 4717 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4718 std::make_pair(NewAR, Predicates); 4719 // Remember the result of the analysis for this SCEV at this locayyytion. 4720 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4721 return PredRewrite; 4722 } 4723 4724 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4725 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4726 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4727 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4728 if (!L) 4729 return None; 4730 4731 // Check to see if we already analyzed this PHI. 4732 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4733 if (I != PredicatedSCEVRewrites.end()) { 4734 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4735 I->second; 4736 // Analysis was done before and failed to create an AddRec: 4737 if (Rewrite.first == SymbolicPHI) 4738 return None; 4739 // Analysis was done before and succeeded to create an AddRec under 4740 // a predicate: 4741 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4742 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4743 return Rewrite; 4744 } 4745 4746 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4747 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4748 4749 // Record in the cache that the analysis failed 4750 if (!Rewrite) { 4751 SmallVector<const SCEVPredicate *, 3> Predicates; 4752 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4753 return None; 4754 } 4755 4756 return Rewrite; 4757 } 4758 4759 // FIXME: This utility is currently required because the Rewriter currently 4760 // does not rewrite this expression: 4761 // {0, +, (sext ix (trunc iy to ix) to iy)} 4762 // into {0, +, %step}, 4763 // even when the following Equal predicate exists: 4764 // "%step == (sext ix (trunc iy to ix) to iy)". 4765 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4766 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4767 if (AR1 == AR2) 4768 return true; 4769 4770 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4771 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4772 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4773 return false; 4774 return true; 4775 }; 4776 4777 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4778 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4779 return false; 4780 return true; 4781 } 4782 4783 /// A helper function for createAddRecFromPHI to handle simple cases. 4784 /// 4785 /// This function tries to find an AddRec expression for the simplest (yet most 4786 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4787 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4788 /// technique for finding the AddRec expression. 4789 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4790 Value *BEValueV, 4791 Value *StartValueV) { 4792 const Loop *L = LI.getLoopFor(PN->getParent()); 4793 assert(L && L->getHeader() == PN->getParent()); 4794 assert(BEValueV && StartValueV); 4795 4796 auto BO = MatchBinaryOp(BEValueV, DT); 4797 if (!BO) 4798 return nullptr; 4799 4800 if (BO->Opcode != Instruction::Add) 4801 return nullptr; 4802 4803 const SCEV *Accum = nullptr; 4804 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4805 Accum = getSCEV(BO->RHS); 4806 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4807 Accum = getSCEV(BO->LHS); 4808 4809 if (!Accum) 4810 return nullptr; 4811 4812 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4813 if (BO->IsNUW) 4814 Flags = setFlags(Flags, SCEV::FlagNUW); 4815 if (BO->IsNSW) 4816 Flags = setFlags(Flags, SCEV::FlagNSW); 4817 4818 const SCEV *StartVal = getSCEV(StartValueV); 4819 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4820 4821 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4822 4823 // We can add Flags to the post-inc expression only if we 4824 // know that it is *undefined behavior* for BEValueV to 4825 // overflow. 4826 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4827 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4828 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4829 4830 return PHISCEV; 4831 } 4832 4833 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4834 const Loop *L = LI.getLoopFor(PN->getParent()); 4835 if (!L || L->getHeader() != PN->getParent()) 4836 return nullptr; 4837 4838 // The loop may have multiple entrances or multiple exits; we can analyze 4839 // this phi as an addrec if it has a unique entry value and a unique 4840 // backedge value. 4841 Value *BEValueV = nullptr, *StartValueV = nullptr; 4842 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4843 Value *V = PN->getIncomingValue(i); 4844 if (L->contains(PN->getIncomingBlock(i))) { 4845 if (!BEValueV) { 4846 BEValueV = V; 4847 } else if (BEValueV != V) { 4848 BEValueV = nullptr; 4849 break; 4850 } 4851 } else if (!StartValueV) { 4852 StartValueV = V; 4853 } else if (StartValueV != V) { 4854 StartValueV = nullptr; 4855 break; 4856 } 4857 } 4858 if (!BEValueV || !StartValueV) 4859 return nullptr; 4860 4861 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4862 "PHI node already processed?"); 4863 4864 // First, try to find AddRec expression without creating a fictituos symbolic 4865 // value for PN. 4866 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 4867 return S; 4868 4869 // Handle PHI node value symbolically. 4870 const SCEV *SymbolicName = getUnknown(PN); 4871 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4872 4873 // Using this symbolic name for the PHI, analyze the value coming around 4874 // the back-edge. 4875 const SCEV *BEValue = getSCEV(BEValueV); 4876 4877 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4878 // has a special value for the first iteration of the loop. 4879 4880 // If the value coming around the backedge is an add with the symbolic 4881 // value we just inserted, then we found a simple induction variable! 4882 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4883 // If there is a single occurrence of the symbolic value, replace it 4884 // with a recurrence. 4885 unsigned FoundIndex = Add->getNumOperands(); 4886 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4887 if (Add->getOperand(i) == SymbolicName) 4888 if (FoundIndex == e) { 4889 FoundIndex = i; 4890 break; 4891 } 4892 4893 if (FoundIndex != Add->getNumOperands()) { 4894 // Create an add with everything but the specified operand. 4895 SmallVector<const SCEV *, 8> Ops; 4896 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4897 if (i != FoundIndex) 4898 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 4899 L, *this)); 4900 const SCEV *Accum = getAddExpr(Ops); 4901 4902 // This is not a valid addrec if the step amount is varying each 4903 // loop iteration, but is not itself an addrec in this loop. 4904 if (isLoopInvariant(Accum, L) || 4905 (isa<SCEVAddRecExpr>(Accum) && 4906 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4907 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4908 4909 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4910 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4911 if (BO->IsNUW) 4912 Flags = setFlags(Flags, SCEV::FlagNUW); 4913 if (BO->IsNSW) 4914 Flags = setFlags(Flags, SCEV::FlagNSW); 4915 } 4916 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4917 // If the increment is an inbounds GEP, then we know the address 4918 // space cannot be wrapped around. We cannot make any guarantee 4919 // about signed or unsigned overflow because pointers are 4920 // unsigned but we may have a negative index from the base 4921 // pointer. We can guarantee that no unsigned wrap occurs if the 4922 // indices form a positive value. 4923 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4924 Flags = setFlags(Flags, SCEV::FlagNW); 4925 4926 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4927 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4928 Flags = setFlags(Flags, SCEV::FlagNUW); 4929 } 4930 4931 // We cannot transfer nuw and nsw flags from subtraction 4932 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4933 // for instance. 4934 } 4935 4936 const SCEV *StartVal = getSCEV(StartValueV); 4937 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4938 4939 // Okay, for the entire analysis of this edge we assumed the PHI 4940 // to be symbolic. We now need to go back and purge all of the 4941 // entries for the scalars that use the symbolic expression. 4942 forgetSymbolicName(PN, SymbolicName); 4943 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4944 4945 // We can add Flags to the post-inc expression only if we 4946 // know that it is *undefined behavior* for BEValueV to 4947 // overflow. 4948 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4949 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4950 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4951 4952 return PHISCEV; 4953 } 4954 } 4955 } else { 4956 // Otherwise, this could be a loop like this: 4957 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4958 // In this case, j = {1,+,1} and BEValue is j. 4959 // Because the other in-value of i (0) fits the evolution of BEValue 4960 // i really is an addrec evolution. 4961 // 4962 // We can generalize this saying that i is the shifted value of BEValue 4963 // by one iteration: 4964 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4965 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4966 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 4967 if (Shifted != getCouldNotCompute() && 4968 Start != getCouldNotCompute()) { 4969 const SCEV *StartVal = getSCEV(StartValueV); 4970 if (Start == StartVal) { 4971 // Okay, for the entire analysis of this edge we assumed the PHI 4972 // to be symbolic. We now need to go back and purge all of the 4973 // entries for the scalars that use the symbolic expression. 4974 forgetSymbolicName(PN, SymbolicName); 4975 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4976 return Shifted; 4977 } 4978 } 4979 } 4980 4981 // Remove the temporary PHI node SCEV that has been inserted while intending 4982 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4983 // as it will prevent later (possibly simpler) SCEV expressions to be added 4984 // to the ValueExprMap. 4985 eraseValueFromMap(PN); 4986 4987 return nullptr; 4988 } 4989 4990 // Checks if the SCEV S is available at BB. S is considered available at BB 4991 // if S can be materialized at BB without introducing a fault. 4992 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4993 BasicBlock *BB) { 4994 struct CheckAvailable { 4995 bool TraversalDone = false; 4996 bool Available = true; 4997 4998 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4999 BasicBlock *BB = nullptr; 5000 DominatorTree &DT; 5001 5002 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5003 : L(L), BB(BB), DT(DT) {} 5004 5005 bool setUnavailable() { 5006 TraversalDone = true; 5007 Available = false; 5008 return false; 5009 } 5010 5011 bool follow(const SCEV *S) { 5012 switch (S->getSCEVType()) { 5013 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5014 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5015 // These expressions are available if their operand(s) is/are. 5016 return true; 5017 5018 case scAddRecExpr: { 5019 // We allow add recurrences that are on the loop BB is in, or some 5020 // outer loop. This guarantees availability because the value of the 5021 // add recurrence at BB is simply the "current" value of the induction 5022 // variable. We can relax this in the future; for instance an add 5023 // recurrence on a sibling dominating loop is also available at BB. 5024 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5025 if (L && (ARLoop == L || ARLoop->contains(L))) 5026 return true; 5027 5028 return setUnavailable(); 5029 } 5030 5031 case scUnknown: { 5032 // For SCEVUnknown, we check for simple dominance. 5033 const auto *SU = cast<SCEVUnknown>(S); 5034 Value *V = SU->getValue(); 5035 5036 if (isa<Argument>(V)) 5037 return false; 5038 5039 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5040 return false; 5041 5042 return setUnavailable(); 5043 } 5044 5045 case scUDivExpr: 5046 case scCouldNotCompute: 5047 // We do not try to smart about these at all. 5048 return setUnavailable(); 5049 } 5050 llvm_unreachable("switch should be fully covered!"); 5051 } 5052 5053 bool isDone() { return TraversalDone; } 5054 }; 5055 5056 CheckAvailable CA(L, BB, DT); 5057 SCEVTraversal<CheckAvailable> ST(CA); 5058 5059 ST.visitAll(S); 5060 return CA.Available; 5061 } 5062 5063 // Try to match a control flow sequence that branches out at BI and merges back 5064 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5065 // match. 5066 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5067 Value *&C, Value *&LHS, Value *&RHS) { 5068 C = BI->getCondition(); 5069 5070 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5071 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5072 5073 if (!LeftEdge.isSingleEdge()) 5074 return false; 5075 5076 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5077 5078 Use &LeftUse = Merge->getOperandUse(0); 5079 Use &RightUse = Merge->getOperandUse(1); 5080 5081 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5082 LHS = LeftUse; 5083 RHS = RightUse; 5084 return true; 5085 } 5086 5087 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5088 LHS = RightUse; 5089 RHS = LeftUse; 5090 return true; 5091 } 5092 5093 return false; 5094 } 5095 5096 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5097 auto IsReachable = 5098 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5099 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5100 const Loop *L = LI.getLoopFor(PN->getParent()); 5101 5102 // We don't want to break LCSSA, even in a SCEV expression tree. 5103 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5104 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5105 return nullptr; 5106 5107 // Try to match 5108 // 5109 // br %cond, label %left, label %right 5110 // left: 5111 // br label %merge 5112 // right: 5113 // br label %merge 5114 // merge: 5115 // V = phi [ %x, %left ], [ %y, %right ] 5116 // 5117 // as "select %cond, %x, %y" 5118 5119 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5120 assert(IDom && "At least the entry block should dominate PN"); 5121 5122 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5123 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5124 5125 if (BI && BI->isConditional() && 5126 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5127 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5128 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5129 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5130 } 5131 5132 return nullptr; 5133 } 5134 5135 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5136 if (const SCEV *S = createAddRecFromPHI(PN)) 5137 return S; 5138 5139 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5140 return S; 5141 5142 // If the PHI has a single incoming value, follow that value, unless the 5143 // PHI's incoming blocks are in a different loop, in which case doing so 5144 // risks breaking LCSSA form. Instcombine would normally zap these, but 5145 // it doesn't have DominatorTree information, so it may miss cases. 5146 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5147 if (LI.replacementPreservesLCSSAForm(PN, V)) 5148 return getSCEV(V); 5149 5150 // If it's not a loop phi, we can't handle it yet. 5151 return getUnknown(PN); 5152 } 5153 5154 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5155 Value *Cond, 5156 Value *TrueVal, 5157 Value *FalseVal) { 5158 // Handle "constant" branch or select. This can occur for instance when a 5159 // loop pass transforms an inner loop and moves on to process the outer loop. 5160 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5161 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5162 5163 // Try to match some simple smax or umax patterns. 5164 auto *ICI = dyn_cast<ICmpInst>(Cond); 5165 if (!ICI) 5166 return getUnknown(I); 5167 5168 Value *LHS = ICI->getOperand(0); 5169 Value *RHS = ICI->getOperand(1); 5170 5171 switch (ICI->getPredicate()) { 5172 case ICmpInst::ICMP_SLT: 5173 case ICmpInst::ICMP_SLE: 5174 std::swap(LHS, RHS); 5175 LLVM_FALLTHROUGH; 5176 case ICmpInst::ICMP_SGT: 5177 case ICmpInst::ICMP_SGE: 5178 // a >s b ? a+x : b+x -> smax(a, b)+x 5179 // a >s b ? b+x : a+x -> smin(a, b)+x 5180 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5181 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5182 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5183 const SCEV *LA = getSCEV(TrueVal); 5184 const SCEV *RA = getSCEV(FalseVal); 5185 const SCEV *LDiff = getMinusSCEV(LA, LS); 5186 const SCEV *RDiff = getMinusSCEV(RA, RS); 5187 if (LDiff == RDiff) 5188 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5189 LDiff = getMinusSCEV(LA, RS); 5190 RDiff = getMinusSCEV(RA, LS); 5191 if (LDiff == RDiff) 5192 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5193 } 5194 break; 5195 case ICmpInst::ICMP_ULT: 5196 case ICmpInst::ICMP_ULE: 5197 std::swap(LHS, RHS); 5198 LLVM_FALLTHROUGH; 5199 case ICmpInst::ICMP_UGT: 5200 case ICmpInst::ICMP_UGE: 5201 // a >u b ? a+x : b+x -> umax(a, b)+x 5202 // a >u b ? b+x : a+x -> umin(a, b)+x 5203 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5204 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5205 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5206 const SCEV *LA = getSCEV(TrueVal); 5207 const SCEV *RA = getSCEV(FalseVal); 5208 const SCEV *LDiff = getMinusSCEV(LA, LS); 5209 const SCEV *RDiff = getMinusSCEV(RA, RS); 5210 if (LDiff == RDiff) 5211 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5212 LDiff = getMinusSCEV(LA, RS); 5213 RDiff = getMinusSCEV(RA, LS); 5214 if (LDiff == RDiff) 5215 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5216 } 5217 break; 5218 case ICmpInst::ICMP_NE: 5219 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5220 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5221 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5222 const SCEV *One = getOne(I->getType()); 5223 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5224 const SCEV *LA = getSCEV(TrueVal); 5225 const SCEV *RA = getSCEV(FalseVal); 5226 const SCEV *LDiff = getMinusSCEV(LA, LS); 5227 const SCEV *RDiff = getMinusSCEV(RA, One); 5228 if (LDiff == RDiff) 5229 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5230 } 5231 break; 5232 case ICmpInst::ICMP_EQ: 5233 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5234 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5235 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5236 const SCEV *One = getOne(I->getType()); 5237 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5238 const SCEV *LA = getSCEV(TrueVal); 5239 const SCEV *RA = getSCEV(FalseVal); 5240 const SCEV *LDiff = getMinusSCEV(LA, One); 5241 const SCEV *RDiff = getMinusSCEV(RA, LS); 5242 if (LDiff == RDiff) 5243 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5244 } 5245 break; 5246 default: 5247 break; 5248 } 5249 5250 return getUnknown(I); 5251 } 5252 5253 /// Expand GEP instructions into add and multiply operations. This allows them 5254 /// to be analyzed by regular SCEV code. 5255 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5256 // Don't attempt to analyze GEPs over unsized objects. 5257 if (!GEP->getSourceElementType()->isSized()) 5258 return getUnknown(GEP); 5259 5260 SmallVector<const SCEV *, 4> IndexExprs; 5261 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5262 IndexExprs.push_back(getSCEV(*Index)); 5263 return getGEPExpr(GEP, IndexExprs); 5264 } 5265 5266 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5267 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5268 return C->getAPInt().countTrailingZeros(); 5269 5270 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5271 return std::min(GetMinTrailingZeros(T->getOperand()), 5272 (uint32_t)getTypeSizeInBits(T->getType())); 5273 5274 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5275 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5276 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5277 ? getTypeSizeInBits(E->getType()) 5278 : OpRes; 5279 } 5280 5281 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5282 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5283 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5284 ? getTypeSizeInBits(E->getType()) 5285 : OpRes; 5286 } 5287 5288 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5289 // The result is the min of all operands results. 5290 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5291 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5292 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5293 return MinOpRes; 5294 } 5295 5296 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5297 // The result is the sum of all operands results. 5298 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5299 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5300 for (unsigned i = 1, e = M->getNumOperands(); 5301 SumOpRes != BitWidth && i != e; ++i) 5302 SumOpRes = 5303 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5304 return SumOpRes; 5305 } 5306 5307 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5308 // The result is the min of all operands results. 5309 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5310 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5311 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5312 return MinOpRes; 5313 } 5314 5315 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5316 // The result is the min of all operands results. 5317 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5318 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5319 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5320 return MinOpRes; 5321 } 5322 5323 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5324 // The result is the min of all operands results. 5325 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5326 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5327 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5328 return MinOpRes; 5329 } 5330 5331 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5332 // For a SCEVUnknown, ask ValueTracking. 5333 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5334 return Known.countMinTrailingZeros(); 5335 } 5336 5337 // SCEVUDivExpr 5338 return 0; 5339 } 5340 5341 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5342 auto I = MinTrailingZerosCache.find(S); 5343 if (I != MinTrailingZerosCache.end()) 5344 return I->second; 5345 5346 uint32_t Result = GetMinTrailingZerosImpl(S); 5347 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5348 assert(InsertPair.second && "Should insert a new key"); 5349 return InsertPair.first->second; 5350 } 5351 5352 /// Helper method to assign a range to V from metadata present in the IR. 5353 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5354 if (Instruction *I = dyn_cast<Instruction>(V)) 5355 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5356 return getConstantRangeFromMetadata(*MD); 5357 5358 return None; 5359 } 5360 5361 /// Determine the range for a particular SCEV. If SignHint is 5362 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5363 /// with a "cleaner" unsigned (resp. signed) representation. 5364 const ConstantRange & 5365 ScalarEvolution::getRangeRef(const SCEV *S, 5366 ScalarEvolution::RangeSignHint SignHint) { 5367 DenseMap<const SCEV *, ConstantRange> &Cache = 5368 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5369 : SignedRanges; 5370 5371 // See if we've computed this range already. 5372 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5373 if (I != Cache.end()) 5374 return I->second; 5375 5376 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5377 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5378 5379 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5380 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5381 5382 // If the value has known zeros, the maximum value will have those known zeros 5383 // as well. 5384 uint32_t TZ = GetMinTrailingZeros(S); 5385 if (TZ != 0) { 5386 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5387 ConservativeResult = 5388 ConstantRange(APInt::getMinValue(BitWidth), 5389 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5390 else 5391 ConservativeResult = ConstantRange( 5392 APInt::getSignedMinValue(BitWidth), 5393 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5394 } 5395 5396 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5397 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5398 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5399 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5400 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 5401 } 5402 5403 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5404 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5405 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5406 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5407 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 5408 } 5409 5410 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5411 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5412 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5413 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5414 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 5415 } 5416 5417 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5418 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5419 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5420 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5421 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 5422 } 5423 5424 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5425 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5426 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5427 return setRange(UDiv, SignHint, 5428 ConservativeResult.intersectWith(X.udiv(Y))); 5429 } 5430 5431 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5432 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5433 return setRange(ZExt, SignHint, 5434 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 5435 } 5436 5437 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5438 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5439 return setRange(SExt, SignHint, 5440 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 5441 } 5442 5443 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5444 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5445 return setRange(Trunc, SignHint, 5446 ConservativeResult.intersectWith(X.truncate(BitWidth))); 5447 } 5448 5449 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5450 // If there's no unsigned wrap, the value will never be less than its 5451 // initial value. 5452 if (AddRec->hasNoUnsignedWrap()) 5453 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5454 if (!C->getValue()->isZero()) 5455 ConservativeResult = ConservativeResult.intersectWith( 5456 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 5457 5458 // If there's no signed wrap, and all the operands have the same sign or 5459 // zero, the value won't ever change sign. 5460 if (AddRec->hasNoSignedWrap()) { 5461 bool AllNonNeg = true; 5462 bool AllNonPos = true; 5463 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5464 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5465 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5466 } 5467 if (AllNonNeg) 5468 ConservativeResult = ConservativeResult.intersectWith( 5469 ConstantRange(APInt(BitWidth, 0), 5470 APInt::getSignedMinValue(BitWidth))); 5471 else if (AllNonPos) 5472 ConservativeResult = ConservativeResult.intersectWith( 5473 ConstantRange(APInt::getSignedMinValue(BitWidth), 5474 APInt(BitWidth, 1))); 5475 } 5476 5477 // TODO: non-affine addrec 5478 if (AddRec->isAffine()) { 5479 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 5480 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5481 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5482 auto RangeFromAffine = getRangeForAffineAR( 5483 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5484 BitWidth); 5485 if (!RangeFromAffine.isFullSet()) 5486 ConservativeResult = 5487 ConservativeResult.intersectWith(RangeFromAffine); 5488 5489 auto RangeFromFactoring = getRangeViaFactoring( 5490 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5491 BitWidth); 5492 if (!RangeFromFactoring.isFullSet()) 5493 ConservativeResult = 5494 ConservativeResult.intersectWith(RangeFromFactoring); 5495 } 5496 } 5497 5498 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5499 } 5500 5501 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5502 // Check if the IR explicitly contains !range metadata. 5503 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5504 if (MDRange.hasValue()) 5505 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 5506 5507 // Split here to avoid paying the compile-time cost of calling both 5508 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5509 // if needed. 5510 const DataLayout &DL = getDataLayout(); 5511 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5512 // For a SCEVUnknown, ask ValueTracking. 5513 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5514 if (Known.One != ~Known.Zero + 1) 5515 ConservativeResult = 5516 ConservativeResult.intersectWith(ConstantRange(Known.One, 5517 ~Known.Zero + 1)); 5518 } else { 5519 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5520 "generalize as needed!"); 5521 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5522 if (NS > 1) 5523 ConservativeResult = ConservativeResult.intersectWith( 5524 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5525 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 5526 } 5527 5528 // A range of Phi is a subset of union of all ranges of its input. 5529 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5530 // Make sure that we do not run over cycled Phis. 5531 if (PendingPhiRanges.insert(Phi).second) { 5532 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5533 for (auto &Op : Phi->operands()) { 5534 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5535 RangeFromOps = RangeFromOps.unionWith(OpRange); 5536 // No point to continue if we already have a full set. 5537 if (RangeFromOps.isFullSet()) 5538 break; 5539 } 5540 ConservativeResult = ConservativeResult.intersectWith(RangeFromOps); 5541 bool Erased = PendingPhiRanges.erase(Phi); 5542 assert(Erased && "Failed to erase Phi properly?"); 5543 (void) Erased; 5544 } 5545 } 5546 5547 return setRange(U, SignHint, std::move(ConservativeResult)); 5548 } 5549 5550 return setRange(S, SignHint, std::move(ConservativeResult)); 5551 } 5552 5553 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5554 // values that the expression can take. Initially, the expression has a value 5555 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5556 // argument defines if we treat Step as signed or unsigned. 5557 static ConstantRange getRangeForAffineARHelper(APInt Step, 5558 const ConstantRange &StartRange, 5559 const APInt &MaxBECount, 5560 unsigned BitWidth, bool Signed) { 5561 // If either Step or MaxBECount is 0, then the expression won't change, and we 5562 // just need to return the initial range. 5563 if (Step == 0 || MaxBECount == 0) 5564 return StartRange; 5565 5566 // If we don't know anything about the initial value (i.e. StartRange is 5567 // FullRange), then we don't know anything about the final range either. 5568 // Return FullRange. 5569 if (StartRange.isFullSet()) 5570 return ConstantRange(BitWidth, /* isFullSet = */ true); 5571 5572 // If Step is signed and negative, then we use its absolute value, but we also 5573 // note that we're moving in the opposite direction. 5574 bool Descending = Signed && Step.isNegative(); 5575 5576 if (Signed) 5577 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5578 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5579 // This equations hold true due to the well-defined wrap-around behavior of 5580 // APInt. 5581 Step = Step.abs(); 5582 5583 // Check if Offset is more than full span of BitWidth. If it is, the 5584 // expression is guaranteed to overflow. 5585 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5586 return ConstantRange(BitWidth, /* isFullSet = */ true); 5587 5588 // Offset is by how much the expression can change. Checks above guarantee no 5589 // overflow here. 5590 APInt Offset = Step * MaxBECount; 5591 5592 // Minimum value of the final range will match the minimal value of StartRange 5593 // if the expression is increasing and will be decreased by Offset otherwise. 5594 // Maximum value of the final range will match the maximal value of StartRange 5595 // if the expression is decreasing and will be increased by Offset otherwise. 5596 APInt StartLower = StartRange.getLower(); 5597 APInt StartUpper = StartRange.getUpper() - 1; 5598 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5599 : (StartUpper + std::move(Offset)); 5600 5601 // It's possible that the new minimum/maximum value will fall into the initial 5602 // range (due to wrap around). This means that the expression can take any 5603 // value in this bitwidth, and we have to return full range. 5604 if (StartRange.contains(MovedBoundary)) 5605 return ConstantRange(BitWidth, /* isFullSet = */ true); 5606 5607 APInt NewLower = 5608 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5609 APInt NewUpper = 5610 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5611 NewUpper += 1; 5612 5613 // If we end up with full range, return a proper full range. 5614 if (NewLower == NewUpper) 5615 return ConstantRange(BitWidth, /* isFullSet = */ true); 5616 5617 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5618 return ConstantRange(std::move(NewLower), std::move(NewUpper)); 5619 } 5620 5621 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5622 const SCEV *Step, 5623 const SCEV *MaxBECount, 5624 unsigned BitWidth) { 5625 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5626 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5627 "Precondition!"); 5628 5629 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5630 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5631 5632 // First, consider step signed. 5633 ConstantRange StartSRange = getSignedRange(Start); 5634 ConstantRange StepSRange = getSignedRange(Step); 5635 5636 // If Step can be both positive and negative, we need to find ranges for the 5637 // maximum absolute step values in both directions and union them. 5638 ConstantRange SR = 5639 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5640 MaxBECountValue, BitWidth, /* Signed = */ true); 5641 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5642 StartSRange, MaxBECountValue, 5643 BitWidth, /* Signed = */ true)); 5644 5645 // Next, consider step unsigned. 5646 ConstantRange UR = getRangeForAffineARHelper( 5647 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5648 MaxBECountValue, BitWidth, /* Signed = */ false); 5649 5650 // Finally, intersect signed and unsigned ranges. 5651 return SR.intersectWith(UR); 5652 } 5653 5654 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5655 const SCEV *Step, 5656 const SCEV *MaxBECount, 5657 unsigned BitWidth) { 5658 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5659 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5660 5661 struct SelectPattern { 5662 Value *Condition = nullptr; 5663 APInt TrueValue; 5664 APInt FalseValue; 5665 5666 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5667 const SCEV *S) { 5668 Optional<unsigned> CastOp; 5669 APInt Offset(BitWidth, 0); 5670 5671 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5672 "Should be!"); 5673 5674 // Peel off a constant offset: 5675 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5676 // In the future we could consider being smarter here and handle 5677 // {Start+Step,+,Step} too. 5678 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5679 return; 5680 5681 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5682 S = SA->getOperand(1); 5683 } 5684 5685 // Peel off a cast operation 5686 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5687 CastOp = SCast->getSCEVType(); 5688 S = SCast->getOperand(); 5689 } 5690 5691 using namespace llvm::PatternMatch; 5692 5693 auto *SU = dyn_cast<SCEVUnknown>(S); 5694 const APInt *TrueVal, *FalseVal; 5695 if (!SU || 5696 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5697 m_APInt(FalseVal)))) { 5698 Condition = nullptr; 5699 return; 5700 } 5701 5702 TrueValue = *TrueVal; 5703 FalseValue = *FalseVal; 5704 5705 // Re-apply the cast we peeled off earlier 5706 if (CastOp.hasValue()) 5707 switch (*CastOp) { 5708 default: 5709 llvm_unreachable("Unknown SCEV cast type!"); 5710 5711 case scTruncate: 5712 TrueValue = TrueValue.trunc(BitWidth); 5713 FalseValue = FalseValue.trunc(BitWidth); 5714 break; 5715 case scZeroExtend: 5716 TrueValue = TrueValue.zext(BitWidth); 5717 FalseValue = FalseValue.zext(BitWidth); 5718 break; 5719 case scSignExtend: 5720 TrueValue = TrueValue.sext(BitWidth); 5721 FalseValue = FalseValue.sext(BitWidth); 5722 break; 5723 } 5724 5725 // Re-apply the constant offset we peeled off earlier 5726 TrueValue += Offset; 5727 FalseValue += Offset; 5728 } 5729 5730 bool isRecognized() { return Condition != nullptr; } 5731 }; 5732 5733 SelectPattern StartPattern(*this, BitWidth, Start); 5734 if (!StartPattern.isRecognized()) 5735 return ConstantRange(BitWidth, /* isFullSet = */ true); 5736 5737 SelectPattern StepPattern(*this, BitWidth, Step); 5738 if (!StepPattern.isRecognized()) 5739 return ConstantRange(BitWidth, /* isFullSet = */ true); 5740 5741 if (StartPattern.Condition != StepPattern.Condition) { 5742 // We don't handle this case today; but we could, by considering four 5743 // possibilities below instead of two. I'm not sure if there are cases where 5744 // that will help over what getRange already does, though. 5745 return ConstantRange(BitWidth, /* isFullSet = */ true); 5746 } 5747 5748 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5749 // construct arbitrary general SCEV expressions here. This function is called 5750 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5751 // say) can end up caching a suboptimal value. 5752 5753 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5754 // C2352 and C2512 (otherwise it isn't needed). 5755 5756 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5757 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5758 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5759 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5760 5761 ConstantRange TrueRange = 5762 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5763 ConstantRange FalseRange = 5764 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5765 5766 return TrueRange.unionWith(FalseRange); 5767 } 5768 5769 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5770 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5771 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5772 5773 // Return early if there are no flags to propagate to the SCEV. 5774 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5775 if (BinOp->hasNoUnsignedWrap()) 5776 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5777 if (BinOp->hasNoSignedWrap()) 5778 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5779 if (Flags == SCEV::FlagAnyWrap) 5780 return SCEV::FlagAnyWrap; 5781 5782 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5783 } 5784 5785 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5786 // Here we check that I is in the header of the innermost loop containing I, 5787 // since we only deal with instructions in the loop header. The actual loop we 5788 // need to check later will come from an add recurrence, but getting that 5789 // requires computing the SCEV of the operands, which can be expensive. This 5790 // check we can do cheaply to rule out some cases early. 5791 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5792 if (InnermostContainingLoop == nullptr || 5793 InnermostContainingLoop->getHeader() != I->getParent()) 5794 return false; 5795 5796 // Only proceed if we can prove that I does not yield poison. 5797 if (!programUndefinedIfFullPoison(I)) 5798 return false; 5799 5800 // At this point we know that if I is executed, then it does not wrap 5801 // according to at least one of NSW or NUW. If I is not executed, then we do 5802 // not know if the calculation that I represents would wrap. Multiple 5803 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5804 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5805 // derived from other instructions that map to the same SCEV. We cannot make 5806 // that guarantee for cases where I is not executed. So we need to find the 5807 // loop that I is considered in relation to and prove that I is executed for 5808 // every iteration of that loop. That implies that the value that I 5809 // calculates does not wrap anywhere in the loop, so then we can apply the 5810 // flags to the SCEV. 5811 // 5812 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5813 // from different loops, so that we know which loop to prove that I is 5814 // executed in. 5815 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5816 // I could be an extractvalue from a call to an overflow intrinsic. 5817 // TODO: We can do better here in some cases. 5818 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5819 return false; 5820 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5821 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5822 bool AllOtherOpsLoopInvariant = true; 5823 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5824 ++OtherOpIndex) { 5825 if (OtherOpIndex != OpIndex) { 5826 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5827 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5828 AllOtherOpsLoopInvariant = false; 5829 break; 5830 } 5831 } 5832 } 5833 if (AllOtherOpsLoopInvariant && 5834 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5835 return true; 5836 } 5837 } 5838 return false; 5839 } 5840 5841 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5842 // If we know that \c I can never be poison period, then that's enough. 5843 if (isSCEVExprNeverPoison(I)) 5844 return true; 5845 5846 // For an add recurrence specifically, we assume that infinite loops without 5847 // side effects are undefined behavior, and then reason as follows: 5848 // 5849 // If the add recurrence is poison in any iteration, it is poison on all 5850 // future iterations (since incrementing poison yields poison). If the result 5851 // of the add recurrence is fed into the loop latch condition and the loop 5852 // does not contain any throws or exiting blocks other than the latch, we now 5853 // have the ability to "choose" whether the backedge is taken or not (by 5854 // choosing a sufficiently evil value for the poison feeding into the branch) 5855 // for every iteration including and after the one in which \p I first became 5856 // poison. There are two possibilities (let's call the iteration in which \p 5857 // I first became poison as K): 5858 // 5859 // 1. In the set of iterations including and after K, the loop body executes 5860 // no side effects. In this case executing the backege an infinte number 5861 // of times will yield undefined behavior. 5862 // 5863 // 2. In the set of iterations including and after K, the loop body executes 5864 // at least one side effect. In this case, that specific instance of side 5865 // effect is control dependent on poison, which also yields undefined 5866 // behavior. 5867 5868 auto *ExitingBB = L->getExitingBlock(); 5869 auto *LatchBB = L->getLoopLatch(); 5870 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5871 return false; 5872 5873 SmallPtrSet<const Instruction *, 16> Pushed; 5874 SmallVector<const Instruction *, 8> PoisonStack; 5875 5876 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5877 // things that are known to be fully poison under that assumption go on the 5878 // PoisonStack. 5879 Pushed.insert(I); 5880 PoisonStack.push_back(I); 5881 5882 bool LatchControlDependentOnPoison = false; 5883 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 5884 const Instruction *Poison = PoisonStack.pop_back_val(); 5885 5886 for (auto *PoisonUser : Poison->users()) { 5887 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 5888 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 5889 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 5890 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 5891 assert(BI->isConditional() && "Only possibility!"); 5892 if (BI->getParent() == LatchBB) { 5893 LatchControlDependentOnPoison = true; 5894 break; 5895 } 5896 } 5897 } 5898 } 5899 5900 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 5901 } 5902 5903 ScalarEvolution::LoopProperties 5904 ScalarEvolution::getLoopProperties(const Loop *L) { 5905 using LoopProperties = ScalarEvolution::LoopProperties; 5906 5907 auto Itr = LoopPropertiesCache.find(L); 5908 if (Itr == LoopPropertiesCache.end()) { 5909 auto HasSideEffects = [](Instruction *I) { 5910 if (auto *SI = dyn_cast<StoreInst>(I)) 5911 return !SI->isSimple(); 5912 5913 return I->mayHaveSideEffects(); 5914 }; 5915 5916 LoopProperties LP = {/* HasNoAbnormalExits */ true, 5917 /*HasNoSideEffects*/ true}; 5918 5919 for (auto *BB : L->getBlocks()) 5920 for (auto &I : *BB) { 5921 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5922 LP.HasNoAbnormalExits = false; 5923 if (HasSideEffects(&I)) 5924 LP.HasNoSideEffects = false; 5925 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 5926 break; // We're already as pessimistic as we can get. 5927 } 5928 5929 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 5930 assert(InsertPair.second && "We just checked!"); 5931 Itr = InsertPair.first; 5932 } 5933 5934 return Itr->second; 5935 } 5936 5937 const SCEV *ScalarEvolution::createSCEV(Value *V) { 5938 if (!isSCEVable(V->getType())) 5939 return getUnknown(V); 5940 5941 if (Instruction *I = dyn_cast<Instruction>(V)) { 5942 // Don't attempt to analyze instructions in blocks that aren't 5943 // reachable. Such instructions don't matter, and they aren't required 5944 // to obey basic rules for definitions dominating uses which this 5945 // analysis depends on. 5946 if (!DT.isReachableFromEntry(I->getParent())) 5947 return getUnknown(V); 5948 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5949 return getConstant(CI); 5950 else if (isa<ConstantPointerNull>(V)) 5951 return getZero(V->getType()); 5952 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5953 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5954 else if (!isa<ConstantExpr>(V)) 5955 return getUnknown(V); 5956 5957 Operator *U = cast<Operator>(V); 5958 if (auto BO = MatchBinaryOp(U, DT)) { 5959 switch (BO->Opcode) { 5960 case Instruction::Add: { 5961 // The simple thing to do would be to just call getSCEV on both operands 5962 // and call getAddExpr with the result. However if we're looking at a 5963 // bunch of things all added together, this can be quite inefficient, 5964 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5965 // Instead, gather up all the operands and make a single getAddExpr call. 5966 // LLVM IR canonical form means we need only traverse the left operands. 5967 SmallVector<const SCEV *, 4> AddOps; 5968 do { 5969 if (BO->Op) { 5970 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5971 AddOps.push_back(OpSCEV); 5972 break; 5973 } 5974 5975 // If a NUW or NSW flag can be applied to the SCEV for this 5976 // addition, then compute the SCEV for this addition by itself 5977 // with a separate call to getAddExpr. We need to do that 5978 // instead of pushing the operands of the addition onto AddOps, 5979 // since the flags are only known to apply to this particular 5980 // addition - they may not apply to other additions that can be 5981 // formed with operands from AddOps. 5982 const SCEV *RHS = getSCEV(BO->RHS); 5983 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5984 if (Flags != SCEV::FlagAnyWrap) { 5985 const SCEV *LHS = getSCEV(BO->LHS); 5986 if (BO->Opcode == Instruction::Sub) 5987 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5988 else 5989 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5990 break; 5991 } 5992 } 5993 5994 if (BO->Opcode == Instruction::Sub) 5995 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 5996 else 5997 AddOps.push_back(getSCEV(BO->RHS)); 5998 5999 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6000 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6001 NewBO->Opcode != Instruction::Sub)) { 6002 AddOps.push_back(getSCEV(BO->LHS)); 6003 break; 6004 } 6005 BO = NewBO; 6006 } while (true); 6007 6008 return getAddExpr(AddOps); 6009 } 6010 6011 case Instruction::Mul: { 6012 SmallVector<const SCEV *, 4> MulOps; 6013 do { 6014 if (BO->Op) { 6015 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6016 MulOps.push_back(OpSCEV); 6017 break; 6018 } 6019 6020 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6021 if (Flags != SCEV::FlagAnyWrap) { 6022 MulOps.push_back( 6023 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6024 break; 6025 } 6026 } 6027 6028 MulOps.push_back(getSCEV(BO->RHS)); 6029 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6030 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6031 MulOps.push_back(getSCEV(BO->LHS)); 6032 break; 6033 } 6034 BO = NewBO; 6035 } while (true); 6036 6037 return getMulExpr(MulOps); 6038 } 6039 case Instruction::UDiv: 6040 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6041 case Instruction::URem: 6042 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6043 case Instruction::Sub: { 6044 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6045 if (BO->Op) 6046 Flags = getNoWrapFlagsFromUB(BO->Op); 6047 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6048 } 6049 case Instruction::And: 6050 // For an expression like x&255 that merely masks off the high bits, 6051 // use zext(trunc(x)) as the SCEV expression. 6052 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6053 if (CI->isZero()) 6054 return getSCEV(BO->RHS); 6055 if (CI->isMinusOne()) 6056 return getSCEV(BO->LHS); 6057 const APInt &A = CI->getValue(); 6058 6059 // Instcombine's ShrinkDemandedConstant may strip bits out of 6060 // constants, obscuring what would otherwise be a low-bits mask. 6061 // Use computeKnownBits to compute what ShrinkDemandedConstant 6062 // knew about to reconstruct a low-bits mask value. 6063 unsigned LZ = A.countLeadingZeros(); 6064 unsigned TZ = A.countTrailingZeros(); 6065 unsigned BitWidth = A.getBitWidth(); 6066 KnownBits Known(BitWidth); 6067 computeKnownBits(BO->LHS, Known, getDataLayout(), 6068 0, &AC, nullptr, &DT); 6069 6070 APInt EffectiveMask = 6071 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6072 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6073 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6074 const SCEV *LHS = getSCEV(BO->LHS); 6075 const SCEV *ShiftedLHS = nullptr; 6076 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6077 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6078 // For an expression like (x * 8) & 8, simplify the multiply. 6079 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6080 unsigned GCD = std::min(MulZeros, TZ); 6081 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6082 SmallVector<const SCEV*, 4> MulOps; 6083 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6084 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6085 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6086 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6087 } 6088 } 6089 if (!ShiftedLHS) 6090 ShiftedLHS = getUDivExpr(LHS, MulCount); 6091 return getMulExpr( 6092 getZeroExtendExpr( 6093 getTruncateExpr(ShiftedLHS, 6094 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6095 BO->LHS->getType()), 6096 MulCount); 6097 } 6098 } 6099 break; 6100 6101 case Instruction::Or: 6102 // If the RHS of the Or is a constant, we may have something like: 6103 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6104 // optimizations will transparently handle this case. 6105 // 6106 // In order for this transformation to be safe, the LHS must be of the 6107 // form X*(2^n) and the Or constant must be less than 2^n. 6108 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6109 const SCEV *LHS = getSCEV(BO->LHS); 6110 const APInt &CIVal = CI->getValue(); 6111 if (GetMinTrailingZeros(LHS) >= 6112 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6113 // Build a plain add SCEV. 6114 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6115 // If the LHS of the add was an addrec and it has no-wrap flags, 6116 // transfer the no-wrap flags, since an or won't introduce a wrap. 6117 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6118 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6119 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6120 OldAR->getNoWrapFlags()); 6121 } 6122 return S; 6123 } 6124 } 6125 break; 6126 6127 case Instruction::Xor: 6128 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6129 // If the RHS of xor is -1, then this is a not operation. 6130 if (CI->isMinusOne()) 6131 return getNotSCEV(getSCEV(BO->LHS)); 6132 6133 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6134 // This is a variant of the check for xor with -1, and it handles 6135 // the case where instcombine has trimmed non-demanded bits out 6136 // of an xor with -1. 6137 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6138 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6139 if (LBO->getOpcode() == Instruction::And && 6140 LCI->getValue() == CI->getValue()) 6141 if (const SCEVZeroExtendExpr *Z = 6142 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6143 Type *UTy = BO->LHS->getType(); 6144 const SCEV *Z0 = Z->getOperand(); 6145 Type *Z0Ty = Z0->getType(); 6146 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6147 6148 // If C is a low-bits mask, the zero extend is serving to 6149 // mask off the high bits. Complement the operand and 6150 // re-apply the zext. 6151 if (CI->getValue().isMask(Z0TySize)) 6152 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6153 6154 // If C is a single bit, it may be in the sign-bit position 6155 // before the zero-extend. In this case, represent the xor 6156 // using an add, which is equivalent, and re-apply the zext. 6157 APInt Trunc = CI->getValue().trunc(Z0TySize); 6158 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6159 Trunc.isSignMask()) 6160 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6161 UTy); 6162 } 6163 } 6164 break; 6165 6166 case Instruction::Shl: 6167 // Turn shift left of a constant amount into a multiply. 6168 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6169 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6170 6171 // If the shift count is not less than the bitwidth, the result of 6172 // the shift is undefined. Don't try to analyze it, because the 6173 // resolution chosen here may differ from the resolution chosen in 6174 // other parts of the compiler. 6175 if (SA->getValue().uge(BitWidth)) 6176 break; 6177 6178 // It is currently not resolved how to interpret NSW for left 6179 // shift by BitWidth - 1, so we avoid applying flags in that 6180 // case. Remove this check (or this comment) once the situation 6181 // is resolved. See 6182 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6183 // and http://reviews.llvm.org/D8890 . 6184 auto Flags = SCEV::FlagAnyWrap; 6185 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6186 Flags = getNoWrapFlagsFromUB(BO->Op); 6187 6188 Constant *X = ConstantInt::get(getContext(), 6189 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6190 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6191 } 6192 break; 6193 6194 case Instruction::AShr: { 6195 // AShr X, C, where C is a constant. 6196 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6197 if (!CI) 6198 break; 6199 6200 Type *OuterTy = BO->LHS->getType(); 6201 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6202 // If the shift count is not less than the bitwidth, the result of 6203 // the shift is undefined. Don't try to analyze it, because the 6204 // resolution chosen here may differ from the resolution chosen in 6205 // other parts of the compiler. 6206 if (CI->getValue().uge(BitWidth)) 6207 break; 6208 6209 if (CI->isZero()) 6210 return getSCEV(BO->LHS); // shift by zero --> noop 6211 6212 uint64_t AShrAmt = CI->getZExtValue(); 6213 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6214 6215 Operator *L = dyn_cast<Operator>(BO->LHS); 6216 if (L && L->getOpcode() == Instruction::Shl) { 6217 // X = Shl A, n 6218 // Y = AShr X, m 6219 // Both n and m are constant. 6220 6221 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6222 if (L->getOperand(1) == BO->RHS) 6223 // For a two-shift sext-inreg, i.e. n = m, 6224 // use sext(trunc(x)) as the SCEV expression. 6225 return getSignExtendExpr( 6226 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6227 6228 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6229 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6230 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6231 if (ShlAmt > AShrAmt) { 6232 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6233 // expression. We already checked that ShlAmt < BitWidth, so 6234 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6235 // ShlAmt - AShrAmt < Amt. 6236 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6237 ShlAmt - AShrAmt); 6238 return getSignExtendExpr( 6239 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6240 getConstant(Mul)), OuterTy); 6241 } 6242 } 6243 } 6244 break; 6245 } 6246 } 6247 } 6248 6249 switch (U->getOpcode()) { 6250 case Instruction::Trunc: 6251 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6252 6253 case Instruction::ZExt: 6254 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6255 6256 case Instruction::SExt: 6257 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6258 // The NSW flag of a subtract does not always survive the conversion to 6259 // A + (-1)*B. By pushing sign extension onto its operands we are much 6260 // more likely to preserve NSW and allow later AddRec optimisations. 6261 // 6262 // NOTE: This is effectively duplicating this logic from getSignExtend: 6263 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6264 // but by that point the NSW information has potentially been lost. 6265 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6266 Type *Ty = U->getType(); 6267 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6268 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6269 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6270 } 6271 } 6272 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6273 6274 case Instruction::BitCast: 6275 // BitCasts are no-op casts so we just eliminate the cast. 6276 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6277 return getSCEV(U->getOperand(0)); 6278 break; 6279 6280 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6281 // lead to pointer expressions which cannot safely be expanded to GEPs, 6282 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6283 // simplifying integer expressions. 6284 6285 case Instruction::GetElementPtr: 6286 return createNodeForGEP(cast<GEPOperator>(U)); 6287 6288 case Instruction::PHI: 6289 return createNodeForPHI(cast<PHINode>(U)); 6290 6291 case Instruction::Select: 6292 // U can also be a select constant expr, which let fall through. Since 6293 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6294 // constant expressions cannot have instructions as operands, we'd have 6295 // returned getUnknown for a select constant expressions anyway. 6296 if (isa<Instruction>(U)) 6297 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6298 U->getOperand(1), U->getOperand(2)); 6299 break; 6300 6301 case Instruction::Call: 6302 case Instruction::Invoke: 6303 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6304 return getSCEV(RV); 6305 break; 6306 } 6307 6308 return getUnknown(V); 6309 } 6310 6311 //===----------------------------------------------------------------------===// 6312 // Iteration Count Computation Code 6313 // 6314 6315 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6316 if (!ExitCount) 6317 return 0; 6318 6319 ConstantInt *ExitConst = ExitCount->getValue(); 6320 6321 // Guard against huge trip counts. 6322 if (ExitConst->getValue().getActiveBits() > 32) 6323 return 0; 6324 6325 // In case of integer overflow, this returns 0, which is correct. 6326 return ((unsigned)ExitConst->getZExtValue()) + 1; 6327 } 6328 6329 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6330 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6331 return getSmallConstantTripCount(L, ExitingBB); 6332 6333 // No trip count information for multiple exits. 6334 return 0; 6335 } 6336 6337 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6338 BasicBlock *ExitingBlock) { 6339 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6340 assert(L->isLoopExiting(ExitingBlock) && 6341 "Exiting block must actually branch out of the loop!"); 6342 const SCEVConstant *ExitCount = 6343 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6344 return getConstantTripCount(ExitCount); 6345 } 6346 6347 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6348 const auto *MaxExitCount = 6349 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 6350 return getConstantTripCount(MaxExitCount); 6351 } 6352 6353 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6354 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6355 return getSmallConstantTripMultiple(L, ExitingBB); 6356 6357 // No trip multiple information for multiple exits. 6358 return 0; 6359 } 6360 6361 /// Returns the largest constant divisor of the trip count of this loop as a 6362 /// normal unsigned value, if possible. This means that the actual trip count is 6363 /// always a multiple of the returned value (don't forget the trip count could 6364 /// very well be zero as well!). 6365 /// 6366 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6367 /// multiple of a constant (which is also the case if the trip count is simply 6368 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6369 /// if the trip count is very large (>= 2^32). 6370 /// 6371 /// As explained in the comments for getSmallConstantTripCount, this assumes 6372 /// that control exits the loop via ExitingBlock. 6373 unsigned 6374 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6375 BasicBlock *ExitingBlock) { 6376 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6377 assert(L->isLoopExiting(ExitingBlock) && 6378 "Exiting block must actually branch out of the loop!"); 6379 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6380 if (ExitCount == getCouldNotCompute()) 6381 return 1; 6382 6383 // Get the trip count from the BE count by adding 1. 6384 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6385 6386 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6387 if (!TC) 6388 // Attempt to factor more general cases. Returns the greatest power of 6389 // two divisor. If overflow happens, the trip count expression is still 6390 // divisible by the greatest power of 2 divisor returned. 6391 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6392 6393 ConstantInt *Result = TC->getValue(); 6394 6395 // Guard against huge trip counts (this requires checking 6396 // for zero to handle the case where the trip count == -1 and the 6397 // addition wraps). 6398 if (!Result || Result->getValue().getActiveBits() > 32 || 6399 Result->getValue().getActiveBits() == 0) 6400 return 1; 6401 6402 return (unsigned)Result->getZExtValue(); 6403 } 6404 6405 /// Get the expression for the number of loop iterations for which this loop is 6406 /// guaranteed not to exit via ExitingBlock. Otherwise return 6407 /// SCEVCouldNotCompute. 6408 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6409 BasicBlock *ExitingBlock) { 6410 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6411 } 6412 6413 const SCEV * 6414 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6415 SCEVUnionPredicate &Preds) { 6416 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 6417 } 6418 6419 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6420 return getBackedgeTakenInfo(L).getExact(this); 6421 } 6422 6423 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6424 /// known never to be less than the actual backedge taken count. 6425 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 6426 return getBackedgeTakenInfo(L).getMax(this); 6427 } 6428 6429 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6430 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6431 } 6432 6433 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6434 static void 6435 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6436 BasicBlock *Header = L->getHeader(); 6437 6438 // Push all Loop-header PHIs onto the Worklist stack. 6439 for (PHINode &PN : Header->phis()) 6440 Worklist.push_back(&PN); 6441 } 6442 6443 const ScalarEvolution::BackedgeTakenInfo & 6444 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6445 auto &BTI = getBackedgeTakenInfo(L); 6446 if (BTI.hasFullInfo()) 6447 return BTI; 6448 6449 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6450 6451 if (!Pair.second) 6452 return Pair.first->second; 6453 6454 BackedgeTakenInfo Result = 6455 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6456 6457 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6458 } 6459 6460 const ScalarEvolution::BackedgeTakenInfo & 6461 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6462 // Initially insert an invalid entry for this loop. If the insertion 6463 // succeeds, proceed to actually compute a backedge-taken count and 6464 // update the value. The temporary CouldNotCompute value tells SCEV 6465 // code elsewhere that it shouldn't attempt to request a new 6466 // backedge-taken count, which could result in infinite recursion. 6467 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6468 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6469 if (!Pair.second) 6470 return Pair.first->second; 6471 6472 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6473 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6474 // must be cleared in this scope. 6475 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6476 6477 if (Result.getExact(this) != getCouldNotCompute()) { 6478 assert(isLoopInvariant(Result.getExact(this), L) && 6479 isLoopInvariant(Result.getMax(this), L) && 6480 "Computed backedge-taken count isn't loop invariant for loop!"); 6481 ++NumTripCountsComputed; 6482 } 6483 else if (Result.getMax(this) == getCouldNotCompute() && 6484 isa<PHINode>(L->getHeader()->begin())) { 6485 // Only count loops that have phi nodes as not being computable. 6486 ++NumTripCountsNotComputed; 6487 } 6488 6489 // Now that we know more about the trip count for this loop, forget any 6490 // existing SCEV values for PHI nodes in this loop since they are only 6491 // conservative estimates made without the benefit of trip count 6492 // information. This is similar to the code in forgetLoop, except that 6493 // it handles SCEVUnknown PHI nodes specially. 6494 if (Result.hasAnyInfo()) { 6495 SmallVector<Instruction *, 16> Worklist; 6496 PushLoopPHIs(L, Worklist); 6497 6498 SmallPtrSet<Instruction *, 8> Discovered; 6499 while (!Worklist.empty()) { 6500 Instruction *I = Worklist.pop_back_val(); 6501 6502 ValueExprMapType::iterator It = 6503 ValueExprMap.find_as(static_cast<Value *>(I)); 6504 if (It != ValueExprMap.end()) { 6505 const SCEV *Old = It->second; 6506 6507 // SCEVUnknown for a PHI either means that it has an unrecognized 6508 // structure, or it's a PHI that's in the progress of being computed 6509 // by createNodeForPHI. In the former case, additional loop trip 6510 // count information isn't going to change anything. In the later 6511 // case, createNodeForPHI will perform the necessary updates on its 6512 // own when it gets to that point. 6513 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6514 eraseValueFromMap(It->first); 6515 forgetMemoizedResults(Old); 6516 } 6517 if (PHINode *PN = dyn_cast<PHINode>(I)) 6518 ConstantEvolutionLoopExitValue.erase(PN); 6519 } 6520 6521 // Since we don't need to invalidate anything for correctness and we're 6522 // only invalidating to make SCEV's results more precise, we get to stop 6523 // early to avoid invalidating too much. This is especially important in 6524 // cases like: 6525 // 6526 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6527 // loop0: 6528 // %pn0 = phi 6529 // ... 6530 // loop1: 6531 // %pn1 = phi 6532 // ... 6533 // 6534 // where both loop0 and loop1's backedge taken count uses the SCEV 6535 // expression for %v. If we don't have the early stop below then in cases 6536 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6537 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6538 // count for loop1, effectively nullifying SCEV's trip count cache. 6539 for (auto *U : I->users()) 6540 if (auto *I = dyn_cast<Instruction>(U)) { 6541 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6542 if (LoopForUser && L->contains(LoopForUser) && 6543 Discovered.insert(I).second) 6544 Worklist.push_back(I); 6545 } 6546 } 6547 } 6548 6549 // Re-lookup the insert position, since the call to 6550 // computeBackedgeTakenCount above could result in a 6551 // recusive call to getBackedgeTakenInfo (on a different 6552 // loop), which would invalidate the iterator computed 6553 // earlier. 6554 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6555 } 6556 6557 void ScalarEvolution::forgetLoop(const Loop *L) { 6558 // Drop any stored trip count value. 6559 auto RemoveLoopFromBackedgeMap = 6560 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6561 auto BTCPos = Map.find(L); 6562 if (BTCPos != Map.end()) { 6563 BTCPos->second.clear(); 6564 Map.erase(BTCPos); 6565 } 6566 }; 6567 6568 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6569 SmallVector<Instruction *, 32> Worklist; 6570 SmallPtrSet<Instruction *, 16> Visited; 6571 6572 // Iterate over all the loops and sub-loops to drop SCEV information. 6573 while (!LoopWorklist.empty()) { 6574 auto *CurrL = LoopWorklist.pop_back_val(); 6575 6576 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6577 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6578 6579 // Drop information about predicated SCEV rewrites for this loop. 6580 for (auto I = PredicatedSCEVRewrites.begin(); 6581 I != PredicatedSCEVRewrites.end();) { 6582 std::pair<const SCEV *, const Loop *> Entry = I->first; 6583 if (Entry.second == CurrL) 6584 PredicatedSCEVRewrites.erase(I++); 6585 else 6586 ++I; 6587 } 6588 6589 auto LoopUsersItr = LoopUsers.find(CurrL); 6590 if (LoopUsersItr != LoopUsers.end()) { 6591 for (auto *S : LoopUsersItr->second) 6592 forgetMemoizedResults(S); 6593 LoopUsers.erase(LoopUsersItr); 6594 } 6595 6596 // Drop information about expressions based on loop-header PHIs. 6597 PushLoopPHIs(CurrL, Worklist); 6598 6599 while (!Worklist.empty()) { 6600 Instruction *I = Worklist.pop_back_val(); 6601 if (!Visited.insert(I).second) 6602 continue; 6603 6604 ValueExprMapType::iterator It = 6605 ValueExprMap.find_as(static_cast<Value *>(I)); 6606 if (It != ValueExprMap.end()) { 6607 eraseValueFromMap(It->first); 6608 forgetMemoizedResults(It->second); 6609 if (PHINode *PN = dyn_cast<PHINode>(I)) 6610 ConstantEvolutionLoopExitValue.erase(PN); 6611 } 6612 6613 PushDefUseChildren(I, Worklist); 6614 } 6615 6616 LoopPropertiesCache.erase(CurrL); 6617 // Forget all contained loops too, to avoid dangling entries in the 6618 // ValuesAtScopes map. 6619 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6620 } 6621 } 6622 6623 void ScalarEvolution::forgetValue(Value *V) { 6624 Instruction *I = dyn_cast<Instruction>(V); 6625 if (!I) return; 6626 6627 // Drop information about expressions based on loop-header PHIs. 6628 SmallVector<Instruction *, 16> Worklist; 6629 Worklist.push_back(I); 6630 6631 SmallPtrSet<Instruction *, 8> Visited; 6632 while (!Worklist.empty()) { 6633 I = Worklist.pop_back_val(); 6634 if (!Visited.insert(I).second) 6635 continue; 6636 6637 ValueExprMapType::iterator It = 6638 ValueExprMap.find_as(static_cast<Value *>(I)); 6639 if (It != ValueExprMap.end()) { 6640 eraseValueFromMap(It->first); 6641 forgetMemoizedResults(It->second); 6642 if (PHINode *PN = dyn_cast<PHINode>(I)) 6643 ConstantEvolutionLoopExitValue.erase(PN); 6644 } 6645 6646 PushDefUseChildren(I, Worklist); 6647 } 6648 } 6649 6650 /// Get the exact loop backedge taken count considering all loop exits. A 6651 /// computable result can only be returned for loops with a single exit. 6652 /// Returning the minimum taken count among all exits is incorrect because one 6653 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 6654 /// the limit of each loop test is never skipped. This is a valid assumption as 6655 /// long as the loop exits via that test. For precise results, it is the 6656 /// caller's responsibility to specify the relevant loop exit using 6657 /// getExact(ExitingBlock, SE). 6658 const SCEV * 6659 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, 6660 SCEVUnionPredicate *Preds) const { 6661 // If any exits were not computable, the loop is not computable. 6662 if (!isComplete() || ExitNotTaken.empty()) 6663 return SE->getCouldNotCompute(); 6664 6665 const SCEV *BECount = nullptr; 6666 for (auto &ENT : ExitNotTaken) { 6667 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 6668 6669 if (!BECount) 6670 BECount = ENT.ExactNotTaken; 6671 else if (BECount != ENT.ExactNotTaken) 6672 return SE->getCouldNotCompute(); 6673 if (Preds && !ENT.hasAlwaysTruePredicate()) 6674 Preds->add(ENT.Predicate.get()); 6675 6676 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6677 "Predicate should be always true!"); 6678 } 6679 6680 assert(BECount && "Invalid not taken count for loop exit"); 6681 return BECount; 6682 } 6683 6684 /// Get the exact not taken count for this loop exit. 6685 const SCEV * 6686 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6687 ScalarEvolution *SE) const { 6688 for (auto &ENT : ExitNotTaken) 6689 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6690 return ENT.ExactNotTaken; 6691 6692 return SE->getCouldNotCompute(); 6693 } 6694 6695 /// getMax - Get the max backedge taken count for the loop. 6696 const SCEV * 6697 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6698 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6699 return !ENT.hasAlwaysTruePredicate(); 6700 }; 6701 6702 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6703 return SE->getCouldNotCompute(); 6704 6705 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6706 "No point in having a non-constant max backedge taken count!"); 6707 return getMax(); 6708 } 6709 6710 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6711 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6712 return !ENT.hasAlwaysTruePredicate(); 6713 }; 6714 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6715 } 6716 6717 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6718 ScalarEvolution *SE) const { 6719 if (getMax() && getMax() != SE->getCouldNotCompute() && 6720 SE->hasOperand(getMax(), S)) 6721 return true; 6722 6723 for (auto &ENT : ExitNotTaken) 6724 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6725 SE->hasOperand(ENT.ExactNotTaken, S)) 6726 return true; 6727 6728 return false; 6729 } 6730 6731 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6732 : ExactNotTaken(E), MaxNotTaken(E) { 6733 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6734 isa<SCEVConstant>(MaxNotTaken)) && 6735 "No point in having a non-constant max backedge taken count!"); 6736 } 6737 6738 ScalarEvolution::ExitLimit::ExitLimit( 6739 const SCEV *E, const SCEV *M, bool MaxOrZero, 6740 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6741 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6742 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6743 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6744 "Exact is not allowed to be less precise than Max"); 6745 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6746 isa<SCEVConstant>(MaxNotTaken)) && 6747 "No point in having a non-constant max backedge taken count!"); 6748 for (auto *PredSet : PredSetList) 6749 for (auto *P : *PredSet) 6750 addPredicate(P); 6751 } 6752 6753 ScalarEvolution::ExitLimit::ExitLimit( 6754 const SCEV *E, const SCEV *M, bool MaxOrZero, 6755 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6756 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6757 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6758 isa<SCEVConstant>(MaxNotTaken)) && 6759 "No point in having a non-constant max backedge taken count!"); 6760 } 6761 6762 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6763 bool MaxOrZero) 6764 : ExitLimit(E, M, MaxOrZero, None) { 6765 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6766 isa<SCEVConstant>(MaxNotTaken)) && 6767 "No point in having a non-constant max backedge taken count!"); 6768 } 6769 6770 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 6771 /// computable exit into a persistent ExitNotTakenInfo array. 6772 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 6773 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 6774 &&ExitCounts, 6775 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 6776 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 6777 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6778 6779 ExitNotTaken.reserve(ExitCounts.size()); 6780 std::transform( 6781 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 6782 [&](const EdgeExitInfo &EEI) { 6783 BasicBlock *ExitBB = EEI.first; 6784 const ExitLimit &EL = EEI.second; 6785 if (EL.Predicates.empty()) 6786 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 6787 6788 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 6789 for (auto *Pred : EL.Predicates) 6790 Predicate->add(Pred); 6791 6792 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 6793 }); 6794 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 6795 "No point in having a non-constant max backedge taken count!"); 6796 } 6797 6798 /// Invalidate this result and free the ExitNotTakenInfo array. 6799 void ScalarEvolution::BackedgeTakenInfo::clear() { 6800 ExitNotTaken.clear(); 6801 } 6802 6803 /// Compute the number of times the backedge of the specified loop will execute. 6804 ScalarEvolution::BackedgeTakenInfo 6805 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 6806 bool AllowPredicates) { 6807 SmallVector<BasicBlock *, 8> ExitingBlocks; 6808 L->getExitingBlocks(ExitingBlocks); 6809 6810 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6811 6812 SmallVector<EdgeExitInfo, 4> ExitCounts; 6813 bool CouldComputeBECount = true; 6814 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 6815 const SCEV *MustExitMaxBECount = nullptr; 6816 const SCEV *MayExitMaxBECount = nullptr; 6817 bool MustExitMaxOrZero = false; 6818 6819 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 6820 // and compute maxBECount. 6821 // Do a union of all the predicates here. 6822 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 6823 BasicBlock *ExitBB = ExitingBlocks[i]; 6824 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 6825 6826 assert((AllowPredicates || EL.Predicates.empty()) && 6827 "Predicated exit limit when predicates are not allowed!"); 6828 6829 // 1. For each exit that can be computed, add an entry to ExitCounts. 6830 // CouldComputeBECount is true only if all exits can be computed. 6831 if (EL.ExactNotTaken == getCouldNotCompute()) 6832 // We couldn't compute an exact value for this exit, so 6833 // we won't be able to compute an exact value for the loop. 6834 CouldComputeBECount = false; 6835 else 6836 ExitCounts.emplace_back(ExitBB, EL); 6837 6838 // 2. Derive the loop's MaxBECount from each exit's max number of 6839 // non-exiting iterations. Partition the loop exits into two kinds: 6840 // LoopMustExits and LoopMayExits. 6841 // 6842 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 6843 // is a LoopMayExit. If any computable LoopMustExit is found, then 6844 // MaxBECount is the minimum EL.MaxNotTaken of computable 6845 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 6846 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 6847 // computable EL.MaxNotTaken. 6848 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 6849 DT.dominates(ExitBB, Latch)) { 6850 if (!MustExitMaxBECount) { 6851 MustExitMaxBECount = EL.MaxNotTaken; 6852 MustExitMaxOrZero = EL.MaxOrZero; 6853 } else { 6854 MustExitMaxBECount = 6855 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 6856 } 6857 } else if (MayExitMaxBECount != getCouldNotCompute()) { 6858 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 6859 MayExitMaxBECount = EL.MaxNotTaken; 6860 else { 6861 MayExitMaxBECount = 6862 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 6863 } 6864 } 6865 } 6866 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 6867 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 6868 // The loop backedge will be taken the maximum or zero times if there's 6869 // a single exit that must be taken the maximum or zero times. 6870 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 6871 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 6872 MaxBECount, MaxOrZero); 6873 } 6874 6875 ScalarEvolution::ExitLimit 6876 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 6877 bool AllowPredicates) { 6878 // Okay, we've chosen an exiting block. See what condition causes us to exit 6879 // at this block and remember the exit block and whether all other targets 6880 // lead to the loop header. 6881 bool MustExecuteLoopHeader = true; 6882 BasicBlock *Exit = nullptr; 6883 for (auto *SBB : successors(ExitingBlock)) 6884 if (!L->contains(SBB)) { 6885 if (Exit) // Multiple exit successors. 6886 return getCouldNotCompute(); 6887 Exit = SBB; 6888 } else if (SBB != L->getHeader()) { 6889 MustExecuteLoopHeader = false; 6890 } 6891 6892 // At this point, we know we have a conditional branch that determines whether 6893 // the loop is exited. However, we don't know if the branch is executed each 6894 // time through the loop. If not, then the execution count of the branch will 6895 // not be equal to the trip count of the loop. 6896 // 6897 // Currently we check for this by checking to see if the Exit branch goes to 6898 // the loop header. If so, we know it will always execute the same number of 6899 // times as the loop. We also handle the case where the exit block *is* the 6900 // loop header. This is common for un-rotated loops. 6901 // 6902 // If both of those tests fail, walk up the unique predecessor chain to the 6903 // header, stopping if there is an edge that doesn't exit the loop. If the 6904 // header is reached, the execution count of the branch will be equal to the 6905 // trip count of the loop. 6906 // 6907 // More extensive analysis could be done to handle more cases here. 6908 // 6909 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 6910 // The simple checks failed, try climbing the unique predecessor chain 6911 // up to the header. 6912 bool Ok = false; 6913 for (BasicBlock *BB = ExitingBlock; BB; ) { 6914 BasicBlock *Pred = BB->getUniquePredecessor(); 6915 if (!Pred) 6916 return getCouldNotCompute(); 6917 TerminatorInst *PredTerm = Pred->getTerminator(); 6918 for (const BasicBlock *PredSucc : PredTerm->successors()) { 6919 if (PredSucc == BB) 6920 continue; 6921 // If the predecessor has a successor that isn't BB and isn't 6922 // outside the loop, assume the worst. 6923 if (L->contains(PredSucc)) 6924 return getCouldNotCompute(); 6925 } 6926 if (Pred == L->getHeader()) { 6927 Ok = true; 6928 break; 6929 } 6930 BB = Pred; 6931 } 6932 if (!Ok) 6933 return getCouldNotCompute(); 6934 } 6935 6936 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 6937 TerminatorInst *Term = ExitingBlock->getTerminator(); 6938 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 6939 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 6940 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 6941 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 6942 "It should have one successor in loop and one exit block!"); 6943 // Proceed to the next level to examine the exit condition expression. 6944 return computeExitLimitFromCond( 6945 L, BI->getCondition(), ExitIfTrue, 6946 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 6947 } 6948 6949 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 6950 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 6951 /*ControlsExit=*/IsOnlyExit); 6952 6953 return getCouldNotCompute(); 6954 } 6955 6956 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 6957 const Loop *L, Value *ExitCond, bool ExitIfTrue, 6958 bool ControlsExit, bool AllowPredicates) { 6959 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 6960 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 6961 ControlsExit, AllowPredicates); 6962 } 6963 6964 Optional<ScalarEvolution::ExitLimit> 6965 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 6966 bool ExitIfTrue, bool ControlsExit, 6967 bool AllowPredicates) { 6968 (void)this->L; 6969 (void)this->ExitIfTrue; 6970 (void)this->AllowPredicates; 6971 6972 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 6973 this->AllowPredicates == AllowPredicates && 6974 "Variance in assumed invariant key components!"); 6975 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 6976 if (Itr == TripCountMap.end()) 6977 return None; 6978 return Itr->second; 6979 } 6980 6981 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 6982 bool ExitIfTrue, 6983 bool ControlsExit, 6984 bool AllowPredicates, 6985 const ExitLimit &EL) { 6986 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 6987 this->AllowPredicates == AllowPredicates && 6988 "Variance in assumed invariant key components!"); 6989 6990 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 6991 assert(InsertResult.second && "Expected successful insertion!"); 6992 (void)InsertResult; 6993 (void)ExitIfTrue; 6994 } 6995 6996 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 6997 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 6998 bool ControlsExit, bool AllowPredicates) { 6999 7000 if (auto MaybeEL = 7001 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7002 return *MaybeEL; 7003 7004 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7005 ControlsExit, AllowPredicates); 7006 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7007 return EL; 7008 } 7009 7010 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7011 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7012 bool ControlsExit, bool AllowPredicates) { 7013 // Check if the controlling expression for this loop is an And or Or. 7014 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7015 if (BO->getOpcode() == Instruction::And) { 7016 // Recurse on the operands of the and. 7017 bool EitherMayExit = !ExitIfTrue; 7018 ExitLimit EL0 = computeExitLimitFromCondCached( 7019 Cache, L, BO->getOperand(0), ExitIfTrue, 7020 ControlsExit && !EitherMayExit, AllowPredicates); 7021 ExitLimit EL1 = computeExitLimitFromCondCached( 7022 Cache, L, BO->getOperand(1), ExitIfTrue, 7023 ControlsExit && !EitherMayExit, AllowPredicates); 7024 const SCEV *BECount = getCouldNotCompute(); 7025 const SCEV *MaxBECount = getCouldNotCompute(); 7026 if (EitherMayExit) { 7027 // Both conditions must be true for the loop to continue executing. 7028 // Choose the less conservative count. 7029 if (EL0.ExactNotTaken == getCouldNotCompute() || 7030 EL1.ExactNotTaken == getCouldNotCompute()) 7031 BECount = getCouldNotCompute(); 7032 else 7033 BECount = 7034 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7035 if (EL0.MaxNotTaken == getCouldNotCompute()) 7036 MaxBECount = EL1.MaxNotTaken; 7037 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7038 MaxBECount = EL0.MaxNotTaken; 7039 else 7040 MaxBECount = 7041 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7042 } else { 7043 // Both conditions must be true at the same time for the loop to exit. 7044 // For now, be conservative. 7045 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7046 MaxBECount = EL0.MaxNotTaken; 7047 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7048 BECount = EL0.ExactNotTaken; 7049 } 7050 7051 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7052 // to be more aggressive when computing BECount than when computing 7053 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7054 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7055 // to not. 7056 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7057 !isa<SCEVCouldNotCompute>(BECount)) 7058 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7059 7060 return ExitLimit(BECount, MaxBECount, false, 7061 {&EL0.Predicates, &EL1.Predicates}); 7062 } 7063 if (BO->getOpcode() == Instruction::Or) { 7064 // Recurse on the operands of the or. 7065 bool EitherMayExit = ExitIfTrue; 7066 ExitLimit EL0 = computeExitLimitFromCondCached( 7067 Cache, L, BO->getOperand(0), ExitIfTrue, 7068 ControlsExit && !EitherMayExit, AllowPredicates); 7069 ExitLimit EL1 = computeExitLimitFromCondCached( 7070 Cache, L, BO->getOperand(1), ExitIfTrue, 7071 ControlsExit && !EitherMayExit, AllowPredicates); 7072 const SCEV *BECount = getCouldNotCompute(); 7073 const SCEV *MaxBECount = getCouldNotCompute(); 7074 if (EitherMayExit) { 7075 // Both conditions must be false for the loop to continue executing. 7076 // Choose the less conservative count. 7077 if (EL0.ExactNotTaken == getCouldNotCompute() || 7078 EL1.ExactNotTaken == getCouldNotCompute()) 7079 BECount = getCouldNotCompute(); 7080 else 7081 BECount = 7082 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7083 if (EL0.MaxNotTaken == getCouldNotCompute()) 7084 MaxBECount = EL1.MaxNotTaken; 7085 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7086 MaxBECount = EL0.MaxNotTaken; 7087 else 7088 MaxBECount = 7089 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7090 } else { 7091 // Both conditions must be false at the same time for the loop to exit. 7092 // For now, be conservative. 7093 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7094 MaxBECount = EL0.MaxNotTaken; 7095 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7096 BECount = EL0.ExactNotTaken; 7097 } 7098 7099 return ExitLimit(BECount, MaxBECount, false, 7100 {&EL0.Predicates, &EL1.Predicates}); 7101 } 7102 } 7103 7104 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7105 // Proceed to the next level to examine the icmp. 7106 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7107 ExitLimit EL = 7108 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7109 if (EL.hasFullInfo() || !AllowPredicates) 7110 return EL; 7111 7112 // Try again, but use SCEV predicates this time. 7113 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7114 /*AllowPredicates=*/true); 7115 } 7116 7117 // Check for a constant condition. These are normally stripped out by 7118 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7119 // preserve the CFG and is temporarily leaving constant conditions 7120 // in place. 7121 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7122 if (ExitIfTrue == !CI->getZExtValue()) 7123 // The backedge is always taken. 7124 return getCouldNotCompute(); 7125 else 7126 // The backedge is never taken. 7127 return getZero(CI->getType()); 7128 } 7129 7130 // If it's not an integer or pointer comparison then compute it the hard way. 7131 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7132 } 7133 7134 ScalarEvolution::ExitLimit 7135 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7136 ICmpInst *ExitCond, 7137 bool ExitIfTrue, 7138 bool ControlsExit, 7139 bool AllowPredicates) { 7140 // If the condition was exit on true, convert the condition to exit on false 7141 ICmpInst::Predicate Pred; 7142 if (!ExitIfTrue) 7143 Pred = ExitCond->getPredicate(); 7144 else 7145 Pred = ExitCond->getInversePredicate(); 7146 const ICmpInst::Predicate OriginalPred = Pred; 7147 7148 // Handle common loops like: for (X = "string"; *X; ++X) 7149 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7150 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7151 ExitLimit ItCnt = 7152 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7153 if (ItCnt.hasAnyInfo()) 7154 return ItCnt; 7155 } 7156 7157 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7158 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7159 7160 // Try to evaluate any dependencies out of the loop. 7161 LHS = getSCEVAtScope(LHS, L); 7162 RHS = getSCEVAtScope(RHS, L); 7163 7164 // At this point, we would like to compute how many iterations of the 7165 // loop the predicate will return true for these inputs. 7166 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7167 // If there is a loop-invariant, force it into the RHS. 7168 std::swap(LHS, RHS); 7169 Pred = ICmpInst::getSwappedPredicate(Pred); 7170 } 7171 7172 // Simplify the operands before analyzing them. 7173 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7174 7175 // If we have a comparison of a chrec against a constant, try to use value 7176 // ranges to answer this query. 7177 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7178 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7179 if (AddRec->getLoop() == L) { 7180 // Form the constant range. 7181 ConstantRange CompRange = 7182 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7183 7184 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7185 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7186 } 7187 7188 switch (Pred) { 7189 case ICmpInst::ICMP_NE: { // while (X != Y) 7190 // Convert to: while (X-Y != 0) 7191 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7192 AllowPredicates); 7193 if (EL.hasAnyInfo()) return EL; 7194 break; 7195 } 7196 case ICmpInst::ICMP_EQ: { // while (X == Y) 7197 // Convert to: while (X-Y == 0) 7198 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7199 if (EL.hasAnyInfo()) return EL; 7200 break; 7201 } 7202 case ICmpInst::ICMP_SLT: 7203 case ICmpInst::ICMP_ULT: { // while (X < Y) 7204 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7205 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7206 AllowPredicates); 7207 if (EL.hasAnyInfo()) return EL; 7208 break; 7209 } 7210 case ICmpInst::ICMP_SGT: 7211 case ICmpInst::ICMP_UGT: { // while (X > Y) 7212 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7213 ExitLimit EL = 7214 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7215 AllowPredicates); 7216 if (EL.hasAnyInfo()) return EL; 7217 break; 7218 } 7219 default: 7220 break; 7221 } 7222 7223 auto *ExhaustiveCount = 7224 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7225 7226 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7227 return ExhaustiveCount; 7228 7229 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7230 ExitCond->getOperand(1), L, OriginalPred); 7231 } 7232 7233 ScalarEvolution::ExitLimit 7234 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7235 SwitchInst *Switch, 7236 BasicBlock *ExitingBlock, 7237 bool ControlsExit) { 7238 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7239 7240 // Give up if the exit is the default dest of a switch. 7241 if (Switch->getDefaultDest() == ExitingBlock) 7242 return getCouldNotCompute(); 7243 7244 assert(L->contains(Switch->getDefaultDest()) && 7245 "Default case must not exit the loop!"); 7246 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7247 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7248 7249 // while (X != Y) --> while (X-Y != 0) 7250 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7251 if (EL.hasAnyInfo()) 7252 return EL; 7253 7254 return getCouldNotCompute(); 7255 } 7256 7257 static ConstantInt * 7258 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7259 ScalarEvolution &SE) { 7260 const SCEV *InVal = SE.getConstant(C); 7261 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7262 assert(isa<SCEVConstant>(Val) && 7263 "Evaluation of SCEV at constant didn't fold correctly?"); 7264 return cast<SCEVConstant>(Val)->getValue(); 7265 } 7266 7267 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7268 /// compute the backedge execution count. 7269 ScalarEvolution::ExitLimit 7270 ScalarEvolution::computeLoadConstantCompareExitLimit( 7271 LoadInst *LI, 7272 Constant *RHS, 7273 const Loop *L, 7274 ICmpInst::Predicate predicate) { 7275 if (LI->isVolatile()) return getCouldNotCompute(); 7276 7277 // Check to see if the loaded pointer is a getelementptr of a global. 7278 // TODO: Use SCEV instead of manually grubbing with GEPs. 7279 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7280 if (!GEP) return getCouldNotCompute(); 7281 7282 // Make sure that it is really a constant global we are gepping, with an 7283 // initializer, and make sure the first IDX is really 0. 7284 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7285 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7286 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7287 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7288 return getCouldNotCompute(); 7289 7290 // Okay, we allow one non-constant index into the GEP instruction. 7291 Value *VarIdx = nullptr; 7292 std::vector<Constant*> Indexes; 7293 unsigned VarIdxNum = 0; 7294 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7295 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7296 Indexes.push_back(CI); 7297 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7298 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7299 VarIdx = GEP->getOperand(i); 7300 VarIdxNum = i-2; 7301 Indexes.push_back(nullptr); 7302 } 7303 7304 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7305 if (!VarIdx) 7306 return getCouldNotCompute(); 7307 7308 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7309 // Check to see if X is a loop variant variable value now. 7310 const SCEV *Idx = getSCEV(VarIdx); 7311 Idx = getSCEVAtScope(Idx, L); 7312 7313 // We can only recognize very limited forms of loop index expressions, in 7314 // particular, only affine AddRec's like {C1,+,C2}. 7315 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7316 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7317 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7318 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7319 return getCouldNotCompute(); 7320 7321 unsigned MaxSteps = MaxBruteForceIterations; 7322 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7323 ConstantInt *ItCst = ConstantInt::get( 7324 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7325 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7326 7327 // Form the GEP offset. 7328 Indexes[VarIdxNum] = Val; 7329 7330 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7331 Indexes); 7332 if (!Result) break; // Cannot compute! 7333 7334 // Evaluate the condition for this iteration. 7335 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7336 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7337 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7338 ++NumArrayLenItCounts; 7339 return getConstant(ItCst); // Found terminating iteration! 7340 } 7341 } 7342 return getCouldNotCompute(); 7343 } 7344 7345 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7346 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7347 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7348 if (!RHS) 7349 return getCouldNotCompute(); 7350 7351 const BasicBlock *Latch = L->getLoopLatch(); 7352 if (!Latch) 7353 return getCouldNotCompute(); 7354 7355 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7356 if (!Predecessor) 7357 return getCouldNotCompute(); 7358 7359 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7360 // Return LHS in OutLHS and shift_opt in OutOpCode. 7361 auto MatchPositiveShift = 7362 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7363 7364 using namespace PatternMatch; 7365 7366 ConstantInt *ShiftAmt; 7367 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7368 OutOpCode = Instruction::LShr; 7369 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7370 OutOpCode = Instruction::AShr; 7371 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7372 OutOpCode = Instruction::Shl; 7373 else 7374 return false; 7375 7376 return ShiftAmt->getValue().isStrictlyPositive(); 7377 }; 7378 7379 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7380 // 7381 // loop: 7382 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7383 // %iv.shifted = lshr i32 %iv, <positive constant> 7384 // 7385 // Return true on a successful match. Return the corresponding PHI node (%iv 7386 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7387 auto MatchShiftRecurrence = 7388 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7389 Optional<Instruction::BinaryOps> PostShiftOpCode; 7390 7391 { 7392 Instruction::BinaryOps OpC; 7393 Value *V; 7394 7395 // If we encounter a shift instruction, "peel off" the shift operation, 7396 // and remember that we did so. Later when we inspect %iv's backedge 7397 // value, we will make sure that the backedge value uses the same 7398 // operation. 7399 // 7400 // Note: the peeled shift operation does not have to be the same 7401 // instruction as the one feeding into the PHI's backedge value. We only 7402 // really care about it being the same *kind* of shift instruction -- 7403 // that's all that is required for our later inferences to hold. 7404 if (MatchPositiveShift(LHS, V, OpC)) { 7405 PostShiftOpCode = OpC; 7406 LHS = V; 7407 } 7408 } 7409 7410 PNOut = dyn_cast<PHINode>(LHS); 7411 if (!PNOut || PNOut->getParent() != L->getHeader()) 7412 return false; 7413 7414 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7415 Value *OpLHS; 7416 7417 return 7418 // The backedge value for the PHI node must be a shift by a positive 7419 // amount 7420 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7421 7422 // of the PHI node itself 7423 OpLHS == PNOut && 7424 7425 // and the kind of shift should be match the kind of shift we peeled 7426 // off, if any. 7427 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7428 }; 7429 7430 PHINode *PN; 7431 Instruction::BinaryOps OpCode; 7432 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7433 return getCouldNotCompute(); 7434 7435 const DataLayout &DL = getDataLayout(); 7436 7437 // The key rationale for this optimization is that for some kinds of shift 7438 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7439 // within a finite number of iterations. If the condition guarding the 7440 // backedge (in the sense that the backedge is taken if the condition is true) 7441 // is false for the value the shift recurrence stabilizes to, then we know 7442 // that the backedge is taken only a finite number of times. 7443 7444 ConstantInt *StableValue = nullptr; 7445 switch (OpCode) { 7446 default: 7447 llvm_unreachable("Impossible case!"); 7448 7449 case Instruction::AShr: { 7450 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7451 // bitwidth(K) iterations. 7452 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7453 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7454 Predecessor->getTerminator(), &DT); 7455 auto *Ty = cast<IntegerType>(RHS->getType()); 7456 if (Known.isNonNegative()) 7457 StableValue = ConstantInt::get(Ty, 0); 7458 else if (Known.isNegative()) 7459 StableValue = ConstantInt::get(Ty, -1, true); 7460 else 7461 return getCouldNotCompute(); 7462 7463 break; 7464 } 7465 case Instruction::LShr: 7466 case Instruction::Shl: 7467 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7468 // stabilize to 0 in at most bitwidth(K) iterations. 7469 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7470 break; 7471 } 7472 7473 auto *Result = 7474 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7475 assert(Result->getType()->isIntegerTy(1) && 7476 "Otherwise cannot be an operand to a branch instruction"); 7477 7478 if (Result->isZeroValue()) { 7479 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7480 const SCEV *UpperBound = 7481 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7482 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7483 } 7484 7485 return getCouldNotCompute(); 7486 } 7487 7488 /// Return true if we can constant fold an instruction of the specified type, 7489 /// assuming that all operands were constants. 7490 static bool CanConstantFold(const Instruction *I) { 7491 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7492 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7493 isa<LoadInst>(I)) 7494 return true; 7495 7496 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7497 if (const Function *F = CI->getCalledFunction()) 7498 return canConstantFoldCallTo(CI, F); 7499 return false; 7500 } 7501 7502 /// Determine whether this instruction can constant evolve within this loop 7503 /// assuming its operands can all constant evolve. 7504 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7505 // An instruction outside of the loop can't be derived from a loop PHI. 7506 if (!L->contains(I)) return false; 7507 7508 if (isa<PHINode>(I)) { 7509 // We don't currently keep track of the control flow needed to evaluate 7510 // PHIs, so we cannot handle PHIs inside of loops. 7511 return L->getHeader() == I->getParent(); 7512 } 7513 7514 // If we won't be able to constant fold this expression even if the operands 7515 // are constants, bail early. 7516 return CanConstantFold(I); 7517 } 7518 7519 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7520 /// recursing through each instruction operand until reaching a loop header phi. 7521 static PHINode * 7522 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7523 DenseMap<Instruction *, PHINode *> &PHIMap, 7524 unsigned Depth) { 7525 if (Depth > MaxConstantEvolvingDepth) 7526 return nullptr; 7527 7528 // Otherwise, we can evaluate this instruction if all of its operands are 7529 // constant or derived from a PHI node themselves. 7530 PHINode *PHI = nullptr; 7531 for (Value *Op : UseInst->operands()) { 7532 if (isa<Constant>(Op)) continue; 7533 7534 Instruction *OpInst = dyn_cast<Instruction>(Op); 7535 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7536 7537 PHINode *P = dyn_cast<PHINode>(OpInst); 7538 if (!P) 7539 // If this operand is already visited, reuse the prior result. 7540 // We may have P != PHI if this is the deepest point at which the 7541 // inconsistent paths meet. 7542 P = PHIMap.lookup(OpInst); 7543 if (!P) { 7544 // Recurse and memoize the results, whether a phi is found or not. 7545 // This recursive call invalidates pointers into PHIMap. 7546 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7547 PHIMap[OpInst] = P; 7548 } 7549 if (!P) 7550 return nullptr; // Not evolving from PHI 7551 if (PHI && PHI != P) 7552 return nullptr; // Evolving from multiple different PHIs. 7553 PHI = P; 7554 } 7555 // This is a expression evolving from a constant PHI! 7556 return PHI; 7557 } 7558 7559 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7560 /// in the loop that V is derived from. We allow arbitrary operations along the 7561 /// way, but the operands of an operation must either be constants or a value 7562 /// derived from a constant PHI. If this expression does not fit with these 7563 /// constraints, return null. 7564 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7565 Instruction *I = dyn_cast<Instruction>(V); 7566 if (!I || !canConstantEvolve(I, L)) return nullptr; 7567 7568 if (PHINode *PN = dyn_cast<PHINode>(I)) 7569 return PN; 7570 7571 // Record non-constant instructions contained by the loop. 7572 DenseMap<Instruction *, PHINode *> PHIMap; 7573 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7574 } 7575 7576 /// EvaluateExpression - Given an expression that passes the 7577 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7578 /// in the loop has the value PHIVal. If we can't fold this expression for some 7579 /// reason, return null. 7580 static Constant *EvaluateExpression(Value *V, const Loop *L, 7581 DenseMap<Instruction *, Constant *> &Vals, 7582 const DataLayout &DL, 7583 const TargetLibraryInfo *TLI) { 7584 // Convenient constant check, but redundant for recursive calls. 7585 if (Constant *C = dyn_cast<Constant>(V)) return C; 7586 Instruction *I = dyn_cast<Instruction>(V); 7587 if (!I) return nullptr; 7588 7589 if (Constant *C = Vals.lookup(I)) return C; 7590 7591 // An instruction inside the loop depends on a value outside the loop that we 7592 // weren't given a mapping for, or a value such as a call inside the loop. 7593 if (!canConstantEvolve(I, L)) return nullptr; 7594 7595 // An unmapped PHI can be due to a branch or another loop inside this loop, 7596 // or due to this not being the initial iteration through a loop where we 7597 // couldn't compute the evolution of this particular PHI last time. 7598 if (isa<PHINode>(I)) return nullptr; 7599 7600 std::vector<Constant*> Operands(I->getNumOperands()); 7601 7602 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7603 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7604 if (!Operand) { 7605 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7606 if (!Operands[i]) return nullptr; 7607 continue; 7608 } 7609 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7610 Vals[Operand] = C; 7611 if (!C) return nullptr; 7612 Operands[i] = C; 7613 } 7614 7615 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7616 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7617 Operands[1], DL, TLI); 7618 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7619 if (!LI->isVolatile()) 7620 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7621 } 7622 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7623 } 7624 7625 7626 // If every incoming value to PN except the one for BB is a specific Constant, 7627 // return that, else return nullptr. 7628 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7629 Constant *IncomingVal = nullptr; 7630 7631 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7632 if (PN->getIncomingBlock(i) == BB) 7633 continue; 7634 7635 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7636 if (!CurrentVal) 7637 return nullptr; 7638 7639 if (IncomingVal != CurrentVal) { 7640 if (IncomingVal) 7641 return nullptr; 7642 IncomingVal = CurrentVal; 7643 } 7644 } 7645 7646 return IncomingVal; 7647 } 7648 7649 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7650 /// in the header of its containing loop, we know the loop executes a 7651 /// constant number of times, and the PHI node is just a recurrence 7652 /// involving constants, fold it. 7653 Constant * 7654 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7655 const APInt &BEs, 7656 const Loop *L) { 7657 auto I = ConstantEvolutionLoopExitValue.find(PN); 7658 if (I != ConstantEvolutionLoopExitValue.end()) 7659 return I->second; 7660 7661 if (BEs.ugt(MaxBruteForceIterations)) 7662 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7663 7664 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7665 7666 DenseMap<Instruction *, Constant *> CurrentIterVals; 7667 BasicBlock *Header = L->getHeader(); 7668 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7669 7670 BasicBlock *Latch = L->getLoopLatch(); 7671 if (!Latch) 7672 return nullptr; 7673 7674 for (PHINode &PHI : Header->phis()) { 7675 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7676 CurrentIterVals[&PHI] = StartCST; 7677 } 7678 if (!CurrentIterVals.count(PN)) 7679 return RetVal = nullptr; 7680 7681 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7682 7683 // Execute the loop symbolically to determine the exit value. 7684 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7685 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7686 7687 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7688 unsigned IterationNum = 0; 7689 const DataLayout &DL = getDataLayout(); 7690 for (; ; ++IterationNum) { 7691 if (IterationNum == NumIterations) 7692 return RetVal = CurrentIterVals[PN]; // Got exit value! 7693 7694 // Compute the value of the PHIs for the next iteration. 7695 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7696 DenseMap<Instruction *, Constant *> NextIterVals; 7697 Constant *NextPHI = 7698 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7699 if (!NextPHI) 7700 return nullptr; // Couldn't evaluate! 7701 NextIterVals[PN] = NextPHI; 7702 7703 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7704 7705 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7706 // cease to be able to evaluate one of them or if they stop evolving, 7707 // because that doesn't necessarily prevent us from computing PN. 7708 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7709 for (const auto &I : CurrentIterVals) { 7710 PHINode *PHI = dyn_cast<PHINode>(I.first); 7711 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7712 PHIsToCompute.emplace_back(PHI, I.second); 7713 } 7714 // We use two distinct loops because EvaluateExpression may invalidate any 7715 // iterators into CurrentIterVals. 7716 for (const auto &I : PHIsToCompute) { 7717 PHINode *PHI = I.first; 7718 Constant *&NextPHI = NextIterVals[PHI]; 7719 if (!NextPHI) { // Not already computed. 7720 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7721 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7722 } 7723 if (NextPHI != I.second) 7724 StoppedEvolving = false; 7725 } 7726 7727 // If all entries in CurrentIterVals == NextIterVals then we can stop 7728 // iterating, the loop can't continue to change. 7729 if (StoppedEvolving) 7730 return RetVal = CurrentIterVals[PN]; 7731 7732 CurrentIterVals.swap(NextIterVals); 7733 } 7734 } 7735 7736 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7737 Value *Cond, 7738 bool ExitWhen) { 7739 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7740 if (!PN) return getCouldNotCompute(); 7741 7742 // If the loop is canonicalized, the PHI will have exactly two entries. 7743 // That's the only form we support here. 7744 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7745 7746 DenseMap<Instruction *, Constant *> CurrentIterVals; 7747 BasicBlock *Header = L->getHeader(); 7748 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7749 7750 BasicBlock *Latch = L->getLoopLatch(); 7751 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7752 7753 for (PHINode &PHI : Header->phis()) { 7754 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7755 CurrentIterVals[&PHI] = StartCST; 7756 } 7757 if (!CurrentIterVals.count(PN)) 7758 return getCouldNotCompute(); 7759 7760 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7761 // the loop symbolically to determine when the condition gets a value of 7762 // "ExitWhen". 7763 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7764 const DataLayout &DL = getDataLayout(); 7765 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7766 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7767 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7768 7769 // Couldn't symbolically evaluate. 7770 if (!CondVal) return getCouldNotCompute(); 7771 7772 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7773 ++NumBruteForceTripCountsComputed; 7774 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7775 } 7776 7777 // Update all the PHI nodes for the next iteration. 7778 DenseMap<Instruction *, Constant *> NextIterVals; 7779 7780 // Create a list of which PHIs we need to compute. We want to do this before 7781 // calling EvaluateExpression on them because that may invalidate iterators 7782 // into CurrentIterVals. 7783 SmallVector<PHINode *, 8> PHIsToCompute; 7784 for (const auto &I : CurrentIterVals) { 7785 PHINode *PHI = dyn_cast<PHINode>(I.first); 7786 if (!PHI || PHI->getParent() != Header) continue; 7787 PHIsToCompute.push_back(PHI); 7788 } 7789 for (PHINode *PHI : PHIsToCompute) { 7790 Constant *&NextPHI = NextIterVals[PHI]; 7791 if (NextPHI) continue; // Already computed! 7792 7793 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7794 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7795 } 7796 CurrentIterVals.swap(NextIterVals); 7797 } 7798 7799 // Too many iterations were needed to evaluate. 7800 return getCouldNotCompute(); 7801 } 7802 7803 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 7804 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 7805 ValuesAtScopes[V]; 7806 // Check to see if we've folded this expression at this loop before. 7807 for (auto &LS : Values) 7808 if (LS.first == L) 7809 return LS.second ? LS.second : V; 7810 7811 Values.emplace_back(L, nullptr); 7812 7813 // Otherwise compute it. 7814 const SCEV *C = computeSCEVAtScope(V, L); 7815 for (auto &LS : reverse(ValuesAtScopes[V])) 7816 if (LS.first == L) { 7817 LS.second = C; 7818 break; 7819 } 7820 return C; 7821 } 7822 7823 /// This builds up a Constant using the ConstantExpr interface. That way, we 7824 /// will return Constants for objects which aren't represented by a 7825 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 7826 /// Returns NULL if the SCEV isn't representable as a Constant. 7827 static Constant *BuildConstantFromSCEV(const SCEV *V) { 7828 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 7829 case scCouldNotCompute: 7830 case scAddRecExpr: 7831 break; 7832 case scConstant: 7833 return cast<SCEVConstant>(V)->getValue(); 7834 case scUnknown: 7835 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 7836 case scSignExtend: { 7837 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 7838 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 7839 return ConstantExpr::getSExt(CastOp, SS->getType()); 7840 break; 7841 } 7842 case scZeroExtend: { 7843 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 7844 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 7845 return ConstantExpr::getZExt(CastOp, SZ->getType()); 7846 break; 7847 } 7848 case scTruncate: { 7849 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 7850 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 7851 return ConstantExpr::getTrunc(CastOp, ST->getType()); 7852 break; 7853 } 7854 case scAddExpr: { 7855 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 7856 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 7857 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7858 unsigned AS = PTy->getAddressSpace(); 7859 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7860 C = ConstantExpr::getBitCast(C, DestPtrTy); 7861 } 7862 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 7863 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 7864 if (!C2) return nullptr; 7865 7866 // First pointer! 7867 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 7868 unsigned AS = C2->getType()->getPointerAddressSpace(); 7869 std::swap(C, C2); 7870 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7871 // The offsets have been converted to bytes. We can add bytes to an 7872 // i8* by GEP with the byte count in the first index. 7873 C = ConstantExpr::getBitCast(C, DestPtrTy); 7874 } 7875 7876 // Don't bother trying to sum two pointers. We probably can't 7877 // statically compute a load that results from it anyway. 7878 if (C2->getType()->isPointerTy()) 7879 return nullptr; 7880 7881 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7882 if (PTy->getElementType()->isStructTy()) 7883 C2 = ConstantExpr::getIntegerCast( 7884 C2, Type::getInt32Ty(C->getContext()), true); 7885 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 7886 } else 7887 C = ConstantExpr::getAdd(C, C2); 7888 } 7889 return C; 7890 } 7891 break; 7892 } 7893 case scMulExpr: { 7894 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 7895 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 7896 // Don't bother with pointers at all. 7897 if (C->getType()->isPointerTy()) return nullptr; 7898 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 7899 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 7900 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 7901 C = ConstantExpr::getMul(C, C2); 7902 } 7903 return C; 7904 } 7905 break; 7906 } 7907 case scUDivExpr: { 7908 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 7909 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 7910 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 7911 if (LHS->getType() == RHS->getType()) 7912 return ConstantExpr::getUDiv(LHS, RHS); 7913 break; 7914 } 7915 case scSMaxExpr: 7916 case scUMaxExpr: 7917 break; // TODO: smax, umax. 7918 } 7919 return nullptr; 7920 } 7921 7922 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 7923 if (isa<SCEVConstant>(V)) return V; 7924 7925 // If this instruction is evolved from a constant-evolving PHI, compute the 7926 // exit value from the loop without using SCEVs. 7927 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 7928 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 7929 const Loop *LI = this->LI[I->getParent()]; 7930 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 7931 if (PHINode *PN = dyn_cast<PHINode>(I)) 7932 if (PN->getParent() == LI->getHeader()) { 7933 // Okay, there is no closed form solution for the PHI node. Check 7934 // to see if the loop that contains it has a known backedge-taken 7935 // count. If so, we may be able to force computation of the exit 7936 // value. 7937 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 7938 if (const SCEVConstant *BTCC = 7939 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 7940 7941 // This trivial case can show up in some degenerate cases where 7942 // the incoming IR has not yet been fully simplified. 7943 if (BTCC->getValue()->isZero()) { 7944 Value *InitValue = nullptr; 7945 bool MultipleInitValues = false; 7946 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 7947 if (!LI->contains(PN->getIncomingBlock(i))) { 7948 if (!InitValue) 7949 InitValue = PN->getIncomingValue(i); 7950 else if (InitValue != PN->getIncomingValue(i)) { 7951 MultipleInitValues = true; 7952 break; 7953 } 7954 } 7955 if (!MultipleInitValues && InitValue) 7956 return getSCEV(InitValue); 7957 } 7958 } 7959 // Okay, we know how many times the containing loop executes. If 7960 // this is a constant evolving PHI node, get the final value at 7961 // the specified iteration number. 7962 Constant *RV = 7963 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 7964 if (RV) return getSCEV(RV); 7965 } 7966 } 7967 7968 // Okay, this is an expression that we cannot symbolically evaluate 7969 // into a SCEV. Check to see if it's possible to symbolically evaluate 7970 // the arguments into constants, and if so, try to constant propagate the 7971 // result. This is particularly useful for computing loop exit values. 7972 if (CanConstantFold(I)) { 7973 SmallVector<Constant *, 4> Operands; 7974 bool MadeImprovement = false; 7975 for (Value *Op : I->operands()) { 7976 if (Constant *C = dyn_cast<Constant>(Op)) { 7977 Operands.push_back(C); 7978 continue; 7979 } 7980 7981 // If any of the operands is non-constant and if they are 7982 // non-integer and non-pointer, don't even try to analyze them 7983 // with scev techniques. 7984 if (!isSCEVable(Op->getType())) 7985 return V; 7986 7987 const SCEV *OrigV = getSCEV(Op); 7988 const SCEV *OpV = getSCEVAtScope(OrigV, L); 7989 MadeImprovement |= OrigV != OpV; 7990 7991 Constant *C = BuildConstantFromSCEV(OpV); 7992 if (!C) return V; 7993 if (C->getType() != Op->getType()) 7994 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 7995 Op->getType(), 7996 false), 7997 C, Op->getType()); 7998 Operands.push_back(C); 7999 } 8000 8001 // Check to see if getSCEVAtScope actually made an improvement. 8002 if (MadeImprovement) { 8003 Constant *C = nullptr; 8004 const DataLayout &DL = getDataLayout(); 8005 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8006 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8007 Operands[1], DL, &TLI); 8008 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8009 if (!LI->isVolatile()) 8010 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8011 } else 8012 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8013 if (!C) return V; 8014 return getSCEV(C); 8015 } 8016 } 8017 } 8018 8019 // This is some other type of SCEVUnknown, just return it. 8020 return V; 8021 } 8022 8023 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8024 // Avoid performing the look-up in the common case where the specified 8025 // expression has no loop-variant portions. 8026 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8027 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8028 if (OpAtScope != Comm->getOperand(i)) { 8029 // Okay, at least one of these operands is loop variant but might be 8030 // foldable. Build a new instance of the folded commutative expression. 8031 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8032 Comm->op_begin()+i); 8033 NewOps.push_back(OpAtScope); 8034 8035 for (++i; i != e; ++i) { 8036 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8037 NewOps.push_back(OpAtScope); 8038 } 8039 if (isa<SCEVAddExpr>(Comm)) 8040 return getAddExpr(NewOps); 8041 if (isa<SCEVMulExpr>(Comm)) 8042 return getMulExpr(NewOps); 8043 if (isa<SCEVSMaxExpr>(Comm)) 8044 return getSMaxExpr(NewOps); 8045 if (isa<SCEVUMaxExpr>(Comm)) 8046 return getUMaxExpr(NewOps); 8047 llvm_unreachable("Unknown commutative SCEV type!"); 8048 } 8049 } 8050 // If we got here, all operands are loop invariant. 8051 return Comm; 8052 } 8053 8054 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8055 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8056 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8057 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8058 return Div; // must be loop invariant 8059 return getUDivExpr(LHS, RHS); 8060 } 8061 8062 // If this is a loop recurrence for a loop that does not contain L, then we 8063 // are dealing with the final value computed by the loop. 8064 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8065 // First, attempt to evaluate each operand. 8066 // Avoid performing the look-up in the common case where the specified 8067 // expression has no loop-variant portions. 8068 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8069 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8070 if (OpAtScope == AddRec->getOperand(i)) 8071 continue; 8072 8073 // Okay, at least one of these operands is loop variant but might be 8074 // foldable. Build a new instance of the folded commutative expression. 8075 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8076 AddRec->op_begin()+i); 8077 NewOps.push_back(OpAtScope); 8078 for (++i; i != e; ++i) 8079 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8080 8081 const SCEV *FoldedRec = 8082 getAddRecExpr(NewOps, AddRec->getLoop(), 8083 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8084 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8085 // The addrec may be folded to a nonrecurrence, for example, if the 8086 // induction variable is multiplied by zero after constant folding. Go 8087 // ahead and return the folded value. 8088 if (!AddRec) 8089 return FoldedRec; 8090 break; 8091 } 8092 8093 // If the scope is outside the addrec's loop, evaluate it by using the 8094 // loop exit value of the addrec. 8095 if (!AddRec->getLoop()->contains(L)) { 8096 // To evaluate this recurrence, we need to know how many times the AddRec 8097 // loop iterates. Compute this now. 8098 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8099 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8100 8101 // Then, evaluate the AddRec. 8102 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8103 } 8104 8105 return AddRec; 8106 } 8107 8108 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8109 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8110 if (Op == Cast->getOperand()) 8111 return Cast; // must be loop invariant 8112 return getZeroExtendExpr(Op, Cast->getType()); 8113 } 8114 8115 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8116 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8117 if (Op == Cast->getOperand()) 8118 return Cast; // must be loop invariant 8119 return getSignExtendExpr(Op, Cast->getType()); 8120 } 8121 8122 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8123 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8124 if (Op == Cast->getOperand()) 8125 return Cast; // must be loop invariant 8126 return getTruncateExpr(Op, Cast->getType()); 8127 } 8128 8129 llvm_unreachable("Unknown SCEV type!"); 8130 } 8131 8132 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8133 return getSCEVAtScope(getSCEV(V), L); 8134 } 8135 8136 /// Finds the minimum unsigned root of the following equation: 8137 /// 8138 /// A * X = B (mod N) 8139 /// 8140 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8141 /// A and B isn't important. 8142 /// 8143 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8144 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8145 ScalarEvolution &SE) { 8146 uint32_t BW = A.getBitWidth(); 8147 assert(BW == SE.getTypeSizeInBits(B->getType())); 8148 assert(A != 0 && "A must be non-zero."); 8149 8150 // 1. D = gcd(A, N) 8151 // 8152 // The gcd of A and N may have only one prime factor: 2. The number of 8153 // trailing zeros in A is its multiplicity 8154 uint32_t Mult2 = A.countTrailingZeros(); 8155 // D = 2^Mult2 8156 8157 // 2. Check if B is divisible by D. 8158 // 8159 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8160 // is not less than multiplicity of this prime factor for D. 8161 if (SE.GetMinTrailingZeros(B) < Mult2) 8162 return SE.getCouldNotCompute(); 8163 8164 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8165 // modulo (N / D). 8166 // 8167 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8168 // (N / D) in general. The inverse itself always fits into BW bits, though, 8169 // so we immediately truncate it. 8170 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8171 APInt Mod(BW + 1, 0); 8172 Mod.setBit(BW - Mult2); // Mod = N / D 8173 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8174 8175 // 4. Compute the minimum unsigned root of the equation: 8176 // I * (B / D) mod (N / D) 8177 // To simplify the computation, we factor out the divide by D: 8178 // (I * B mod N) / D 8179 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8180 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8181 } 8182 8183 /// Find the roots of the quadratic equation for the given quadratic chrec 8184 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 8185 /// two SCEVCouldNotCompute objects. 8186 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 8187 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8188 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8189 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8190 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8191 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8192 8193 // We currently can only solve this if the coefficients are constants. 8194 if (!LC || !MC || !NC) 8195 return None; 8196 8197 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 8198 const APInt &L = LC->getAPInt(); 8199 const APInt &M = MC->getAPInt(); 8200 const APInt &N = NC->getAPInt(); 8201 APInt Two(BitWidth, 2); 8202 8203 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 8204 8205 // The A coefficient is N/2 8206 APInt A = N.sdiv(Two); 8207 8208 // The B coefficient is M-N/2 8209 APInt B = M; 8210 B -= A; // A is the same as N/2. 8211 8212 // The C coefficient is L. 8213 const APInt& C = L; 8214 8215 // Compute the B^2-4ac term. 8216 APInt SqrtTerm = B; 8217 SqrtTerm *= B; 8218 SqrtTerm -= 4 * (A * C); 8219 8220 if (SqrtTerm.isNegative()) { 8221 // The loop is provably infinite. 8222 return None; 8223 } 8224 8225 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 8226 // integer value or else APInt::sqrt() will assert. 8227 APInt SqrtVal = SqrtTerm.sqrt(); 8228 8229 // Compute the two solutions for the quadratic formula. 8230 // The divisions must be performed as signed divisions. 8231 APInt NegB = -std::move(B); 8232 APInt TwoA = std::move(A); 8233 TwoA <<= 1; 8234 if (TwoA.isNullValue()) 8235 return None; 8236 8237 LLVMContext &Context = SE.getContext(); 8238 8239 ConstantInt *Solution1 = 8240 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 8241 ConstantInt *Solution2 = 8242 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 8243 8244 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 8245 cast<SCEVConstant>(SE.getConstant(Solution2))); 8246 } 8247 8248 ScalarEvolution::ExitLimit 8249 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8250 bool AllowPredicates) { 8251 8252 // This is only used for loops with a "x != y" exit test. The exit condition 8253 // is now expressed as a single expression, V = x-y. So the exit test is 8254 // effectively V != 0. We know and take advantage of the fact that this 8255 // expression only being used in a comparison by zero context. 8256 8257 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8258 // If the value is a constant 8259 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8260 // If the value is already zero, the branch will execute zero times. 8261 if (C->getValue()->isZero()) return C; 8262 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8263 } 8264 8265 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 8266 if (!AddRec && AllowPredicates) 8267 // Try to make this an AddRec using runtime tests, in the first X 8268 // iterations of this loop, where X is the SCEV expression found by the 8269 // algorithm below. 8270 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8271 8272 if (!AddRec || AddRec->getLoop() != L) 8273 return getCouldNotCompute(); 8274 8275 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8276 // the quadratic equation to solve it. 8277 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8278 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 8279 const SCEVConstant *R1 = Roots->first; 8280 const SCEVConstant *R2 = Roots->second; 8281 // Pick the smallest positive root value. 8282 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 8283 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 8284 if (!CB->getZExtValue()) 8285 std::swap(R1, R2); // R1 is the minimum root now. 8286 8287 // We can only use this value if the chrec ends up with an exact zero 8288 // value at this index. When solving for "X*X != 5", for example, we 8289 // should not accept a root of 2. 8290 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 8291 if (Val->isZero()) 8292 // We found a quadratic root! 8293 return ExitLimit(R1, R1, false, Predicates); 8294 } 8295 } 8296 return getCouldNotCompute(); 8297 } 8298 8299 // Otherwise we can only handle this if it is affine. 8300 if (!AddRec->isAffine()) 8301 return getCouldNotCompute(); 8302 8303 // If this is an affine expression, the execution count of this branch is 8304 // the minimum unsigned root of the following equation: 8305 // 8306 // Start + Step*N = 0 (mod 2^BW) 8307 // 8308 // equivalent to: 8309 // 8310 // Step*N = -Start (mod 2^BW) 8311 // 8312 // where BW is the common bit width of Start and Step. 8313 8314 // Get the initial value for the loop. 8315 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8316 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8317 8318 // For now we handle only constant steps. 8319 // 8320 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8321 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8322 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8323 // We have not yet seen any such cases. 8324 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8325 if (!StepC || StepC->getValue()->isZero()) 8326 return getCouldNotCompute(); 8327 8328 // For positive steps (counting up until unsigned overflow): 8329 // N = -Start/Step (as unsigned) 8330 // For negative steps (counting down to zero): 8331 // N = Start/-Step 8332 // First compute the unsigned distance from zero in the direction of Step. 8333 bool CountDown = StepC->getAPInt().isNegative(); 8334 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8335 8336 // Handle unitary steps, which cannot wraparound. 8337 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8338 // N = Distance (as unsigned) 8339 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8340 APInt MaxBECount = getUnsignedRangeMax(Distance); 8341 8342 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8343 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8344 // case, and see if we can improve the bound. 8345 // 8346 // Explicitly handling this here is necessary because getUnsignedRange 8347 // isn't context-sensitive; it doesn't know that we only care about the 8348 // range inside the loop. 8349 const SCEV *Zero = getZero(Distance->getType()); 8350 const SCEV *One = getOne(Distance->getType()); 8351 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8352 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8353 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8354 // as "unsigned_max(Distance + 1) - 1". 8355 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8356 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8357 } 8358 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8359 } 8360 8361 // If the condition controls loop exit (the loop exits only if the expression 8362 // is true) and the addition is no-wrap we can use unsigned divide to 8363 // compute the backedge count. In this case, the step may not divide the 8364 // distance, but we don't care because if the condition is "missed" the loop 8365 // will have undefined behavior due to wrapping. 8366 if (ControlsExit && AddRec->hasNoSelfWrap() && 8367 loopHasNoAbnormalExits(AddRec->getLoop())) { 8368 const SCEV *Exact = 8369 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8370 const SCEV *Max = 8371 Exact == getCouldNotCompute() 8372 ? Exact 8373 : getConstant(getUnsignedRangeMax(Exact)); 8374 return ExitLimit(Exact, Max, false, Predicates); 8375 } 8376 8377 // Solve the general equation. 8378 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8379 getNegativeSCEV(Start), *this); 8380 const SCEV *M = E == getCouldNotCompute() 8381 ? E 8382 : getConstant(getUnsignedRangeMax(E)); 8383 return ExitLimit(E, M, false, Predicates); 8384 } 8385 8386 ScalarEvolution::ExitLimit 8387 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8388 // Loops that look like: while (X == 0) are very strange indeed. We don't 8389 // handle them yet except for the trivial case. This could be expanded in the 8390 // future as needed. 8391 8392 // If the value is a constant, check to see if it is known to be non-zero 8393 // already. If so, the backedge will execute zero times. 8394 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8395 if (!C->getValue()->isZero()) 8396 return getZero(C->getType()); 8397 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8398 } 8399 8400 // We could implement others, but I really doubt anyone writes loops like 8401 // this, and if they did, they would already be constant folded. 8402 return getCouldNotCompute(); 8403 } 8404 8405 std::pair<BasicBlock *, BasicBlock *> 8406 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8407 // If the block has a unique predecessor, then there is no path from the 8408 // predecessor to the block that does not go through the direct edge 8409 // from the predecessor to the block. 8410 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8411 return {Pred, BB}; 8412 8413 // A loop's header is defined to be a block that dominates the loop. 8414 // If the header has a unique predecessor outside the loop, it must be 8415 // a block that has exactly one successor that can reach the loop. 8416 if (Loop *L = LI.getLoopFor(BB)) 8417 return {L->getLoopPredecessor(), L->getHeader()}; 8418 8419 return {nullptr, nullptr}; 8420 } 8421 8422 /// SCEV structural equivalence is usually sufficient for testing whether two 8423 /// expressions are equal, however for the purposes of looking for a condition 8424 /// guarding a loop, it can be useful to be a little more general, since a 8425 /// front-end may have replicated the controlling expression. 8426 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8427 // Quick check to see if they are the same SCEV. 8428 if (A == B) return true; 8429 8430 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8431 // Not all instructions that are "identical" compute the same value. For 8432 // instance, two distinct alloca instructions allocating the same type are 8433 // identical and do not read memory; but compute distinct values. 8434 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8435 }; 8436 8437 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8438 // two different instructions with the same value. Check for this case. 8439 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8440 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8441 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8442 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8443 if (ComputesEqualValues(AI, BI)) 8444 return true; 8445 8446 // Otherwise assume they may have a different value. 8447 return false; 8448 } 8449 8450 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8451 const SCEV *&LHS, const SCEV *&RHS, 8452 unsigned Depth) { 8453 bool Changed = false; 8454 8455 // If we hit the max recursion limit bail out. 8456 if (Depth >= 3) 8457 return false; 8458 8459 // Canonicalize a constant to the right side. 8460 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8461 // Check for both operands constant. 8462 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8463 if (ConstantExpr::getICmp(Pred, 8464 LHSC->getValue(), 8465 RHSC->getValue())->isNullValue()) 8466 goto trivially_false; 8467 else 8468 goto trivially_true; 8469 } 8470 // Otherwise swap the operands to put the constant on the right. 8471 std::swap(LHS, RHS); 8472 Pred = ICmpInst::getSwappedPredicate(Pred); 8473 Changed = true; 8474 } 8475 8476 // If we're comparing an addrec with a value which is loop-invariant in the 8477 // addrec's loop, put the addrec on the left. Also make a dominance check, 8478 // as both operands could be addrecs loop-invariant in each other's loop. 8479 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8480 const Loop *L = AR->getLoop(); 8481 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8482 std::swap(LHS, RHS); 8483 Pred = ICmpInst::getSwappedPredicate(Pred); 8484 Changed = true; 8485 } 8486 } 8487 8488 // If there's a constant operand, canonicalize comparisons with boundary 8489 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8490 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8491 const APInt &RA = RC->getAPInt(); 8492 8493 bool SimplifiedByConstantRange = false; 8494 8495 if (!ICmpInst::isEquality(Pred)) { 8496 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8497 if (ExactCR.isFullSet()) 8498 goto trivially_true; 8499 else if (ExactCR.isEmptySet()) 8500 goto trivially_false; 8501 8502 APInt NewRHS; 8503 CmpInst::Predicate NewPred; 8504 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8505 ICmpInst::isEquality(NewPred)) { 8506 // We were able to convert an inequality to an equality. 8507 Pred = NewPred; 8508 RHS = getConstant(NewRHS); 8509 Changed = SimplifiedByConstantRange = true; 8510 } 8511 } 8512 8513 if (!SimplifiedByConstantRange) { 8514 switch (Pred) { 8515 default: 8516 break; 8517 case ICmpInst::ICMP_EQ: 8518 case ICmpInst::ICMP_NE: 8519 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8520 if (!RA) 8521 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8522 if (const SCEVMulExpr *ME = 8523 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8524 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8525 ME->getOperand(0)->isAllOnesValue()) { 8526 RHS = AE->getOperand(1); 8527 LHS = ME->getOperand(1); 8528 Changed = true; 8529 } 8530 break; 8531 8532 8533 // The "Should have been caught earlier!" messages refer to the fact 8534 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8535 // should have fired on the corresponding cases, and canonicalized the 8536 // check to trivially_true or trivially_false. 8537 8538 case ICmpInst::ICMP_UGE: 8539 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8540 Pred = ICmpInst::ICMP_UGT; 8541 RHS = getConstant(RA - 1); 8542 Changed = true; 8543 break; 8544 case ICmpInst::ICMP_ULE: 8545 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8546 Pred = ICmpInst::ICMP_ULT; 8547 RHS = getConstant(RA + 1); 8548 Changed = true; 8549 break; 8550 case ICmpInst::ICMP_SGE: 8551 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8552 Pred = ICmpInst::ICMP_SGT; 8553 RHS = getConstant(RA - 1); 8554 Changed = true; 8555 break; 8556 case ICmpInst::ICMP_SLE: 8557 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8558 Pred = ICmpInst::ICMP_SLT; 8559 RHS = getConstant(RA + 1); 8560 Changed = true; 8561 break; 8562 } 8563 } 8564 } 8565 8566 // Check for obvious equality. 8567 if (HasSameValue(LHS, RHS)) { 8568 if (ICmpInst::isTrueWhenEqual(Pred)) 8569 goto trivially_true; 8570 if (ICmpInst::isFalseWhenEqual(Pred)) 8571 goto trivially_false; 8572 } 8573 8574 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8575 // adding or subtracting 1 from one of the operands. 8576 switch (Pred) { 8577 case ICmpInst::ICMP_SLE: 8578 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8579 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8580 SCEV::FlagNSW); 8581 Pred = ICmpInst::ICMP_SLT; 8582 Changed = true; 8583 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8584 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8585 SCEV::FlagNSW); 8586 Pred = ICmpInst::ICMP_SLT; 8587 Changed = true; 8588 } 8589 break; 8590 case ICmpInst::ICMP_SGE: 8591 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 8592 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 8593 SCEV::FlagNSW); 8594 Pred = ICmpInst::ICMP_SGT; 8595 Changed = true; 8596 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 8597 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8598 SCEV::FlagNSW); 8599 Pred = ICmpInst::ICMP_SGT; 8600 Changed = true; 8601 } 8602 break; 8603 case ICmpInst::ICMP_ULE: 8604 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 8605 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8606 SCEV::FlagNUW); 8607 Pred = ICmpInst::ICMP_ULT; 8608 Changed = true; 8609 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 8610 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 8611 Pred = ICmpInst::ICMP_ULT; 8612 Changed = true; 8613 } 8614 break; 8615 case ICmpInst::ICMP_UGE: 8616 if (!getUnsignedRangeMin(RHS).isMinValue()) { 8617 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 8618 Pred = ICmpInst::ICMP_UGT; 8619 Changed = true; 8620 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 8621 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8622 SCEV::FlagNUW); 8623 Pred = ICmpInst::ICMP_UGT; 8624 Changed = true; 8625 } 8626 break; 8627 default: 8628 break; 8629 } 8630 8631 // TODO: More simplifications are possible here. 8632 8633 // Recursively simplify until we either hit a recursion limit or nothing 8634 // changes. 8635 if (Changed) 8636 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 8637 8638 return Changed; 8639 8640 trivially_true: 8641 // Return 0 == 0. 8642 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8643 Pred = ICmpInst::ICMP_EQ; 8644 return true; 8645 8646 trivially_false: 8647 // Return 0 != 0. 8648 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8649 Pred = ICmpInst::ICMP_NE; 8650 return true; 8651 } 8652 8653 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 8654 return getSignedRangeMax(S).isNegative(); 8655 } 8656 8657 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 8658 return getSignedRangeMin(S).isStrictlyPositive(); 8659 } 8660 8661 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 8662 return !getSignedRangeMin(S).isNegative(); 8663 } 8664 8665 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 8666 return !getSignedRangeMax(S).isStrictlyPositive(); 8667 } 8668 8669 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 8670 return isKnownNegative(S) || isKnownPositive(S); 8671 } 8672 8673 std::pair<const SCEV *, const SCEV *> 8674 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 8675 // Compute SCEV on entry of loop L. 8676 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 8677 if (Start == getCouldNotCompute()) 8678 return { Start, Start }; 8679 // Compute post increment SCEV for loop L. 8680 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 8681 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 8682 return { Start, PostInc }; 8683 } 8684 8685 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 8686 const SCEV *LHS, const SCEV *RHS) { 8687 // First collect all loops. 8688 SmallPtrSet<const Loop *, 8> LoopsUsed; 8689 getUsedLoops(LHS, LoopsUsed); 8690 getUsedLoops(RHS, LoopsUsed); 8691 8692 if (LoopsUsed.empty()) 8693 return false; 8694 8695 // Domination relationship must be a linear order on collected loops. 8696 #ifndef NDEBUG 8697 for (auto *L1 : LoopsUsed) 8698 for (auto *L2 : LoopsUsed) 8699 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 8700 DT.dominates(L2->getHeader(), L1->getHeader())) && 8701 "Domination relationship is not a linear order"); 8702 #endif 8703 8704 const Loop *MDL = *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 8705 [&](const Loop *L1, const Loop *L2) { 8706 return DT.dominates(L1->getHeader(), L2->getHeader()); 8707 }); 8708 8709 // Get init and post increment value for LHS. 8710 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 8711 // if LHS contains unknown non-invariant SCEV then bail out. 8712 if (SplitLHS.first == getCouldNotCompute()) 8713 return false; 8714 assert (SplitLHS.first != getCouldNotCompute() && "Unexpected CNC"); 8715 // Get init and post increment value for RHS. 8716 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 8717 // if RHS contains unknown non-invariant SCEV then bail out. 8718 if (SplitRHS.first == getCouldNotCompute()) 8719 return false; 8720 assert (SplitRHS.first != getCouldNotCompute() && "Unexpected CNC"); 8721 // It is possible that init SCEV contains an invariant load but it does 8722 // not dominate MDL and is not available at MDL loop entry, so we should 8723 // check it here. 8724 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 8725 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 8726 return false; 8727 8728 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 8729 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 8730 SplitRHS.second); 8731 } 8732 8733 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 8734 const SCEV *LHS, const SCEV *RHS) { 8735 // Canonicalize the inputs first. 8736 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8737 8738 if (isKnownViaInduction(Pred, LHS, RHS)) 8739 return true; 8740 8741 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 8742 return true; 8743 8744 // Otherwise see what can be done with some simple reasoning. 8745 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 8746 } 8747 8748 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 8749 const SCEVAddRecExpr *LHS, 8750 const SCEV *RHS) { 8751 const Loop *L = LHS->getLoop(); 8752 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 8753 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 8754 } 8755 8756 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 8757 ICmpInst::Predicate Pred, 8758 bool &Increasing) { 8759 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 8760 8761 #ifndef NDEBUG 8762 // Verify an invariant: inverting the predicate should turn a monotonically 8763 // increasing change to a monotonically decreasing one, and vice versa. 8764 bool IncreasingSwapped; 8765 bool ResultSwapped = isMonotonicPredicateImpl( 8766 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 8767 8768 assert(Result == ResultSwapped && "should be able to analyze both!"); 8769 if (ResultSwapped) 8770 assert(Increasing == !IncreasingSwapped && 8771 "monotonicity should flip as we flip the predicate"); 8772 #endif 8773 8774 return Result; 8775 } 8776 8777 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 8778 ICmpInst::Predicate Pred, 8779 bool &Increasing) { 8780 8781 // A zero step value for LHS means the induction variable is essentially a 8782 // loop invariant value. We don't really depend on the predicate actually 8783 // flipping from false to true (for increasing predicates, and the other way 8784 // around for decreasing predicates), all we care about is that *if* the 8785 // predicate changes then it only changes from false to true. 8786 // 8787 // A zero step value in itself is not very useful, but there may be places 8788 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 8789 // as general as possible. 8790 8791 switch (Pred) { 8792 default: 8793 return false; // Conservative answer 8794 8795 case ICmpInst::ICMP_UGT: 8796 case ICmpInst::ICMP_UGE: 8797 case ICmpInst::ICMP_ULT: 8798 case ICmpInst::ICMP_ULE: 8799 if (!LHS->hasNoUnsignedWrap()) 8800 return false; 8801 8802 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 8803 return true; 8804 8805 case ICmpInst::ICMP_SGT: 8806 case ICmpInst::ICMP_SGE: 8807 case ICmpInst::ICMP_SLT: 8808 case ICmpInst::ICMP_SLE: { 8809 if (!LHS->hasNoSignedWrap()) 8810 return false; 8811 8812 const SCEV *Step = LHS->getStepRecurrence(*this); 8813 8814 if (isKnownNonNegative(Step)) { 8815 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 8816 return true; 8817 } 8818 8819 if (isKnownNonPositive(Step)) { 8820 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 8821 return true; 8822 } 8823 8824 return false; 8825 } 8826 8827 } 8828 8829 llvm_unreachable("switch has default clause!"); 8830 } 8831 8832 bool ScalarEvolution::isLoopInvariantPredicate( 8833 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 8834 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 8835 const SCEV *&InvariantRHS) { 8836 8837 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 8838 if (!isLoopInvariant(RHS, L)) { 8839 if (!isLoopInvariant(LHS, L)) 8840 return false; 8841 8842 std::swap(LHS, RHS); 8843 Pred = ICmpInst::getSwappedPredicate(Pred); 8844 } 8845 8846 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8847 if (!ArLHS || ArLHS->getLoop() != L) 8848 return false; 8849 8850 bool Increasing; 8851 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 8852 return false; 8853 8854 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 8855 // true as the loop iterates, and the backedge is control dependent on 8856 // "ArLHS `Pred` RHS" == true then we can reason as follows: 8857 // 8858 // * if the predicate was false in the first iteration then the predicate 8859 // is never evaluated again, since the loop exits without taking the 8860 // backedge. 8861 // * if the predicate was true in the first iteration then it will 8862 // continue to be true for all future iterations since it is 8863 // monotonically increasing. 8864 // 8865 // For both the above possibilities, we can replace the loop varying 8866 // predicate with its value on the first iteration of the loop (which is 8867 // loop invariant). 8868 // 8869 // A similar reasoning applies for a monotonically decreasing predicate, by 8870 // replacing true with false and false with true in the above two bullets. 8871 8872 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 8873 8874 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 8875 return false; 8876 8877 InvariantPred = Pred; 8878 InvariantLHS = ArLHS->getStart(); 8879 InvariantRHS = RHS; 8880 return true; 8881 } 8882 8883 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 8884 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8885 if (HasSameValue(LHS, RHS)) 8886 return ICmpInst::isTrueWhenEqual(Pred); 8887 8888 // This code is split out from isKnownPredicate because it is called from 8889 // within isLoopEntryGuardedByCond. 8890 8891 auto CheckRanges = 8892 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 8893 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 8894 .contains(RangeLHS); 8895 }; 8896 8897 // The check at the top of the function catches the case where the values are 8898 // known to be equal. 8899 if (Pred == CmpInst::ICMP_EQ) 8900 return false; 8901 8902 if (Pred == CmpInst::ICMP_NE) 8903 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 8904 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 8905 isKnownNonZero(getMinusSCEV(LHS, RHS)); 8906 8907 if (CmpInst::isSigned(Pred)) 8908 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 8909 8910 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 8911 } 8912 8913 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 8914 const SCEV *LHS, 8915 const SCEV *RHS) { 8916 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 8917 // Return Y via OutY. 8918 auto MatchBinaryAddToConst = 8919 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 8920 SCEV::NoWrapFlags ExpectedFlags) { 8921 const SCEV *NonConstOp, *ConstOp; 8922 SCEV::NoWrapFlags FlagsPresent; 8923 8924 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 8925 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 8926 return false; 8927 8928 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 8929 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 8930 }; 8931 8932 APInt C; 8933 8934 switch (Pred) { 8935 default: 8936 break; 8937 8938 case ICmpInst::ICMP_SGE: 8939 std::swap(LHS, RHS); 8940 LLVM_FALLTHROUGH; 8941 case ICmpInst::ICMP_SLE: 8942 // X s<= (X + C)<nsw> if C >= 0 8943 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 8944 return true; 8945 8946 // (X + C)<nsw> s<= X if C <= 0 8947 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 8948 !C.isStrictlyPositive()) 8949 return true; 8950 break; 8951 8952 case ICmpInst::ICMP_SGT: 8953 std::swap(LHS, RHS); 8954 LLVM_FALLTHROUGH; 8955 case ICmpInst::ICMP_SLT: 8956 // X s< (X + C)<nsw> if C > 0 8957 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 8958 C.isStrictlyPositive()) 8959 return true; 8960 8961 // (X + C)<nsw> s< X if C < 0 8962 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 8963 return true; 8964 break; 8965 } 8966 8967 return false; 8968 } 8969 8970 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 8971 const SCEV *LHS, 8972 const SCEV *RHS) { 8973 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 8974 return false; 8975 8976 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 8977 // the stack can result in exponential time complexity. 8978 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 8979 8980 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 8981 // 8982 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 8983 // isKnownPredicate. isKnownPredicate is more powerful, but also more 8984 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 8985 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 8986 // use isKnownPredicate later if needed. 8987 return isKnownNonNegative(RHS) && 8988 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 8989 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 8990 } 8991 8992 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 8993 ICmpInst::Predicate Pred, 8994 const SCEV *LHS, const SCEV *RHS) { 8995 // No need to even try if we know the module has no guards. 8996 if (!HasGuards) 8997 return false; 8998 8999 return any_of(*BB, [&](Instruction &I) { 9000 using namespace llvm::PatternMatch; 9001 9002 Value *Condition; 9003 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9004 m_Value(Condition))) && 9005 isImpliedCond(Pred, LHS, RHS, Condition, false); 9006 }); 9007 } 9008 9009 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9010 /// protected by a conditional between LHS and RHS. This is used to 9011 /// to eliminate casts. 9012 bool 9013 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9014 ICmpInst::Predicate Pred, 9015 const SCEV *LHS, const SCEV *RHS) { 9016 // Interpret a null as meaning no loop, where there is obviously no guard 9017 // (interprocedural conditions notwithstanding). 9018 if (!L) return true; 9019 9020 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9021 return true; 9022 9023 BasicBlock *Latch = L->getLoopLatch(); 9024 if (!Latch) 9025 return false; 9026 9027 BranchInst *LoopContinuePredicate = 9028 dyn_cast<BranchInst>(Latch->getTerminator()); 9029 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9030 isImpliedCond(Pred, LHS, RHS, 9031 LoopContinuePredicate->getCondition(), 9032 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9033 return true; 9034 9035 // We don't want more than one activation of the following loops on the stack 9036 // -- that can lead to O(n!) time complexity. 9037 if (WalkingBEDominatingConds) 9038 return false; 9039 9040 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9041 9042 // See if we can exploit a trip count to prove the predicate. 9043 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9044 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9045 if (LatchBECount != getCouldNotCompute()) { 9046 // We know that Latch branches back to the loop header exactly 9047 // LatchBECount times. This means the backdege condition at Latch is 9048 // equivalent to "{0,+,1} u< LatchBECount". 9049 Type *Ty = LatchBECount->getType(); 9050 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9051 const SCEV *LoopCounter = 9052 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9053 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9054 LatchBECount)) 9055 return true; 9056 } 9057 9058 // Check conditions due to any @llvm.assume intrinsics. 9059 for (auto &AssumeVH : AC.assumptions()) { 9060 if (!AssumeVH) 9061 continue; 9062 auto *CI = cast<CallInst>(AssumeVH); 9063 if (!DT.dominates(CI, Latch->getTerminator())) 9064 continue; 9065 9066 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9067 return true; 9068 } 9069 9070 // If the loop is not reachable from the entry block, we risk running into an 9071 // infinite loop as we walk up into the dom tree. These loops do not matter 9072 // anyway, so we just return a conservative answer when we see them. 9073 if (!DT.isReachableFromEntry(L->getHeader())) 9074 return false; 9075 9076 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9077 return true; 9078 9079 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9080 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9081 assert(DTN && "should reach the loop header before reaching the root!"); 9082 9083 BasicBlock *BB = DTN->getBlock(); 9084 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9085 return true; 9086 9087 BasicBlock *PBB = BB->getSinglePredecessor(); 9088 if (!PBB) 9089 continue; 9090 9091 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9092 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9093 continue; 9094 9095 Value *Condition = ContinuePredicate->getCondition(); 9096 9097 // If we have an edge `E` within the loop body that dominates the only 9098 // latch, the condition guarding `E` also guards the backedge. This 9099 // reasoning works only for loops with a single latch. 9100 9101 BasicBlockEdge DominatingEdge(PBB, BB); 9102 if (DominatingEdge.isSingleEdge()) { 9103 // We're constructively (and conservatively) enumerating edges within the 9104 // loop body that dominate the latch. The dominator tree better agree 9105 // with us on this: 9106 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9107 9108 if (isImpliedCond(Pred, LHS, RHS, Condition, 9109 BB != ContinuePredicate->getSuccessor(0))) 9110 return true; 9111 } 9112 } 9113 9114 return false; 9115 } 9116 9117 bool 9118 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9119 ICmpInst::Predicate Pred, 9120 const SCEV *LHS, const SCEV *RHS) { 9121 // Interpret a null as meaning no loop, where there is obviously no guard 9122 // (interprocedural conditions notwithstanding). 9123 if (!L) return false; 9124 9125 // Both LHS and RHS must be available at loop entry. 9126 assert(isAvailableAtLoopEntry(LHS, L) && 9127 "LHS is not available at Loop Entry"); 9128 assert(isAvailableAtLoopEntry(RHS, L) && 9129 "RHS is not available at Loop Entry"); 9130 9131 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9132 return true; 9133 9134 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9135 // the facts (a >= b && a != b) separately. A typical situation is when the 9136 // non-strict comparison is known from ranges and non-equality is known from 9137 // dominating predicates. If we are proving strict comparison, we always try 9138 // to prove non-equality and non-strict comparison separately. 9139 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9140 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9141 bool ProvedNonStrictComparison = false; 9142 bool ProvedNonEquality = false; 9143 9144 if (ProvingStrictComparison) { 9145 ProvedNonStrictComparison = 9146 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9147 ProvedNonEquality = 9148 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9149 if (ProvedNonStrictComparison && ProvedNonEquality) 9150 return true; 9151 } 9152 9153 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9154 auto ProveViaGuard = [&](BasicBlock *Block) { 9155 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9156 return true; 9157 if (ProvingStrictComparison) { 9158 if (!ProvedNonStrictComparison) 9159 ProvedNonStrictComparison = 9160 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9161 if (!ProvedNonEquality) 9162 ProvedNonEquality = 9163 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9164 if (ProvedNonStrictComparison && ProvedNonEquality) 9165 return true; 9166 } 9167 return false; 9168 }; 9169 9170 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9171 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9172 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9173 return true; 9174 if (ProvingStrictComparison) { 9175 if (!ProvedNonStrictComparison) 9176 ProvedNonStrictComparison = 9177 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9178 if (!ProvedNonEquality) 9179 ProvedNonEquality = 9180 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9181 if (ProvedNonStrictComparison && ProvedNonEquality) 9182 return true; 9183 } 9184 return false; 9185 }; 9186 9187 // Starting at the loop predecessor, climb up the predecessor chain, as long 9188 // as there are predecessors that can be found that have unique successors 9189 // leading to the original header. 9190 for (std::pair<BasicBlock *, BasicBlock *> 9191 Pair(L->getLoopPredecessor(), L->getHeader()); 9192 Pair.first; 9193 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9194 9195 if (ProveViaGuard(Pair.first)) 9196 return true; 9197 9198 BranchInst *LoopEntryPredicate = 9199 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9200 if (!LoopEntryPredicate || 9201 LoopEntryPredicate->isUnconditional()) 9202 continue; 9203 9204 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9205 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9206 return true; 9207 } 9208 9209 // Check conditions due to any @llvm.assume intrinsics. 9210 for (auto &AssumeVH : AC.assumptions()) { 9211 if (!AssumeVH) 9212 continue; 9213 auto *CI = cast<CallInst>(AssumeVH); 9214 if (!DT.dominates(CI, L->getHeader())) 9215 continue; 9216 9217 if (ProveViaCond(CI->getArgOperand(0), false)) 9218 return true; 9219 } 9220 9221 return false; 9222 } 9223 9224 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9225 const SCEV *LHS, const SCEV *RHS, 9226 Value *FoundCondValue, 9227 bool Inverse) { 9228 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9229 return false; 9230 9231 auto ClearOnExit = 9232 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9233 9234 // Recursively handle And and Or conditions. 9235 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9236 if (BO->getOpcode() == Instruction::And) { 9237 if (!Inverse) 9238 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9239 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9240 } else if (BO->getOpcode() == Instruction::Or) { 9241 if (Inverse) 9242 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9243 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9244 } 9245 } 9246 9247 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9248 if (!ICI) return false; 9249 9250 // Now that we found a conditional branch that dominates the loop or controls 9251 // the loop latch. Check to see if it is the comparison we are looking for. 9252 ICmpInst::Predicate FoundPred; 9253 if (Inverse) 9254 FoundPred = ICI->getInversePredicate(); 9255 else 9256 FoundPred = ICI->getPredicate(); 9257 9258 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9259 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9260 9261 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9262 } 9263 9264 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9265 const SCEV *RHS, 9266 ICmpInst::Predicate FoundPred, 9267 const SCEV *FoundLHS, 9268 const SCEV *FoundRHS) { 9269 // Balance the types. 9270 if (getTypeSizeInBits(LHS->getType()) < 9271 getTypeSizeInBits(FoundLHS->getType())) { 9272 if (CmpInst::isSigned(Pred)) { 9273 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9274 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9275 } else { 9276 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9277 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9278 } 9279 } else if (getTypeSizeInBits(LHS->getType()) > 9280 getTypeSizeInBits(FoundLHS->getType())) { 9281 if (CmpInst::isSigned(FoundPred)) { 9282 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9283 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9284 } else { 9285 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9286 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9287 } 9288 } 9289 9290 // Canonicalize the query to match the way instcombine will have 9291 // canonicalized the comparison. 9292 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9293 if (LHS == RHS) 9294 return CmpInst::isTrueWhenEqual(Pred); 9295 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9296 if (FoundLHS == FoundRHS) 9297 return CmpInst::isFalseWhenEqual(FoundPred); 9298 9299 // Check to see if we can make the LHS or RHS match. 9300 if (LHS == FoundRHS || RHS == FoundLHS) { 9301 if (isa<SCEVConstant>(RHS)) { 9302 std::swap(FoundLHS, FoundRHS); 9303 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9304 } else { 9305 std::swap(LHS, RHS); 9306 Pred = ICmpInst::getSwappedPredicate(Pred); 9307 } 9308 } 9309 9310 // Check whether the found predicate is the same as the desired predicate. 9311 if (FoundPred == Pred) 9312 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9313 9314 // Check whether swapping the found predicate makes it the same as the 9315 // desired predicate. 9316 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9317 if (isa<SCEVConstant>(RHS)) 9318 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9319 else 9320 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9321 RHS, LHS, FoundLHS, FoundRHS); 9322 } 9323 9324 // Unsigned comparison is the same as signed comparison when both the operands 9325 // are non-negative. 9326 if (CmpInst::isUnsigned(FoundPred) && 9327 CmpInst::getSignedPredicate(FoundPred) == Pred && 9328 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9329 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9330 9331 // Check if we can make progress by sharpening ranges. 9332 if (FoundPred == ICmpInst::ICMP_NE && 9333 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9334 9335 const SCEVConstant *C = nullptr; 9336 const SCEV *V = nullptr; 9337 9338 if (isa<SCEVConstant>(FoundLHS)) { 9339 C = cast<SCEVConstant>(FoundLHS); 9340 V = FoundRHS; 9341 } else { 9342 C = cast<SCEVConstant>(FoundRHS); 9343 V = FoundLHS; 9344 } 9345 9346 // The guarding predicate tells us that C != V. If the known range 9347 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9348 // range we consider has to correspond to same signedness as the 9349 // predicate we're interested in folding. 9350 9351 APInt Min = ICmpInst::isSigned(Pred) ? 9352 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9353 9354 if (Min == C->getAPInt()) { 9355 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9356 // This is true even if (Min + 1) wraps around -- in case of 9357 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9358 9359 APInt SharperMin = Min + 1; 9360 9361 switch (Pred) { 9362 case ICmpInst::ICMP_SGE: 9363 case ICmpInst::ICMP_UGE: 9364 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9365 // RHS, we're done. 9366 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9367 getConstant(SharperMin))) 9368 return true; 9369 LLVM_FALLTHROUGH; 9370 9371 case ICmpInst::ICMP_SGT: 9372 case ICmpInst::ICMP_UGT: 9373 // We know from the range information that (V `Pred` Min || 9374 // V == Min). We know from the guarding condition that !(V 9375 // == Min). This gives us 9376 // 9377 // V `Pred` Min || V == Min && !(V == Min) 9378 // => V `Pred` Min 9379 // 9380 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9381 9382 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9383 return true; 9384 LLVM_FALLTHROUGH; 9385 9386 default: 9387 // No change 9388 break; 9389 } 9390 } 9391 } 9392 9393 // Check whether the actual condition is beyond sufficient. 9394 if (FoundPred == ICmpInst::ICMP_EQ) 9395 if (ICmpInst::isTrueWhenEqual(Pred)) 9396 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9397 return true; 9398 if (Pred == ICmpInst::ICMP_NE) 9399 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9400 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9401 return true; 9402 9403 // Otherwise assume the worst. 9404 return false; 9405 } 9406 9407 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9408 const SCEV *&L, const SCEV *&R, 9409 SCEV::NoWrapFlags &Flags) { 9410 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9411 if (!AE || AE->getNumOperands() != 2) 9412 return false; 9413 9414 L = AE->getOperand(0); 9415 R = AE->getOperand(1); 9416 Flags = AE->getNoWrapFlags(); 9417 return true; 9418 } 9419 9420 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9421 const SCEV *Less) { 9422 // We avoid subtracting expressions here because this function is usually 9423 // fairly deep in the call stack (i.e. is called many times). 9424 9425 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9426 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9427 const auto *MAR = cast<SCEVAddRecExpr>(More); 9428 9429 if (LAR->getLoop() != MAR->getLoop()) 9430 return None; 9431 9432 // We look at affine expressions only; not for correctness but to keep 9433 // getStepRecurrence cheap. 9434 if (!LAR->isAffine() || !MAR->isAffine()) 9435 return None; 9436 9437 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9438 return None; 9439 9440 Less = LAR->getStart(); 9441 More = MAR->getStart(); 9442 9443 // fall through 9444 } 9445 9446 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9447 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9448 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9449 return M - L; 9450 } 9451 9452 const SCEV *L, *R; 9453 SCEV::NoWrapFlags Flags; 9454 if (splitBinaryAdd(Less, L, R, Flags)) 9455 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 9456 if (R == More) 9457 return -(LC->getAPInt()); 9458 9459 if (splitBinaryAdd(More, L, R, Flags)) 9460 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 9461 if (R == Less) 9462 return LC->getAPInt(); 9463 9464 return None; 9465 } 9466 9467 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9468 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9469 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9470 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9471 return false; 9472 9473 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9474 if (!AddRecLHS) 9475 return false; 9476 9477 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9478 if (!AddRecFoundLHS) 9479 return false; 9480 9481 // We'd like to let SCEV reason about control dependencies, so we constrain 9482 // both the inequalities to be about add recurrences on the same loop. This 9483 // way we can use isLoopEntryGuardedByCond later. 9484 9485 const Loop *L = AddRecFoundLHS->getLoop(); 9486 if (L != AddRecLHS->getLoop()) 9487 return false; 9488 9489 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9490 // 9491 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9492 // ... (2) 9493 // 9494 // Informal proof for (2), assuming (1) [*]: 9495 // 9496 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9497 // 9498 // Then 9499 // 9500 // FoundLHS s< FoundRHS s< INT_MIN - C 9501 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9502 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9503 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9504 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9505 // <=> FoundLHS + C s< FoundRHS + C 9506 // 9507 // [*]: (1) can be proved by ruling out overflow. 9508 // 9509 // [**]: This can be proved by analyzing all the four possibilities: 9510 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9511 // (A s>= 0, B s>= 0). 9512 // 9513 // Note: 9514 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9515 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9516 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9517 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9518 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9519 // C)". 9520 9521 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9522 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9523 if (!LDiff || !RDiff || *LDiff != *RDiff) 9524 return false; 9525 9526 if (LDiff->isMinValue()) 9527 return true; 9528 9529 APInt FoundRHSLimit; 9530 9531 if (Pred == CmpInst::ICMP_ULT) { 9532 FoundRHSLimit = -(*RDiff); 9533 } else { 9534 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9535 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9536 } 9537 9538 // Try to prove (1) or (2), as needed. 9539 return isAvailableAtLoopEntry(FoundRHS, L) && 9540 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9541 getConstant(FoundRHSLimit)); 9542 } 9543 9544 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 9545 const SCEV *LHS, const SCEV *RHS, 9546 const SCEV *FoundLHS, 9547 const SCEV *FoundRHS) { 9548 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9549 return true; 9550 9551 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9552 return true; 9553 9554 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 9555 FoundLHS, FoundRHS) || 9556 // ~x < ~y --> x > y 9557 isImpliedCondOperandsHelper(Pred, LHS, RHS, 9558 getNotSCEV(FoundRHS), 9559 getNotSCEV(FoundLHS)); 9560 } 9561 9562 /// If Expr computes ~A, return A else return nullptr 9563 static const SCEV *MatchNotExpr(const SCEV *Expr) { 9564 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 9565 if (!Add || Add->getNumOperands() != 2 || 9566 !Add->getOperand(0)->isAllOnesValue()) 9567 return nullptr; 9568 9569 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 9570 if (!AddRHS || AddRHS->getNumOperands() != 2 || 9571 !AddRHS->getOperand(0)->isAllOnesValue()) 9572 return nullptr; 9573 9574 return AddRHS->getOperand(1); 9575 } 9576 9577 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 9578 template<typename MaxExprType> 9579 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 9580 const SCEV *Candidate) { 9581 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 9582 if (!MaxExpr) return false; 9583 9584 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 9585 } 9586 9587 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 9588 template<typename MaxExprType> 9589 static bool IsMinConsistingOf(ScalarEvolution &SE, 9590 const SCEV *MaybeMinExpr, 9591 const SCEV *Candidate) { 9592 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 9593 if (!MaybeMaxExpr) 9594 return false; 9595 9596 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 9597 } 9598 9599 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 9600 ICmpInst::Predicate Pred, 9601 const SCEV *LHS, const SCEV *RHS) { 9602 // If both sides are affine addrecs for the same loop, with equal 9603 // steps, and we know the recurrences don't wrap, then we only 9604 // need to check the predicate on the starting values. 9605 9606 if (!ICmpInst::isRelational(Pred)) 9607 return false; 9608 9609 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 9610 if (!LAR) 9611 return false; 9612 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 9613 if (!RAR) 9614 return false; 9615 if (LAR->getLoop() != RAR->getLoop()) 9616 return false; 9617 if (!LAR->isAffine() || !RAR->isAffine()) 9618 return false; 9619 9620 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 9621 return false; 9622 9623 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 9624 SCEV::FlagNSW : SCEV::FlagNUW; 9625 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 9626 return false; 9627 9628 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 9629 } 9630 9631 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 9632 /// expression? 9633 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 9634 ICmpInst::Predicate Pred, 9635 const SCEV *LHS, const SCEV *RHS) { 9636 switch (Pred) { 9637 default: 9638 return false; 9639 9640 case ICmpInst::ICMP_SGE: 9641 std::swap(LHS, RHS); 9642 LLVM_FALLTHROUGH; 9643 case ICmpInst::ICMP_SLE: 9644 return 9645 // min(A, ...) <= A 9646 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 9647 // A <= max(A, ...) 9648 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 9649 9650 case ICmpInst::ICMP_UGE: 9651 std::swap(LHS, RHS); 9652 LLVM_FALLTHROUGH; 9653 case ICmpInst::ICMP_ULE: 9654 return 9655 // min(A, ...) <= A 9656 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 9657 // A <= max(A, ...) 9658 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 9659 } 9660 9661 llvm_unreachable("covered switch fell through?!"); 9662 } 9663 9664 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 9665 const SCEV *LHS, const SCEV *RHS, 9666 const SCEV *FoundLHS, 9667 const SCEV *FoundRHS, 9668 unsigned Depth) { 9669 assert(getTypeSizeInBits(LHS->getType()) == 9670 getTypeSizeInBits(RHS->getType()) && 9671 "LHS and RHS have different sizes?"); 9672 assert(getTypeSizeInBits(FoundLHS->getType()) == 9673 getTypeSizeInBits(FoundRHS->getType()) && 9674 "FoundLHS and FoundRHS have different sizes?"); 9675 // We want to avoid hurting the compile time with analysis of too big trees. 9676 if (Depth > MaxSCEVOperationsImplicationDepth) 9677 return false; 9678 // We only want to work with ICMP_SGT comparison so far. 9679 // TODO: Extend to ICMP_UGT? 9680 if (Pred == ICmpInst::ICMP_SLT) { 9681 Pred = ICmpInst::ICMP_SGT; 9682 std::swap(LHS, RHS); 9683 std::swap(FoundLHS, FoundRHS); 9684 } 9685 if (Pred != ICmpInst::ICMP_SGT) 9686 return false; 9687 9688 auto GetOpFromSExt = [&](const SCEV *S) { 9689 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 9690 return Ext->getOperand(); 9691 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 9692 // the constant in some cases. 9693 return S; 9694 }; 9695 9696 // Acquire values from extensions. 9697 auto *OrigFoundLHS = FoundLHS; 9698 LHS = GetOpFromSExt(LHS); 9699 FoundLHS = GetOpFromSExt(FoundLHS); 9700 9701 // Is the SGT predicate can be proved trivially or using the found context. 9702 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 9703 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 9704 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 9705 FoundRHS, Depth + 1); 9706 }; 9707 9708 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 9709 // We want to avoid creation of any new non-constant SCEV. Since we are 9710 // going to compare the operands to RHS, we should be certain that we don't 9711 // need any size extensions for this. So let's decline all cases when the 9712 // sizes of types of LHS and RHS do not match. 9713 // TODO: Maybe try to get RHS from sext to catch more cases? 9714 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 9715 return false; 9716 9717 // Should not overflow. 9718 if (!LHSAddExpr->hasNoSignedWrap()) 9719 return false; 9720 9721 auto *LL = LHSAddExpr->getOperand(0); 9722 auto *LR = LHSAddExpr->getOperand(1); 9723 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 9724 9725 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 9726 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 9727 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 9728 }; 9729 // Try to prove the following rule: 9730 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 9731 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 9732 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 9733 return true; 9734 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 9735 Value *LL, *LR; 9736 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 9737 9738 using namespace llvm::PatternMatch; 9739 9740 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 9741 // Rules for division. 9742 // We are going to perform some comparisons with Denominator and its 9743 // derivative expressions. In general case, creating a SCEV for it may 9744 // lead to a complex analysis of the entire graph, and in particular it 9745 // can request trip count recalculation for the same loop. This would 9746 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 9747 // this, we only want to create SCEVs that are constants in this section. 9748 // So we bail if Denominator is not a constant. 9749 if (!isa<ConstantInt>(LR)) 9750 return false; 9751 9752 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 9753 9754 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 9755 // then a SCEV for the numerator already exists and matches with FoundLHS. 9756 auto *Numerator = getExistingSCEV(LL); 9757 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 9758 return false; 9759 9760 // Make sure that the numerator matches with FoundLHS and the denominator 9761 // is positive. 9762 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 9763 return false; 9764 9765 auto *DTy = Denominator->getType(); 9766 auto *FRHSTy = FoundRHS->getType(); 9767 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 9768 // One of types is a pointer and another one is not. We cannot extend 9769 // them properly to a wider type, so let us just reject this case. 9770 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 9771 // to avoid this check. 9772 return false; 9773 9774 // Given that: 9775 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 9776 auto *WTy = getWiderType(DTy, FRHSTy); 9777 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 9778 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 9779 9780 // Try to prove the following rule: 9781 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 9782 // For example, given that FoundLHS > 2. It means that FoundLHS is at 9783 // least 3. If we divide it by Denominator < 4, we will have at least 1. 9784 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 9785 if (isKnownNonPositive(RHS) && 9786 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 9787 return true; 9788 9789 // Try to prove the following rule: 9790 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 9791 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 9792 // If we divide it by Denominator > 2, then: 9793 // 1. If FoundLHS is negative, then the result is 0. 9794 // 2. If FoundLHS is non-negative, then the result is non-negative. 9795 // Anyways, the result is non-negative. 9796 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 9797 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 9798 if (isKnownNegative(RHS) && 9799 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 9800 return true; 9801 } 9802 } 9803 9804 return false; 9805 } 9806 9807 bool 9808 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 9809 const SCEV *LHS, const SCEV *RHS) { 9810 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 9811 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 9812 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 9813 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 9814 } 9815 9816 bool 9817 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 9818 const SCEV *LHS, const SCEV *RHS, 9819 const SCEV *FoundLHS, 9820 const SCEV *FoundRHS) { 9821 switch (Pred) { 9822 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 9823 case ICmpInst::ICMP_EQ: 9824 case ICmpInst::ICMP_NE: 9825 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 9826 return true; 9827 break; 9828 case ICmpInst::ICMP_SLT: 9829 case ICmpInst::ICMP_SLE: 9830 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 9831 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 9832 return true; 9833 break; 9834 case ICmpInst::ICMP_SGT: 9835 case ICmpInst::ICMP_SGE: 9836 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 9837 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 9838 return true; 9839 break; 9840 case ICmpInst::ICMP_ULT: 9841 case ICmpInst::ICMP_ULE: 9842 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 9843 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 9844 return true; 9845 break; 9846 case ICmpInst::ICMP_UGT: 9847 case ICmpInst::ICMP_UGE: 9848 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 9849 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 9850 return true; 9851 break; 9852 } 9853 9854 // Maybe it can be proved via operations? 9855 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9856 return true; 9857 9858 return false; 9859 } 9860 9861 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 9862 const SCEV *LHS, 9863 const SCEV *RHS, 9864 const SCEV *FoundLHS, 9865 const SCEV *FoundRHS) { 9866 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 9867 // The restriction on `FoundRHS` be lifted easily -- it exists only to 9868 // reduce the compile time impact of this optimization. 9869 return false; 9870 9871 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 9872 if (!Addend) 9873 return false; 9874 9875 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 9876 9877 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 9878 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 9879 ConstantRange FoundLHSRange = 9880 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 9881 9882 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 9883 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 9884 9885 // We can also compute the range of values for `LHS` that satisfy the 9886 // consequent, "`LHS` `Pred` `RHS`": 9887 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 9888 ConstantRange SatisfyingLHSRange = 9889 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 9890 9891 // The antecedent implies the consequent if every value of `LHS` that 9892 // satisfies the antecedent also satisfies the consequent. 9893 return SatisfyingLHSRange.contains(LHSRange); 9894 } 9895 9896 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 9897 bool IsSigned, bool NoWrap) { 9898 assert(isKnownPositive(Stride) && "Positive stride expected!"); 9899 9900 if (NoWrap) return false; 9901 9902 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 9903 const SCEV *One = getOne(Stride->getType()); 9904 9905 if (IsSigned) { 9906 APInt MaxRHS = getSignedRangeMax(RHS); 9907 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 9908 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 9909 9910 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 9911 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 9912 } 9913 9914 APInt MaxRHS = getUnsignedRangeMax(RHS); 9915 APInt MaxValue = APInt::getMaxValue(BitWidth); 9916 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 9917 9918 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 9919 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 9920 } 9921 9922 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 9923 bool IsSigned, bool NoWrap) { 9924 if (NoWrap) return false; 9925 9926 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 9927 const SCEV *One = getOne(Stride->getType()); 9928 9929 if (IsSigned) { 9930 APInt MinRHS = getSignedRangeMin(RHS); 9931 APInt MinValue = APInt::getSignedMinValue(BitWidth); 9932 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 9933 9934 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 9935 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 9936 } 9937 9938 APInt MinRHS = getUnsignedRangeMin(RHS); 9939 APInt MinValue = APInt::getMinValue(BitWidth); 9940 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 9941 9942 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 9943 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 9944 } 9945 9946 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 9947 bool Equality) { 9948 const SCEV *One = getOne(Step->getType()); 9949 Delta = Equality ? getAddExpr(Delta, Step) 9950 : getAddExpr(Delta, getMinusSCEV(Step, One)); 9951 return getUDivExpr(Delta, Step); 9952 } 9953 9954 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 9955 const SCEV *Stride, 9956 const SCEV *End, 9957 unsigned BitWidth, 9958 bool IsSigned) { 9959 9960 assert(!isKnownNonPositive(Stride) && 9961 "Stride is expected strictly positive!"); 9962 // Calculate the maximum backedge count based on the range of values 9963 // permitted by Start, End, and Stride. 9964 const SCEV *MaxBECount; 9965 APInt MinStart = 9966 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 9967 9968 APInt StrideForMaxBECount = 9969 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 9970 9971 // We already know that the stride is positive, so we paper over conservatism 9972 // in our range computation by forcing StrideForMaxBECount to be at least one. 9973 // In theory this is unnecessary, but we expect MaxBECount to be a 9974 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 9975 // is nothing to constant fold it to). 9976 APInt One(BitWidth, 1, IsSigned); 9977 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 9978 9979 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 9980 : APInt::getMaxValue(BitWidth); 9981 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 9982 9983 // Although End can be a MAX expression we estimate MaxEnd considering only 9984 // the case End = RHS of the loop termination condition. This is safe because 9985 // in the other case (End - Start) is zero, leading to a zero maximum backedge 9986 // taken count. 9987 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 9988 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 9989 9990 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 9991 getConstant(StrideForMaxBECount) /* Step */, 9992 false /* Equality */); 9993 9994 return MaxBECount; 9995 } 9996 9997 ScalarEvolution::ExitLimit 9998 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 9999 const Loop *L, bool IsSigned, 10000 bool ControlsExit, bool AllowPredicates) { 10001 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10002 10003 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10004 bool PredicatedIV = false; 10005 10006 if (!IV && AllowPredicates) { 10007 // Try to make this an AddRec using runtime tests, in the first X 10008 // iterations of this loop, where X is the SCEV expression found by the 10009 // algorithm below. 10010 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10011 PredicatedIV = true; 10012 } 10013 10014 // Avoid weird loops 10015 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10016 return getCouldNotCompute(); 10017 10018 bool NoWrap = ControlsExit && 10019 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10020 10021 const SCEV *Stride = IV->getStepRecurrence(*this); 10022 10023 bool PositiveStride = isKnownPositive(Stride); 10024 10025 // Avoid negative or zero stride values. 10026 if (!PositiveStride) { 10027 // We can compute the correct backedge taken count for loops with unknown 10028 // strides if we can prove that the loop is not an infinite loop with side 10029 // effects. Here's the loop structure we are trying to handle - 10030 // 10031 // i = start 10032 // do { 10033 // A[i] = i; 10034 // i += s; 10035 // } while (i < end); 10036 // 10037 // The backedge taken count for such loops is evaluated as - 10038 // (max(end, start + stride) - start - 1) /u stride 10039 // 10040 // The additional preconditions that we need to check to prove correctness 10041 // of the above formula is as follows - 10042 // 10043 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10044 // NoWrap flag). 10045 // b) loop is single exit with no side effects. 10046 // 10047 // 10048 // Precondition a) implies that if the stride is negative, this is a single 10049 // trip loop. The backedge taken count formula reduces to zero in this case. 10050 // 10051 // Precondition b) implies that the unknown stride cannot be zero otherwise 10052 // we have UB. 10053 // 10054 // The positive stride case is the same as isKnownPositive(Stride) returning 10055 // true (original behavior of the function). 10056 // 10057 // We want to make sure that the stride is truly unknown as there are edge 10058 // cases where ScalarEvolution propagates no wrap flags to the 10059 // post-increment/decrement IV even though the increment/decrement operation 10060 // itself is wrapping. The computed backedge taken count may be wrong in 10061 // such cases. This is prevented by checking that the stride is not known to 10062 // be either positive or non-positive. For example, no wrap flags are 10063 // propagated to the post-increment IV of this loop with a trip count of 2 - 10064 // 10065 // unsigned char i; 10066 // for(i=127; i<128; i+=129) 10067 // A[i] = i; 10068 // 10069 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10070 !loopHasNoSideEffects(L)) 10071 return getCouldNotCompute(); 10072 } else if (!Stride->isOne() && 10073 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10074 // Avoid proven overflow cases: this will ensure that the backedge taken 10075 // count will not generate any unsigned overflow. Relaxed no-overflow 10076 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10077 // undefined behaviors like the case of C language. 10078 return getCouldNotCompute(); 10079 10080 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10081 : ICmpInst::ICMP_ULT; 10082 const SCEV *Start = IV->getStart(); 10083 const SCEV *End = RHS; 10084 // When the RHS is not invariant, we do not know the end bound of the loop and 10085 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10086 // calculate the MaxBECount, given the start, stride and max value for the end 10087 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10088 // checked above). 10089 if (!isLoopInvariant(RHS, L)) { 10090 const SCEV *MaxBECount = computeMaxBECountForLT( 10091 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10092 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10093 false /*MaxOrZero*/, Predicates); 10094 } 10095 // If the backedge is taken at least once, then it will be taken 10096 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10097 // is the LHS value of the less-than comparison the first time it is evaluated 10098 // and End is the RHS. 10099 const SCEV *BECountIfBackedgeTaken = 10100 computeBECount(getMinusSCEV(End, Start), Stride, false); 10101 // If the loop entry is guarded by the result of the backedge test of the 10102 // first loop iteration, then we know the backedge will be taken at least 10103 // once and so the backedge taken count is as above. If not then we use the 10104 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10105 // as if the backedge is taken at least once max(End,Start) is End and so the 10106 // result is as above, and if not max(End,Start) is Start so we get a backedge 10107 // count of zero. 10108 const SCEV *BECount; 10109 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10110 BECount = BECountIfBackedgeTaken; 10111 else { 10112 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10113 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10114 } 10115 10116 const SCEV *MaxBECount; 10117 bool MaxOrZero = false; 10118 if (isa<SCEVConstant>(BECount)) 10119 MaxBECount = BECount; 10120 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10121 // If we know exactly how many times the backedge will be taken if it's 10122 // taken at least once, then the backedge count will either be that or 10123 // zero. 10124 MaxBECount = BECountIfBackedgeTaken; 10125 MaxOrZero = true; 10126 } else { 10127 MaxBECount = computeMaxBECountForLT( 10128 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10129 } 10130 10131 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10132 !isa<SCEVCouldNotCompute>(BECount)) 10133 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10134 10135 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10136 } 10137 10138 ScalarEvolution::ExitLimit 10139 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10140 const Loop *L, bool IsSigned, 10141 bool ControlsExit, bool AllowPredicates) { 10142 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10143 // We handle only IV > Invariant 10144 if (!isLoopInvariant(RHS, L)) 10145 return getCouldNotCompute(); 10146 10147 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10148 if (!IV && AllowPredicates) 10149 // Try to make this an AddRec using runtime tests, in the first X 10150 // iterations of this loop, where X is the SCEV expression found by the 10151 // algorithm below. 10152 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10153 10154 // Avoid weird loops 10155 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10156 return getCouldNotCompute(); 10157 10158 bool NoWrap = ControlsExit && 10159 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10160 10161 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10162 10163 // Avoid negative or zero stride values 10164 if (!isKnownPositive(Stride)) 10165 return getCouldNotCompute(); 10166 10167 // Avoid proven overflow cases: this will ensure that the backedge taken count 10168 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10169 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10170 // behaviors like the case of C language. 10171 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10172 return getCouldNotCompute(); 10173 10174 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10175 : ICmpInst::ICMP_UGT; 10176 10177 const SCEV *Start = IV->getStart(); 10178 const SCEV *End = RHS; 10179 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10180 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10181 10182 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10183 10184 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10185 : getUnsignedRangeMax(Start); 10186 10187 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10188 : getUnsignedRangeMin(Stride); 10189 10190 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10191 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10192 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10193 10194 // Although End can be a MIN expression we estimate MinEnd considering only 10195 // the case End = RHS. This is safe because in the other case (Start - End) 10196 // is zero, leading to a zero maximum backedge taken count. 10197 APInt MinEnd = 10198 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10199 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10200 10201 10202 const SCEV *MaxBECount = getCouldNotCompute(); 10203 if (isa<SCEVConstant>(BECount)) 10204 MaxBECount = BECount; 10205 else 10206 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 10207 getConstant(MinStride), false); 10208 10209 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10210 MaxBECount = BECount; 10211 10212 return ExitLimit(BECount, MaxBECount, false, Predicates); 10213 } 10214 10215 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10216 ScalarEvolution &SE) const { 10217 if (Range.isFullSet()) // Infinite loop. 10218 return SE.getCouldNotCompute(); 10219 10220 // If the start is a non-zero constant, shift the range to simplify things. 10221 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10222 if (!SC->getValue()->isZero()) { 10223 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10224 Operands[0] = SE.getZero(SC->getType()); 10225 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10226 getNoWrapFlags(FlagNW)); 10227 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10228 return ShiftedAddRec->getNumIterationsInRange( 10229 Range.subtract(SC->getAPInt()), SE); 10230 // This is strange and shouldn't happen. 10231 return SE.getCouldNotCompute(); 10232 } 10233 10234 // The only time we can solve this is when we have all constant indices. 10235 // Otherwise, we cannot determine the overflow conditions. 10236 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10237 return SE.getCouldNotCompute(); 10238 10239 // Okay at this point we know that all elements of the chrec are constants and 10240 // that the start element is zero. 10241 10242 // First check to see if the range contains zero. If not, the first 10243 // iteration exits. 10244 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10245 if (!Range.contains(APInt(BitWidth, 0))) 10246 return SE.getZero(getType()); 10247 10248 if (isAffine()) { 10249 // If this is an affine expression then we have this situation: 10250 // Solve {0,+,A} in Range === Ax in Range 10251 10252 // We know that zero is in the range. If A is positive then we know that 10253 // the upper value of the range must be the first possible exit value. 10254 // If A is negative then the lower of the range is the last possible loop 10255 // value. Also note that we already checked for a full range. 10256 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10257 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10258 10259 // The exit value should be (End+A)/A. 10260 APInt ExitVal = (End + A).udiv(A); 10261 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10262 10263 // Evaluate at the exit value. If we really did fall out of the valid 10264 // range, then we computed our trip count, otherwise wrap around or other 10265 // things must have happened. 10266 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10267 if (Range.contains(Val->getValue())) 10268 return SE.getCouldNotCompute(); // Something strange happened 10269 10270 // Ensure that the previous value is in the range. This is a sanity check. 10271 assert(Range.contains( 10272 EvaluateConstantChrecAtConstant(this, 10273 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10274 "Linear scev computation is off in a bad way!"); 10275 return SE.getConstant(ExitValue); 10276 } else if (isQuadratic()) { 10277 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 10278 // quadratic equation to solve it. To do this, we must frame our problem in 10279 // terms of figuring out when zero is crossed, instead of when 10280 // Range.getUpper() is crossed. 10281 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 10282 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 10283 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 10284 10285 // Next, solve the constructed addrec 10286 if (auto Roots = 10287 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 10288 const SCEVConstant *R1 = Roots->first; 10289 const SCEVConstant *R2 = Roots->second; 10290 // Pick the smallest positive root value. 10291 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 10292 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 10293 if (!CB->getZExtValue()) 10294 std::swap(R1, R2); // R1 is the minimum root now. 10295 10296 // Make sure the root is not off by one. The returned iteration should 10297 // not be in the range, but the previous one should be. When solving 10298 // for "X*X < 5", for example, we should not return a root of 2. 10299 ConstantInt *R1Val = 10300 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 10301 if (Range.contains(R1Val->getValue())) { 10302 // The next iteration must be out of the range... 10303 ConstantInt *NextVal = 10304 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 10305 10306 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 10307 if (!Range.contains(R1Val->getValue())) 10308 return SE.getConstant(NextVal); 10309 return SE.getCouldNotCompute(); // Something strange happened 10310 } 10311 10312 // If R1 was not in the range, then it is a good return value. Make 10313 // sure that R1-1 WAS in the range though, just in case. 10314 ConstantInt *NextVal = 10315 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 10316 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 10317 if (Range.contains(R1Val->getValue())) 10318 return R1; 10319 return SE.getCouldNotCompute(); // Something strange happened 10320 } 10321 } 10322 } 10323 10324 return SE.getCouldNotCompute(); 10325 } 10326 10327 const SCEVAddRecExpr * 10328 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10329 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10330 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10331 // but in this case we cannot guarantee that the value returned will be an 10332 // AddRec because SCEV does not have a fixed point where it stops 10333 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10334 // may happen if we reach arithmetic depth limit while simplifying. So we 10335 // construct the returned value explicitly. 10336 SmallVector<const SCEV *, 3> Ops; 10337 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10338 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10339 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10340 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10341 // We know that the last operand is not a constant zero (otherwise it would 10342 // have been popped out earlier). This guarantees us that if the result has 10343 // the same last operand, then it will also not be popped out, meaning that 10344 // the returned value will be an AddRec. 10345 const SCEV *Last = getOperand(getNumOperands() - 1); 10346 assert(!Last->isZero() && "Recurrency with zero step?"); 10347 Ops.push_back(Last); 10348 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10349 SCEV::FlagAnyWrap)); 10350 } 10351 10352 // Return true when S contains at least an undef value. 10353 static inline bool containsUndefs(const SCEV *S) { 10354 return SCEVExprContains(S, [](const SCEV *S) { 10355 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10356 return isa<UndefValue>(SU->getValue()); 10357 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 10358 return isa<UndefValue>(SC->getValue()); 10359 return false; 10360 }); 10361 } 10362 10363 namespace { 10364 10365 // Collect all steps of SCEV expressions. 10366 struct SCEVCollectStrides { 10367 ScalarEvolution &SE; 10368 SmallVectorImpl<const SCEV *> &Strides; 10369 10370 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10371 : SE(SE), Strides(S) {} 10372 10373 bool follow(const SCEV *S) { 10374 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10375 Strides.push_back(AR->getStepRecurrence(SE)); 10376 return true; 10377 } 10378 10379 bool isDone() const { return false; } 10380 }; 10381 10382 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10383 struct SCEVCollectTerms { 10384 SmallVectorImpl<const SCEV *> &Terms; 10385 10386 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10387 10388 bool follow(const SCEV *S) { 10389 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10390 isa<SCEVSignExtendExpr>(S)) { 10391 if (!containsUndefs(S)) 10392 Terms.push_back(S); 10393 10394 // Stop recursion: once we collected a term, do not walk its operands. 10395 return false; 10396 } 10397 10398 // Keep looking. 10399 return true; 10400 } 10401 10402 bool isDone() const { return false; } 10403 }; 10404 10405 // Check if a SCEV contains an AddRecExpr. 10406 struct SCEVHasAddRec { 10407 bool &ContainsAddRec; 10408 10409 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10410 ContainsAddRec = false; 10411 } 10412 10413 bool follow(const SCEV *S) { 10414 if (isa<SCEVAddRecExpr>(S)) { 10415 ContainsAddRec = true; 10416 10417 // Stop recursion: once we collected a term, do not walk its operands. 10418 return false; 10419 } 10420 10421 // Keep looking. 10422 return true; 10423 } 10424 10425 bool isDone() const { return false; } 10426 }; 10427 10428 // Find factors that are multiplied with an expression that (possibly as a 10429 // subexpression) contains an AddRecExpr. In the expression: 10430 // 10431 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10432 // 10433 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10434 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10435 // parameters as they form a product with an induction variable. 10436 // 10437 // This collector expects all array size parameters to be in the same MulExpr. 10438 // It might be necessary to later add support for collecting parameters that are 10439 // spread over different nested MulExpr. 10440 struct SCEVCollectAddRecMultiplies { 10441 SmallVectorImpl<const SCEV *> &Terms; 10442 ScalarEvolution &SE; 10443 10444 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10445 : Terms(T), SE(SE) {} 10446 10447 bool follow(const SCEV *S) { 10448 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10449 bool HasAddRec = false; 10450 SmallVector<const SCEV *, 0> Operands; 10451 for (auto Op : Mul->operands()) { 10452 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10453 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10454 Operands.push_back(Op); 10455 } else if (Unknown) { 10456 HasAddRec = true; 10457 } else { 10458 bool ContainsAddRec; 10459 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10460 visitAll(Op, ContiansAddRec); 10461 HasAddRec |= ContainsAddRec; 10462 } 10463 } 10464 if (Operands.size() == 0) 10465 return true; 10466 10467 if (!HasAddRec) 10468 return false; 10469 10470 Terms.push_back(SE.getMulExpr(Operands)); 10471 // Stop recursion: once we collected a term, do not walk its operands. 10472 return false; 10473 } 10474 10475 // Keep looking. 10476 return true; 10477 } 10478 10479 bool isDone() const { return false; } 10480 }; 10481 10482 } // end anonymous namespace 10483 10484 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 10485 /// two places: 10486 /// 1) The strides of AddRec expressions. 10487 /// 2) Unknowns that are multiplied with AddRec expressions. 10488 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 10489 SmallVectorImpl<const SCEV *> &Terms) { 10490 SmallVector<const SCEV *, 4> Strides; 10491 SCEVCollectStrides StrideCollector(*this, Strides); 10492 visitAll(Expr, StrideCollector); 10493 10494 DEBUG({ 10495 dbgs() << "Strides:\n"; 10496 for (const SCEV *S : Strides) 10497 dbgs() << *S << "\n"; 10498 }); 10499 10500 for (const SCEV *S : Strides) { 10501 SCEVCollectTerms TermCollector(Terms); 10502 visitAll(S, TermCollector); 10503 } 10504 10505 DEBUG({ 10506 dbgs() << "Terms:\n"; 10507 for (const SCEV *T : Terms) 10508 dbgs() << *T << "\n"; 10509 }); 10510 10511 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 10512 visitAll(Expr, MulCollector); 10513 } 10514 10515 static bool findArrayDimensionsRec(ScalarEvolution &SE, 10516 SmallVectorImpl<const SCEV *> &Terms, 10517 SmallVectorImpl<const SCEV *> &Sizes) { 10518 int Last = Terms.size() - 1; 10519 const SCEV *Step = Terms[Last]; 10520 10521 // End of recursion. 10522 if (Last == 0) { 10523 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 10524 SmallVector<const SCEV *, 2> Qs; 10525 for (const SCEV *Op : M->operands()) 10526 if (!isa<SCEVConstant>(Op)) 10527 Qs.push_back(Op); 10528 10529 Step = SE.getMulExpr(Qs); 10530 } 10531 10532 Sizes.push_back(Step); 10533 return true; 10534 } 10535 10536 for (const SCEV *&Term : Terms) { 10537 // Normalize the terms before the next call to findArrayDimensionsRec. 10538 const SCEV *Q, *R; 10539 SCEVDivision::divide(SE, Term, Step, &Q, &R); 10540 10541 // Bail out when GCD does not evenly divide one of the terms. 10542 if (!R->isZero()) 10543 return false; 10544 10545 Term = Q; 10546 } 10547 10548 // Remove all SCEVConstants. 10549 Terms.erase( 10550 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 10551 Terms.end()); 10552 10553 if (Terms.size() > 0) 10554 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 10555 return false; 10556 10557 Sizes.push_back(Step); 10558 return true; 10559 } 10560 10561 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 10562 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 10563 for (const SCEV *T : Terms) 10564 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 10565 return true; 10566 return false; 10567 } 10568 10569 // Return the number of product terms in S. 10570 static inline int numberOfTerms(const SCEV *S) { 10571 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 10572 return Expr->getNumOperands(); 10573 return 1; 10574 } 10575 10576 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 10577 if (isa<SCEVConstant>(T)) 10578 return nullptr; 10579 10580 if (isa<SCEVUnknown>(T)) 10581 return T; 10582 10583 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 10584 SmallVector<const SCEV *, 2> Factors; 10585 for (const SCEV *Op : M->operands()) 10586 if (!isa<SCEVConstant>(Op)) 10587 Factors.push_back(Op); 10588 10589 return SE.getMulExpr(Factors); 10590 } 10591 10592 return T; 10593 } 10594 10595 /// Return the size of an element read or written by Inst. 10596 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 10597 Type *Ty; 10598 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 10599 Ty = Store->getValueOperand()->getType(); 10600 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 10601 Ty = Load->getType(); 10602 else 10603 return nullptr; 10604 10605 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 10606 return getSizeOfExpr(ETy, Ty); 10607 } 10608 10609 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 10610 SmallVectorImpl<const SCEV *> &Sizes, 10611 const SCEV *ElementSize) { 10612 if (Terms.size() < 1 || !ElementSize) 10613 return; 10614 10615 // Early return when Terms do not contain parameters: we do not delinearize 10616 // non parametric SCEVs. 10617 if (!containsParameters(Terms)) 10618 return; 10619 10620 DEBUG({ 10621 dbgs() << "Terms:\n"; 10622 for (const SCEV *T : Terms) 10623 dbgs() << *T << "\n"; 10624 }); 10625 10626 // Remove duplicates. 10627 array_pod_sort(Terms.begin(), Terms.end()); 10628 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 10629 10630 // Put larger terms first. 10631 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 10632 return numberOfTerms(LHS) > numberOfTerms(RHS); 10633 }); 10634 10635 // Try to divide all terms by the element size. If term is not divisible by 10636 // element size, proceed with the original term. 10637 for (const SCEV *&Term : Terms) { 10638 const SCEV *Q, *R; 10639 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 10640 if (!Q->isZero()) 10641 Term = Q; 10642 } 10643 10644 SmallVector<const SCEV *, 4> NewTerms; 10645 10646 // Remove constant factors. 10647 for (const SCEV *T : Terms) 10648 if (const SCEV *NewT = removeConstantFactors(*this, T)) 10649 NewTerms.push_back(NewT); 10650 10651 DEBUG({ 10652 dbgs() << "Terms after sorting:\n"; 10653 for (const SCEV *T : NewTerms) 10654 dbgs() << *T << "\n"; 10655 }); 10656 10657 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 10658 Sizes.clear(); 10659 return; 10660 } 10661 10662 // The last element to be pushed into Sizes is the size of an element. 10663 Sizes.push_back(ElementSize); 10664 10665 DEBUG({ 10666 dbgs() << "Sizes:\n"; 10667 for (const SCEV *S : Sizes) 10668 dbgs() << *S << "\n"; 10669 }); 10670 } 10671 10672 void ScalarEvolution::computeAccessFunctions( 10673 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 10674 SmallVectorImpl<const SCEV *> &Sizes) { 10675 // Early exit in case this SCEV is not an affine multivariate function. 10676 if (Sizes.empty()) 10677 return; 10678 10679 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 10680 if (!AR->isAffine()) 10681 return; 10682 10683 const SCEV *Res = Expr; 10684 int Last = Sizes.size() - 1; 10685 for (int i = Last; i >= 0; i--) { 10686 const SCEV *Q, *R; 10687 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 10688 10689 DEBUG({ 10690 dbgs() << "Res: " << *Res << "\n"; 10691 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 10692 dbgs() << "Res divided by Sizes[i]:\n"; 10693 dbgs() << "Quotient: " << *Q << "\n"; 10694 dbgs() << "Remainder: " << *R << "\n"; 10695 }); 10696 10697 Res = Q; 10698 10699 // Do not record the last subscript corresponding to the size of elements in 10700 // the array. 10701 if (i == Last) { 10702 10703 // Bail out if the remainder is too complex. 10704 if (isa<SCEVAddRecExpr>(R)) { 10705 Subscripts.clear(); 10706 Sizes.clear(); 10707 return; 10708 } 10709 10710 continue; 10711 } 10712 10713 // Record the access function for the current subscript. 10714 Subscripts.push_back(R); 10715 } 10716 10717 // Also push in last position the remainder of the last division: it will be 10718 // the access function of the innermost dimension. 10719 Subscripts.push_back(Res); 10720 10721 std::reverse(Subscripts.begin(), Subscripts.end()); 10722 10723 DEBUG({ 10724 dbgs() << "Subscripts:\n"; 10725 for (const SCEV *S : Subscripts) 10726 dbgs() << *S << "\n"; 10727 }); 10728 } 10729 10730 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 10731 /// sizes of an array access. Returns the remainder of the delinearization that 10732 /// is the offset start of the array. The SCEV->delinearize algorithm computes 10733 /// the multiples of SCEV coefficients: that is a pattern matching of sub 10734 /// expressions in the stride and base of a SCEV corresponding to the 10735 /// computation of a GCD (greatest common divisor) of base and stride. When 10736 /// SCEV->delinearize fails, it returns the SCEV unchanged. 10737 /// 10738 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 10739 /// 10740 /// void foo(long n, long m, long o, double A[n][m][o]) { 10741 /// 10742 /// for (long i = 0; i < n; i++) 10743 /// for (long j = 0; j < m; j++) 10744 /// for (long k = 0; k < o; k++) 10745 /// A[i][j][k] = 1.0; 10746 /// } 10747 /// 10748 /// the delinearization input is the following AddRec SCEV: 10749 /// 10750 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 10751 /// 10752 /// From this SCEV, we are able to say that the base offset of the access is %A 10753 /// because it appears as an offset that does not divide any of the strides in 10754 /// the loops: 10755 /// 10756 /// CHECK: Base offset: %A 10757 /// 10758 /// and then SCEV->delinearize determines the size of some of the dimensions of 10759 /// the array as these are the multiples by which the strides are happening: 10760 /// 10761 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 10762 /// 10763 /// Note that the outermost dimension remains of UnknownSize because there are 10764 /// no strides that would help identifying the size of the last dimension: when 10765 /// the array has been statically allocated, one could compute the size of that 10766 /// dimension by dividing the overall size of the array by the size of the known 10767 /// dimensions: %m * %o * 8. 10768 /// 10769 /// Finally delinearize provides the access functions for the array reference 10770 /// that does correspond to A[i][j][k] of the above C testcase: 10771 /// 10772 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 10773 /// 10774 /// The testcases are checking the output of a function pass: 10775 /// DelinearizationPass that walks through all loads and stores of a function 10776 /// asking for the SCEV of the memory access with respect to all enclosing 10777 /// loops, calling SCEV->delinearize on that and printing the results. 10778 void ScalarEvolution::delinearize(const SCEV *Expr, 10779 SmallVectorImpl<const SCEV *> &Subscripts, 10780 SmallVectorImpl<const SCEV *> &Sizes, 10781 const SCEV *ElementSize) { 10782 // First step: collect parametric terms. 10783 SmallVector<const SCEV *, 4> Terms; 10784 collectParametricTerms(Expr, Terms); 10785 10786 if (Terms.empty()) 10787 return; 10788 10789 // Second step: find subscript sizes. 10790 findArrayDimensions(Terms, Sizes, ElementSize); 10791 10792 if (Sizes.empty()) 10793 return; 10794 10795 // Third step: compute the access functions for each subscript. 10796 computeAccessFunctions(Expr, Subscripts, Sizes); 10797 10798 if (Subscripts.empty()) 10799 return; 10800 10801 DEBUG({ 10802 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 10803 dbgs() << "ArrayDecl[UnknownSize]"; 10804 for (const SCEV *S : Sizes) 10805 dbgs() << "[" << *S << "]"; 10806 10807 dbgs() << "\nArrayRef"; 10808 for (const SCEV *S : Subscripts) 10809 dbgs() << "[" << *S << "]"; 10810 dbgs() << "\n"; 10811 }); 10812 } 10813 10814 //===----------------------------------------------------------------------===// 10815 // SCEVCallbackVH Class Implementation 10816 //===----------------------------------------------------------------------===// 10817 10818 void ScalarEvolution::SCEVCallbackVH::deleted() { 10819 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 10820 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 10821 SE->ConstantEvolutionLoopExitValue.erase(PN); 10822 SE->eraseValueFromMap(getValPtr()); 10823 // this now dangles! 10824 } 10825 10826 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 10827 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 10828 10829 // Forget all the expressions associated with users of the old value, 10830 // so that future queries will recompute the expressions using the new 10831 // value. 10832 Value *Old = getValPtr(); 10833 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 10834 SmallPtrSet<User *, 8> Visited; 10835 while (!Worklist.empty()) { 10836 User *U = Worklist.pop_back_val(); 10837 // Deleting the Old value will cause this to dangle. Postpone 10838 // that until everything else is done. 10839 if (U == Old) 10840 continue; 10841 if (!Visited.insert(U).second) 10842 continue; 10843 if (PHINode *PN = dyn_cast<PHINode>(U)) 10844 SE->ConstantEvolutionLoopExitValue.erase(PN); 10845 SE->eraseValueFromMap(U); 10846 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 10847 } 10848 // Delete the Old value. 10849 if (PHINode *PN = dyn_cast<PHINode>(Old)) 10850 SE->ConstantEvolutionLoopExitValue.erase(PN); 10851 SE->eraseValueFromMap(Old); 10852 // this now dangles! 10853 } 10854 10855 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 10856 : CallbackVH(V), SE(se) {} 10857 10858 //===----------------------------------------------------------------------===// 10859 // ScalarEvolution Class Implementation 10860 //===----------------------------------------------------------------------===// 10861 10862 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 10863 AssumptionCache &AC, DominatorTree &DT, 10864 LoopInfo &LI) 10865 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 10866 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 10867 LoopDispositions(64), BlockDispositions(64) { 10868 // To use guards for proving predicates, we need to scan every instruction in 10869 // relevant basic blocks, and not just terminators. Doing this is a waste of 10870 // time if the IR does not actually contain any calls to 10871 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 10872 // 10873 // This pessimizes the case where a pass that preserves ScalarEvolution wants 10874 // to _add_ guards to the module when there weren't any before, and wants 10875 // ScalarEvolution to optimize based on those guards. For now we prefer to be 10876 // efficient in lieu of being smart in that rather obscure case. 10877 10878 auto *GuardDecl = F.getParent()->getFunction( 10879 Intrinsic::getName(Intrinsic::experimental_guard)); 10880 HasGuards = GuardDecl && !GuardDecl->use_empty(); 10881 } 10882 10883 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 10884 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 10885 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 10886 ValueExprMap(std::move(Arg.ValueExprMap)), 10887 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 10888 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 10889 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 10890 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 10891 PredicatedBackedgeTakenCounts( 10892 std::move(Arg.PredicatedBackedgeTakenCounts)), 10893 ConstantEvolutionLoopExitValue( 10894 std::move(Arg.ConstantEvolutionLoopExitValue)), 10895 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 10896 LoopDispositions(std::move(Arg.LoopDispositions)), 10897 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 10898 BlockDispositions(std::move(Arg.BlockDispositions)), 10899 UnsignedRanges(std::move(Arg.UnsignedRanges)), 10900 SignedRanges(std::move(Arg.SignedRanges)), 10901 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 10902 UniquePreds(std::move(Arg.UniquePreds)), 10903 SCEVAllocator(std::move(Arg.SCEVAllocator)), 10904 LoopUsers(std::move(Arg.LoopUsers)), 10905 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 10906 FirstUnknown(Arg.FirstUnknown) { 10907 Arg.FirstUnknown = nullptr; 10908 } 10909 10910 ScalarEvolution::~ScalarEvolution() { 10911 // Iterate through all the SCEVUnknown instances and call their 10912 // destructors, so that they release their references to their values. 10913 for (SCEVUnknown *U = FirstUnknown; U;) { 10914 SCEVUnknown *Tmp = U; 10915 U = U->Next; 10916 Tmp->~SCEVUnknown(); 10917 } 10918 FirstUnknown = nullptr; 10919 10920 ExprValueMap.clear(); 10921 ValueExprMap.clear(); 10922 HasRecMap.clear(); 10923 10924 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 10925 // that a loop had multiple computable exits. 10926 for (auto &BTCI : BackedgeTakenCounts) 10927 BTCI.second.clear(); 10928 for (auto &BTCI : PredicatedBackedgeTakenCounts) 10929 BTCI.second.clear(); 10930 10931 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 10932 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 10933 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 10934 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 10935 } 10936 10937 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 10938 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 10939 } 10940 10941 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 10942 const Loop *L) { 10943 // Print all inner loops first 10944 for (Loop *I : *L) 10945 PrintLoopInfo(OS, SE, I); 10946 10947 OS << "Loop "; 10948 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10949 OS << ": "; 10950 10951 SmallVector<BasicBlock *, 8> ExitBlocks; 10952 L->getExitBlocks(ExitBlocks); 10953 if (ExitBlocks.size() != 1) 10954 OS << "<multiple exits> "; 10955 10956 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 10957 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 10958 } else { 10959 OS << "Unpredictable backedge-taken count. "; 10960 } 10961 10962 OS << "\n" 10963 "Loop "; 10964 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10965 OS << ": "; 10966 10967 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 10968 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 10969 if (SE->isBackedgeTakenCountMaxOrZero(L)) 10970 OS << ", actual taken count either this or zero."; 10971 } else { 10972 OS << "Unpredictable max backedge-taken count. "; 10973 } 10974 10975 OS << "\n" 10976 "Loop "; 10977 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10978 OS << ": "; 10979 10980 SCEVUnionPredicate Pred; 10981 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 10982 if (!isa<SCEVCouldNotCompute>(PBT)) { 10983 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 10984 OS << " Predicates:\n"; 10985 Pred.print(OS, 4); 10986 } else { 10987 OS << "Unpredictable predicated backedge-taken count. "; 10988 } 10989 OS << "\n"; 10990 10991 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 10992 OS << "Loop "; 10993 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10994 OS << ": "; 10995 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 10996 } 10997 } 10998 10999 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11000 switch (LD) { 11001 case ScalarEvolution::LoopVariant: 11002 return "Variant"; 11003 case ScalarEvolution::LoopInvariant: 11004 return "Invariant"; 11005 case ScalarEvolution::LoopComputable: 11006 return "Computable"; 11007 } 11008 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11009 } 11010 11011 void ScalarEvolution::print(raw_ostream &OS) const { 11012 // ScalarEvolution's implementation of the print method is to print 11013 // out SCEV values of all instructions that are interesting. Doing 11014 // this potentially causes it to create new SCEV objects though, 11015 // which technically conflicts with the const qualifier. This isn't 11016 // observable from outside the class though, so casting away the 11017 // const isn't dangerous. 11018 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11019 11020 OS << "Classifying expressions for: "; 11021 F.printAsOperand(OS, /*PrintType=*/false); 11022 OS << "\n"; 11023 for (Instruction &I : instructions(F)) 11024 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11025 OS << I << '\n'; 11026 OS << " --> "; 11027 const SCEV *SV = SE.getSCEV(&I); 11028 SV->print(OS); 11029 if (!isa<SCEVCouldNotCompute>(SV)) { 11030 OS << " U: "; 11031 SE.getUnsignedRange(SV).print(OS); 11032 OS << " S: "; 11033 SE.getSignedRange(SV).print(OS); 11034 } 11035 11036 const Loop *L = LI.getLoopFor(I.getParent()); 11037 11038 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11039 if (AtUse != SV) { 11040 OS << " --> "; 11041 AtUse->print(OS); 11042 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11043 OS << " U: "; 11044 SE.getUnsignedRange(AtUse).print(OS); 11045 OS << " S: "; 11046 SE.getSignedRange(AtUse).print(OS); 11047 } 11048 } 11049 11050 if (L) { 11051 OS << "\t\t" "Exits: "; 11052 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11053 if (!SE.isLoopInvariant(ExitValue, L)) { 11054 OS << "<<Unknown>>"; 11055 } else { 11056 OS << *ExitValue; 11057 } 11058 11059 bool First = true; 11060 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11061 if (First) { 11062 OS << "\t\t" "LoopDispositions: { "; 11063 First = false; 11064 } else { 11065 OS << ", "; 11066 } 11067 11068 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11069 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11070 } 11071 11072 for (auto *InnerL : depth_first(L)) { 11073 if (InnerL == L) 11074 continue; 11075 if (First) { 11076 OS << "\t\t" "LoopDispositions: { "; 11077 First = false; 11078 } else { 11079 OS << ", "; 11080 } 11081 11082 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11083 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11084 } 11085 11086 OS << " }"; 11087 } 11088 11089 OS << "\n"; 11090 } 11091 11092 OS << "Determining loop execution counts for: "; 11093 F.printAsOperand(OS, /*PrintType=*/false); 11094 OS << "\n"; 11095 for (Loop *I : LI) 11096 PrintLoopInfo(OS, &SE, I); 11097 } 11098 11099 ScalarEvolution::LoopDisposition 11100 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11101 auto &Values = LoopDispositions[S]; 11102 for (auto &V : Values) { 11103 if (V.getPointer() == L) 11104 return V.getInt(); 11105 } 11106 Values.emplace_back(L, LoopVariant); 11107 LoopDisposition D = computeLoopDisposition(S, L); 11108 auto &Values2 = LoopDispositions[S]; 11109 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11110 if (V.getPointer() == L) { 11111 V.setInt(D); 11112 break; 11113 } 11114 } 11115 return D; 11116 } 11117 11118 ScalarEvolution::LoopDisposition 11119 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11120 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11121 case scConstant: 11122 return LoopInvariant; 11123 case scTruncate: 11124 case scZeroExtend: 11125 case scSignExtend: 11126 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11127 case scAddRecExpr: { 11128 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11129 11130 // If L is the addrec's loop, it's computable. 11131 if (AR->getLoop() == L) 11132 return LoopComputable; 11133 11134 // Add recurrences are never invariant in the function-body (null loop). 11135 if (!L) 11136 return LoopVariant; 11137 11138 // Everything that is not defined at loop entry is variant. 11139 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11140 return LoopVariant; 11141 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11142 " dominate the contained loop's header?"); 11143 11144 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11145 if (AR->getLoop()->contains(L)) 11146 return LoopInvariant; 11147 11148 // This recurrence is variant w.r.t. L if any of its operands 11149 // are variant. 11150 for (auto *Op : AR->operands()) 11151 if (!isLoopInvariant(Op, L)) 11152 return LoopVariant; 11153 11154 // Otherwise it's loop-invariant. 11155 return LoopInvariant; 11156 } 11157 case scAddExpr: 11158 case scMulExpr: 11159 case scUMaxExpr: 11160 case scSMaxExpr: { 11161 bool HasVarying = false; 11162 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11163 LoopDisposition D = getLoopDisposition(Op, L); 11164 if (D == LoopVariant) 11165 return LoopVariant; 11166 if (D == LoopComputable) 11167 HasVarying = true; 11168 } 11169 return HasVarying ? LoopComputable : LoopInvariant; 11170 } 11171 case scUDivExpr: { 11172 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11173 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11174 if (LD == LoopVariant) 11175 return LoopVariant; 11176 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11177 if (RD == LoopVariant) 11178 return LoopVariant; 11179 return (LD == LoopInvariant && RD == LoopInvariant) ? 11180 LoopInvariant : LoopComputable; 11181 } 11182 case scUnknown: 11183 // All non-instruction values are loop invariant. All instructions are loop 11184 // invariant if they are not contained in the specified loop. 11185 // Instructions are never considered invariant in the function body 11186 // (null loop) because they are defined within the "loop". 11187 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11188 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11189 return LoopInvariant; 11190 case scCouldNotCompute: 11191 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11192 } 11193 llvm_unreachable("Unknown SCEV kind!"); 11194 } 11195 11196 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11197 return getLoopDisposition(S, L) == LoopInvariant; 11198 } 11199 11200 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11201 return getLoopDisposition(S, L) == LoopComputable; 11202 } 11203 11204 ScalarEvolution::BlockDisposition 11205 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11206 auto &Values = BlockDispositions[S]; 11207 for (auto &V : Values) { 11208 if (V.getPointer() == BB) 11209 return V.getInt(); 11210 } 11211 Values.emplace_back(BB, DoesNotDominateBlock); 11212 BlockDisposition D = computeBlockDisposition(S, BB); 11213 auto &Values2 = BlockDispositions[S]; 11214 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11215 if (V.getPointer() == BB) { 11216 V.setInt(D); 11217 break; 11218 } 11219 } 11220 return D; 11221 } 11222 11223 ScalarEvolution::BlockDisposition 11224 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11225 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11226 case scConstant: 11227 return ProperlyDominatesBlock; 11228 case scTruncate: 11229 case scZeroExtend: 11230 case scSignExtend: 11231 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11232 case scAddRecExpr: { 11233 // This uses a "dominates" query instead of "properly dominates" query 11234 // to test for proper dominance too, because the instruction which 11235 // produces the addrec's value is a PHI, and a PHI effectively properly 11236 // dominates its entire containing block. 11237 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11238 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11239 return DoesNotDominateBlock; 11240 11241 // Fall through into SCEVNAryExpr handling. 11242 LLVM_FALLTHROUGH; 11243 } 11244 case scAddExpr: 11245 case scMulExpr: 11246 case scUMaxExpr: 11247 case scSMaxExpr: { 11248 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11249 bool Proper = true; 11250 for (const SCEV *NAryOp : NAry->operands()) { 11251 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11252 if (D == DoesNotDominateBlock) 11253 return DoesNotDominateBlock; 11254 if (D == DominatesBlock) 11255 Proper = false; 11256 } 11257 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11258 } 11259 case scUDivExpr: { 11260 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11261 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11262 BlockDisposition LD = getBlockDisposition(LHS, BB); 11263 if (LD == DoesNotDominateBlock) 11264 return DoesNotDominateBlock; 11265 BlockDisposition RD = getBlockDisposition(RHS, BB); 11266 if (RD == DoesNotDominateBlock) 11267 return DoesNotDominateBlock; 11268 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11269 ProperlyDominatesBlock : DominatesBlock; 11270 } 11271 case scUnknown: 11272 if (Instruction *I = 11273 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11274 if (I->getParent() == BB) 11275 return DominatesBlock; 11276 if (DT.properlyDominates(I->getParent(), BB)) 11277 return ProperlyDominatesBlock; 11278 return DoesNotDominateBlock; 11279 } 11280 return ProperlyDominatesBlock; 11281 case scCouldNotCompute: 11282 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11283 } 11284 llvm_unreachable("Unknown SCEV kind!"); 11285 } 11286 11287 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11288 return getBlockDisposition(S, BB) >= DominatesBlock; 11289 } 11290 11291 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11292 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11293 } 11294 11295 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11296 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11297 } 11298 11299 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11300 auto IsS = [&](const SCEV *X) { return S == X; }; 11301 auto ContainsS = [&](const SCEV *X) { 11302 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11303 }; 11304 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11305 } 11306 11307 void 11308 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11309 ValuesAtScopes.erase(S); 11310 LoopDispositions.erase(S); 11311 BlockDispositions.erase(S); 11312 UnsignedRanges.erase(S); 11313 SignedRanges.erase(S); 11314 ExprValueMap.erase(S); 11315 HasRecMap.erase(S); 11316 MinTrailingZerosCache.erase(S); 11317 11318 for (auto I = PredicatedSCEVRewrites.begin(); 11319 I != PredicatedSCEVRewrites.end();) { 11320 std::pair<const SCEV *, const Loop *> Entry = I->first; 11321 if (Entry.first == S) 11322 PredicatedSCEVRewrites.erase(I++); 11323 else 11324 ++I; 11325 } 11326 11327 auto RemoveSCEVFromBackedgeMap = 11328 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11329 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11330 BackedgeTakenInfo &BEInfo = I->second; 11331 if (BEInfo.hasOperand(S, this)) { 11332 BEInfo.clear(); 11333 Map.erase(I++); 11334 } else 11335 ++I; 11336 } 11337 }; 11338 11339 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11340 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11341 } 11342 11343 void 11344 ScalarEvolution::getUsedLoops(const SCEV *S, 11345 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11346 struct FindUsedLoops { 11347 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11348 : LoopsUsed(LoopsUsed) {} 11349 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11350 bool follow(const SCEV *S) { 11351 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11352 LoopsUsed.insert(AR->getLoop()); 11353 return true; 11354 } 11355 11356 bool isDone() const { return false; } 11357 }; 11358 11359 FindUsedLoops F(LoopsUsed); 11360 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11361 } 11362 11363 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11364 SmallPtrSet<const Loop *, 8> LoopsUsed; 11365 getUsedLoops(S, LoopsUsed); 11366 for (auto *L : LoopsUsed) 11367 LoopUsers[L].push_back(S); 11368 } 11369 11370 void ScalarEvolution::verify() const { 11371 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11372 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11373 11374 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11375 11376 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11377 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11378 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11379 11380 const SCEV *visitConstant(const SCEVConstant *Constant) { 11381 return SE.getConstant(Constant->getAPInt()); 11382 } 11383 11384 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11385 return SE.getUnknown(Expr->getValue()); 11386 } 11387 11388 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11389 return SE.getCouldNotCompute(); 11390 } 11391 }; 11392 11393 SCEVMapper SCM(SE2); 11394 11395 while (!LoopStack.empty()) { 11396 auto *L = LoopStack.pop_back_val(); 11397 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11398 11399 auto *CurBECount = SCM.visit( 11400 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11401 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11402 11403 if (CurBECount == SE2.getCouldNotCompute() || 11404 NewBECount == SE2.getCouldNotCompute()) { 11405 // NB! This situation is legal, but is very suspicious -- whatever pass 11406 // change the loop to make a trip count go from could not compute to 11407 // computable or vice-versa *should have* invalidated SCEV. However, we 11408 // choose not to assert here (for now) since we don't want false 11409 // positives. 11410 continue; 11411 } 11412 11413 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11414 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11415 // not propagate undef aggressively). This means we can (and do) fail 11416 // verification in cases where a transform makes the trip count of a loop 11417 // go from "undef" to "undef+1" (say). The transform is fine, since in 11418 // both cases the loop iterates "undef" times, but SCEV thinks we 11419 // increased the trip count of the loop by 1 incorrectly. 11420 continue; 11421 } 11422 11423 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11424 SE.getTypeSizeInBits(NewBECount->getType())) 11425 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11426 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11427 SE.getTypeSizeInBits(NewBECount->getType())) 11428 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11429 11430 auto *ConstantDelta = 11431 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 11432 11433 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 11434 dbgs() << "Trip Count Changed!\n"; 11435 dbgs() << "Old: " << *CurBECount << "\n"; 11436 dbgs() << "New: " << *NewBECount << "\n"; 11437 dbgs() << "Delta: " << *ConstantDelta << "\n"; 11438 std::abort(); 11439 } 11440 } 11441 } 11442 11443 bool ScalarEvolution::invalidate( 11444 Function &F, const PreservedAnalyses &PA, 11445 FunctionAnalysisManager::Invalidator &Inv) { 11446 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11447 // of its dependencies is invalidated. 11448 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11449 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11450 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11451 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11452 Inv.invalidate<LoopAnalysis>(F, PA); 11453 } 11454 11455 AnalysisKey ScalarEvolutionAnalysis::Key; 11456 11457 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11458 FunctionAnalysisManager &AM) { 11459 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11460 AM.getResult<AssumptionAnalysis>(F), 11461 AM.getResult<DominatorTreeAnalysis>(F), 11462 AM.getResult<LoopAnalysis>(F)); 11463 } 11464 11465 PreservedAnalyses 11466 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11467 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11468 return PreservedAnalyses::all(); 11469 } 11470 11471 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 11472 "Scalar Evolution Analysis", false, true) 11473 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 11474 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 11475 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 11476 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 11477 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 11478 "Scalar Evolution Analysis", false, true) 11479 11480 char ScalarEvolutionWrapperPass::ID = 0; 11481 11482 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 11483 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 11484 } 11485 11486 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 11487 SE.reset(new ScalarEvolution( 11488 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 11489 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 11490 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 11491 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 11492 return false; 11493 } 11494 11495 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 11496 11497 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 11498 SE->print(OS); 11499 } 11500 11501 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 11502 if (!VerifySCEV) 11503 return; 11504 11505 SE->verify(); 11506 } 11507 11508 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 11509 AU.setPreservesAll(); 11510 AU.addRequiredTransitive<AssumptionCacheTracker>(); 11511 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 11512 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 11513 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 11514 } 11515 11516 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 11517 const SCEV *RHS) { 11518 FoldingSetNodeID ID; 11519 assert(LHS->getType() == RHS->getType() && 11520 "Type mismatch between LHS and RHS"); 11521 // Unique this node based on the arguments 11522 ID.AddInteger(SCEVPredicate::P_Equal); 11523 ID.AddPointer(LHS); 11524 ID.AddPointer(RHS); 11525 void *IP = nullptr; 11526 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11527 return S; 11528 SCEVEqualPredicate *Eq = new (SCEVAllocator) 11529 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 11530 UniquePreds.InsertNode(Eq, IP); 11531 return Eq; 11532 } 11533 11534 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 11535 const SCEVAddRecExpr *AR, 11536 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11537 FoldingSetNodeID ID; 11538 // Unique this node based on the arguments 11539 ID.AddInteger(SCEVPredicate::P_Wrap); 11540 ID.AddPointer(AR); 11541 ID.AddInteger(AddedFlags); 11542 void *IP = nullptr; 11543 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11544 return S; 11545 auto *OF = new (SCEVAllocator) 11546 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 11547 UniquePreds.InsertNode(OF, IP); 11548 return OF; 11549 } 11550 11551 namespace { 11552 11553 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 11554 public: 11555 11556 /// Rewrites \p S in the context of a loop L and the SCEV predication 11557 /// infrastructure. 11558 /// 11559 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 11560 /// equivalences present in \p Pred. 11561 /// 11562 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 11563 /// \p NewPreds such that the result will be an AddRecExpr. 11564 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 11565 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11566 SCEVUnionPredicate *Pred) { 11567 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 11568 return Rewriter.visit(S); 11569 } 11570 11571 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11572 if (Pred) { 11573 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 11574 for (auto *Pred : ExprPreds) 11575 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 11576 if (IPred->getLHS() == Expr) 11577 return IPred->getRHS(); 11578 } 11579 return convertToAddRecWithPreds(Expr); 11580 } 11581 11582 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 11583 const SCEV *Operand = visit(Expr->getOperand()); 11584 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11585 if (AR && AR->getLoop() == L && AR->isAffine()) { 11586 // This couldn't be folded because the operand didn't have the nuw 11587 // flag. Add the nusw flag as an assumption that we could make. 11588 const SCEV *Step = AR->getStepRecurrence(SE); 11589 Type *Ty = Expr->getType(); 11590 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 11591 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 11592 SE.getSignExtendExpr(Step, Ty), L, 11593 AR->getNoWrapFlags()); 11594 } 11595 return SE.getZeroExtendExpr(Operand, Expr->getType()); 11596 } 11597 11598 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 11599 const SCEV *Operand = visit(Expr->getOperand()); 11600 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11601 if (AR && AR->getLoop() == L && AR->isAffine()) { 11602 // This couldn't be folded because the operand didn't have the nsw 11603 // flag. Add the nssw flag as an assumption that we could make. 11604 const SCEV *Step = AR->getStepRecurrence(SE); 11605 Type *Ty = Expr->getType(); 11606 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 11607 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 11608 SE.getSignExtendExpr(Step, Ty), L, 11609 AR->getNoWrapFlags()); 11610 } 11611 return SE.getSignExtendExpr(Operand, Expr->getType()); 11612 } 11613 11614 private: 11615 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 11616 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11617 SCEVUnionPredicate *Pred) 11618 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 11619 11620 bool addOverflowAssumption(const SCEVPredicate *P) { 11621 if (!NewPreds) { 11622 // Check if we've already made this assumption. 11623 return Pred && Pred->implies(P); 11624 } 11625 NewPreds->insert(P); 11626 return true; 11627 } 11628 11629 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 11630 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11631 auto *A = SE.getWrapPredicate(AR, AddedFlags); 11632 return addOverflowAssumption(A); 11633 } 11634 11635 // If \p Expr represents a PHINode, we try to see if it can be represented 11636 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 11637 // to add this predicate as a runtime overflow check, we return the AddRec. 11638 // If \p Expr does not meet these conditions (is not a PHI node, or we 11639 // couldn't create an AddRec for it, or couldn't add the predicate), we just 11640 // return \p Expr. 11641 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 11642 if (!isa<PHINode>(Expr->getValue())) 11643 return Expr; 11644 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 11645 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 11646 if (!PredicatedRewrite) 11647 return Expr; 11648 for (auto *P : PredicatedRewrite->second){ 11649 // Wrap predicates from outer loops are not supported. 11650 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 11651 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 11652 if (L != AR->getLoop()) 11653 return Expr; 11654 } 11655 if (!addOverflowAssumption(P)) 11656 return Expr; 11657 } 11658 return PredicatedRewrite->first; 11659 } 11660 11661 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 11662 SCEVUnionPredicate *Pred; 11663 const Loop *L; 11664 }; 11665 11666 } // end anonymous namespace 11667 11668 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 11669 SCEVUnionPredicate &Preds) { 11670 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 11671 } 11672 11673 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 11674 const SCEV *S, const Loop *L, 11675 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 11676 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 11677 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 11678 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 11679 11680 if (!AddRec) 11681 return nullptr; 11682 11683 // Since the transformation was successful, we can now transfer the SCEV 11684 // predicates. 11685 for (auto *P : TransformPreds) 11686 Preds.insert(P); 11687 11688 return AddRec; 11689 } 11690 11691 /// SCEV predicates 11692 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 11693 SCEVPredicateKind Kind) 11694 : FastID(ID), Kind(Kind) {} 11695 11696 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 11697 const SCEV *LHS, const SCEV *RHS) 11698 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 11699 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 11700 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 11701 } 11702 11703 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 11704 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 11705 11706 if (!Op) 11707 return false; 11708 11709 return Op->LHS == LHS && Op->RHS == RHS; 11710 } 11711 11712 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 11713 11714 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 11715 11716 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 11717 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 11718 } 11719 11720 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 11721 const SCEVAddRecExpr *AR, 11722 IncrementWrapFlags Flags) 11723 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 11724 11725 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 11726 11727 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 11728 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 11729 11730 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 11731 } 11732 11733 bool SCEVWrapPredicate::isAlwaysTrue() const { 11734 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 11735 IncrementWrapFlags IFlags = Flags; 11736 11737 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 11738 IFlags = clearFlags(IFlags, IncrementNSSW); 11739 11740 return IFlags == IncrementAnyWrap; 11741 } 11742 11743 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 11744 OS.indent(Depth) << *getExpr() << " Added Flags: "; 11745 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 11746 OS << "<nusw>"; 11747 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 11748 OS << "<nssw>"; 11749 OS << "\n"; 11750 } 11751 11752 SCEVWrapPredicate::IncrementWrapFlags 11753 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 11754 ScalarEvolution &SE) { 11755 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 11756 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 11757 11758 // We can safely transfer the NSW flag as NSSW. 11759 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 11760 ImpliedFlags = IncrementNSSW; 11761 11762 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 11763 // If the increment is positive, the SCEV NUW flag will also imply the 11764 // WrapPredicate NUSW flag. 11765 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 11766 if (Step->getValue()->getValue().isNonNegative()) 11767 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 11768 } 11769 11770 return ImpliedFlags; 11771 } 11772 11773 /// Union predicates don't get cached so create a dummy set ID for it. 11774 SCEVUnionPredicate::SCEVUnionPredicate() 11775 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 11776 11777 bool SCEVUnionPredicate::isAlwaysTrue() const { 11778 return all_of(Preds, 11779 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 11780 } 11781 11782 ArrayRef<const SCEVPredicate *> 11783 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 11784 auto I = SCEVToPreds.find(Expr); 11785 if (I == SCEVToPreds.end()) 11786 return ArrayRef<const SCEVPredicate *>(); 11787 return I->second; 11788 } 11789 11790 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 11791 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 11792 return all_of(Set->Preds, 11793 [this](const SCEVPredicate *I) { return this->implies(I); }); 11794 11795 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 11796 if (ScevPredsIt == SCEVToPreds.end()) 11797 return false; 11798 auto &SCEVPreds = ScevPredsIt->second; 11799 11800 return any_of(SCEVPreds, 11801 [N](const SCEVPredicate *I) { return I->implies(N); }); 11802 } 11803 11804 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 11805 11806 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 11807 for (auto Pred : Preds) 11808 Pred->print(OS, Depth); 11809 } 11810 11811 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 11812 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 11813 for (auto Pred : Set->Preds) 11814 add(Pred); 11815 return; 11816 } 11817 11818 if (implies(N)) 11819 return; 11820 11821 const SCEV *Key = N->getExpr(); 11822 assert(Key && "Only SCEVUnionPredicate doesn't have an " 11823 " associated expression!"); 11824 11825 SCEVToPreds[Key].push_back(N); 11826 Preds.push_back(N); 11827 } 11828 11829 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 11830 Loop &L) 11831 : SE(SE), L(L) {} 11832 11833 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 11834 const SCEV *Expr = SE.getSCEV(V); 11835 RewriteEntry &Entry = RewriteMap[Expr]; 11836 11837 // If we already have an entry and the version matches, return it. 11838 if (Entry.second && Generation == Entry.first) 11839 return Entry.second; 11840 11841 // We found an entry but it's stale. Rewrite the stale entry 11842 // according to the current predicate. 11843 if (Entry.second) 11844 Expr = Entry.second; 11845 11846 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 11847 Entry = {Generation, NewSCEV}; 11848 11849 return NewSCEV; 11850 } 11851 11852 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 11853 if (!BackedgeCount) { 11854 SCEVUnionPredicate BackedgePred; 11855 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 11856 addPredicate(BackedgePred); 11857 } 11858 return BackedgeCount; 11859 } 11860 11861 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 11862 if (Preds.implies(&Pred)) 11863 return; 11864 Preds.add(&Pred); 11865 updateGeneration(); 11866 } 11867 11868 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 11869 return Preds; 11870 } 11871 11872 void PredicatedScalarEvolution::updateGeneration() { 11873 // If the generation number wrapped recompute everything. 11874 if (++Generation == 0) { 11875 for (auto &II : RewriteMap) { 11876 const SCEV *Rewritten = II.second.second; 11877 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 11878 } 11879 } 11880 } 11881 11882 void PredicatedScalarEvolution::setNoOverflow( 11883 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 11884 const SCEV *Expr = getSCEV(V); 11885 const auto *AR = cast<SCEVAddRecExpr>(Expr); 11886 11887 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 11888 11889 // Clear the statically implied flags. 11890 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 11891 addPredicate(*SE.getWrapPredicate(AR, Flags)); 11892 11893 auto II = FlagsMap.insert({V, Flags}); 11894 if (!II.second) 11895 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 11896 } 11897 11898 bool PredicatedScalarEvolution::hasNoOverflow( 11899 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 11900 const SCEV *Expr = getSCEV(V); 11901 const auto *AR = cast<SCEVAddRecExpr>(Expr); 11902 11903 Flags = SCEVWrapPredicate::clearFlags( 11904 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 11905 11906 auto II = FlagsMap.find(V); 11907 11908 if (II != FlagsMap.end()) 11909 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 11910 11911 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 11912 } 11913 11914 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 11915 const SCEV *Expr = this->getSCEV(V); 11916 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 11917 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 11918 11919 if (!New) 11920 return nullptr; 11921 11922 for (auto *P : NewPreds) 11923 Preds.add(P); 11924 11925 updateGeneration(); 11926 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 11927 return New; 11928 } 11929 11930 PredicatedScalarEvolution::PredicatedScalarEvolution( 11931 const PredicatedScalarEvolution &Init) 11932 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 11933 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 11934 for (const auto &I : Init.FlagsMap) 11935 FlagsMap.insert(I); 11936 } 11937 11938 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 11939 // For each block. 11940 for (auto *BB : L.getBlocks()) 11941 for (auto &I : *BB) { 11942 if (!SE.isSCEVable(I.getType())) 11943 continue; 11944 11945 auto *Expr = SE.getSCEV(&I); 11946 auto II = RewriteMap.find(Expr); 11947 11948 if (II == RewriteMap.end()) 11949 continue; 11950 11951 // Don't print things that are not interesting. 11952 if (II->second.second == Expr) 11953 continue; 11954 11955 OS.indent(Depth) << "[PSE]" << I << ":\n"; 11956 OS.indent(Depth + 2) << *Expr << "\n"; 11957 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 11958 } 11959 } 11960