1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution analysis 10 // engine, which is used primarily to analyze expressions involving induction 11 // variables in loops. 12 // 13 // There are several aspects to this library. First is the representation of 14 // scalar expressions, which are represented as subclasses of the SCEV class. 15 // These classes are used to represent certain types of subexpressions that we 16 // can handle. We only create one SCEV of a particular shape, so 17 // pointer-comparisons for equality are legal. 18 // 19 // One important aspect of the SCEV objects is that they are never cyclic, even 20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 22 // recurrence) then we represent it directly as a recurrence node, otherwise we 23 // represent it as a SCEVUnknown node. 24 // 25 // In addition to being able to represent expressions of various types, we also 26 // have folders that are used to build the *canonical* representation for a 27 // particular expression. These folders are capable of using a variety of 28 // rewrite rules to simplify the expressions. 29 // 30 // Once the folders are defined, we can implement the more interesting 31 // higher-level code, such as the code that recognizes PHI nodes of various 32 // types, computes the execution count of a loop, etc. 33 // 34 // TODO: We should use these routines and value representations to implement 35 // dependence analysis! 36 // 37 //===----------------------------------------------------------------------===// 38 // 39 // There are several good references for the techniques used in this analysis. 40 // 41 // Chains of recurrences -- a method to expedite the evaluation 42 // of closed-form functions 43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 44 // 45 // On computational properties of chains of recurrences 46 // Eugene V. Zima 47 // 48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 49 // Robert A. van Engelen 50 // 51 // Efficient Symbolic Analysis for Optimizing Compilers 52 // Robert A. van Engelen 53 // 54 // Using the chains of recurrences algebra for data dependence testing and 55 // induction variable substitution 56 // MS Thesis, Johnie Birch 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 83 #include "llvm/Analysis/TargetLibraryInfo.h" 84 #include "llvm/Analysis/ValueTracking.h" 85 #include "llvm/Config/llvm-config.h" 86 #include "llvm/IR/Argument.h" 87 #include "llvm/IR/BasicBlock.h" 88 #include "llvm/IR/CFG.h" 89 #include "llvm/IR/CallSite.h" 90 #include "llvm/IR/Constant.h" 91 #include "llvm/IR/ConstantRange.h" 92 #include "llvm/IR/Constants.h" 93 #include "llvm/IR/DataLayout.h" 94 #include "llvm/IR/DerivedTypes.h" 95 #include "llvm/IR/Dominators.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/GlobalAlias.h" 98 #include "llvm/IR/GlobalValue.h" 99 #include "llvm/IR/GlobalVariable.h" 100 #include "llvm/IR/InstIterator.h" 101 #include "llvm/IR/InstrTypes.h" 102 #include "llvm/IR/Instruction.h" 103 #include "llvm/IR/Instructions.h" 104 #include "llvm/IR/IntrinsicInst.h" 105 #include "llvm/IR/Intrinsics.h" 106 #include "llvm/IR/LLVMContext.h" 107 #include "llvm/IR/Metadata.h" 108 #include "llvm/IR/Operator.h" 109 #include "llvm/IR/PatternMatch.h" 110 #include "llvm/IR/Type.h" 111 #include "llvm/IR/Use.h" 112 #include "llvm/IR/User.h" 113 #include "llvm/IR/Value.h" 114 #include "llvm/IR/Verifier.h" 115 #include "llvm/Pass.h" 116 #include "llvm/Support/Casting.h" 117 #include "llvm/Support/CommandLine.h" 118 #include "llvm/Support/Compiler.h" 119 #include "llvm/Support/Debug.h" 120 #include "llvm/Support/ErrorHandling.h" 121 #include "llvm/Support/KnownBits.h" 122 #include "llvm/Support/SaveAndRestore.h" 123 #include "llvm/Support/raw_ostream.h" 124 #include <algorithm> 125 #include <cassert> 126 #include <climits> 127 #include <cstddef> 128 #include <cstdint> 129 #include <cstdlib> 130 #include <map> 131 #include <memory> 132 #include <tuple> 133 #include <utility> 134 #include <vector> 135 136 using namespace llvm; 137 138 #define DEBUG_TYPE "scalar-evolution" 139 140 STATISTIC(NumArrayLenItCounts, 141 "Number of trip counts computed with array length"); 142 STATISTIC(NumTripCountsComputed, 143 "Number of loops with predictable loop counts"); 144 STATISTIC(NumTripCountsNotComputed, 145 "Number of loops without predictable loop counts"); 146 STATISTIC(NumBruteForceTripCountsComputed, 147 "Number of loops with trip counts computed by force"); 148 149 static cl::opt<unsigned> 150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 151 cl::desc("Maximum number of iterations SCEV will " 152 "symbolically execute a constant " 153 "derived loop"), 154 cl::init(100)); 155 156 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 157 static cl::opt<bool> VerifySCEV( 158 "verify-scev", cl::Hidden, 159 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 160 static cl::opt<bool> 161 VerifySCEVMap("verify-scev-maps", cl::Hidden, 162 cl::desc("Verify no dangling value in ScalarEvolution's " 163 "ExprValueMap (slow)")); 164 165 static cl::opt<bool> VerifyIR( 166 "scev-verify-ir", cl::Hidden, 167 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 168 cl::init(false)); 169 170 static cl::opt<unsigned> MulOpsInlineThreshold( 171 "scev-mulops-inline-threshold", cl::Hidden, 172 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 173 cl::init(32)); 174 175 static cl::opt<unsigned> AddOpsInlineThreshold( 176 "scev-addops-inline-threshold", cl::Hidden, 177 cl::desc("Threshold for inlining addition operands into a SCEV"), 178 cl::init(500)); 179 180 static cl::opt<unsigned> MaxSCEVCompareDepth( 181 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 182 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 183 cl::init(32)); 184 185 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 186 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 187 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 188 cl::init(2)); 189 190 static cl::opt<unsigned> MaxValueCompareDepth( 191 "scalar-evolution-max-value-compare-depth", cl::Hidden, 192 cl::desc("Maximum depth of recursive value complexity comparisons"), 193 cl::init(2)); 194 195 static cl::opt<unsigned> 196 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 197 cl::desc("Maximum depth of recursive arithmetics"), 198 cl::init(32)); 199 200 static cl::opt<unsigned> MaxConstantEvolvingDepth( 201 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 202 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 203 204 static cl::opt<unsigned> 205 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 206 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 207 cl::init(8)); 208 209 static cl::opt<unsigned> 210 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 211 cl::desc("Max coefficients in AddRec during evolving"), 212 cl::init(8)); 213 214 static cl::opt<unsigned> 215 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 216 cl::desc("Size of the expression which is considered huge"), 217 cl::init(4096)); 218 219 //===----------------------------------------------------------------------===// 220 // SCEV class definitions 221 //===----------------------------------------------------------------------===// 222 223 //===----------------------------------------------------------------------===// 224 // Implementation of the SCEV class. 225 // 226 227 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 228 LLVM_DUMP_METHOD void SCEV::dump() const { 229 print(dbgs()); 230 dbgs() << '\n'; 231 } 232 #endif 233 234 void SCEV::print(raw_ostream &OS) const { 235 switch (static_cast<SCEVTypes>(getSCEVType())) { 236 case scConstant: 237 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 238 return; 239 case scTruncate: { 240 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 241 const SCEV *Op = Trunc->getOperand(); 242 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 243 << *Trunc->getType() << ")"; 244 return; 245 } 246 case scZeroExtend: { 247 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 248 const SCEV *Op = ZExt->getOperand(); 249 OS << "(zext " << *Op->getType() << " " << *Op << " to " 250 << *ZExt->getType() << ")"; 251 return; 252 } 253 case scSignExtend: { 254 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 255 const SCEV *Op = SExt->getOperand(); 256 OS << "(sext " << *Op->getType() << " " << *Op << " to " 257 << *SExt->getType() << ")"; 258 return; 259 } 260 case scAddRecExpr: { 261 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 262 OS << "{" << *AR->getOperand(0); 263 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 264 OS << ",+," << *AR->getOperand(i); 265 OS << "}<"; 266 if (AR->hasNoUnsignedWrap()) 267 OS << "nuw><"; 268 if (AR->hasNoSignedWrap()) 269 OS << "nsw><"; 270 if (AR->hasNoSelfWrap() && 271 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 272 OS << "nw><"; 273 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 274 OS << ">"; 275 return; 276 } 277 case scAddExpr: 278 case scMulExpr: 279 case scUMaxExpr: 280 case scSMaxExpr: { 281 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 282 const char *OpStr = nullptr; 283 switch (NAry->getSCEVType()) { 284 case scAddExpr: OpStr = " + "; break; 285 case scMulExpr: OpStr = " * "; break; 286 case scUMaxExpr: OpStr = " umax "; break; 287 case scSMaxExpr: OpStr = " smax "; break; 288 } 289 OS << "("; 290 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 291 I != E; ++I) { 292 OS << **I; 293 if (std::next(I) != E) 294 OS << OpStr; 295 } 296 OS << ")"; 297 switch (NAry->getSCEVType()) { 298 case scAddExpr: 299 case scMulExpr: 300 if (NAry->hasNoUnsignedWrap()) 301 OS << "<nuw>"; 302 if (NAry->hasNoSignedWrap()) 303 OS << "<nsw>"; 304 } 305 return; 306 } 307 case scUDivExpr: { 308 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 309 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 310 return; 311 } 312 case scUnknown: { 313 const SCEVUnknown *U = cast<SCEVUnknown>(this); 314 Type *AllocTy; 315 if (U->isSizeOf(AllocTy)) { 316 OS << "sizeof(" << *AllocTy << ")"; 317 return; 318 } 319 if (U->isAlignOf(AllocTy)) { 320 OS << "alignof(" << *AllocTy << ")"; 321 return; 322 } 323 324 Type *CTy; 325 Constant *FieldNo; 326 if (U->isOffsetOf(CTy, FieldNo)) { 327 OS << "offsetof(" << *CTy << ", "; 328 FieldNo->printAsOperand(OS, false); 329 OS << ")"; 330 return; 331 } 332 333 // Otherwise just print it normally. 334 U->getValue()->printAsOperand(OS, false); 335 return; 336 } 337 case scCouldNotCompute: 338 OS << "***COULDNOTCOMPUTE***"; 339 return; 340 } 341 llvm_unreachable("Unknown SCEV kind!"); 342 } 343 344 Type *SCEV::getType() const { 345 switch (static_cast<SCEVTypes>(getSCEVType())) { 346 case scConstant: 347 return cast<SCEVConstant>(this)->getType(); 348 case scTruncate: 349 case scZeroExtend: 350 case scSignExtend: 351 return cast<SCEVCastExpr>(this)->getType(); 352 case scAddRecExpr: 353 case scMulExpr: 354 case scUMaxExpr: 355 case scSMaxExpr: 356 return cast<SCEVNAryExpr>(this)->getType(); 357 case scAddExpr: 358 return cast<SCEVAddExpr>(this)->getType(); 359 case scUDivExpr: 360 return cast<SCEVUDivExpr>(this)->getType(); 361 case scUnknown: 362 return cast<SCEVUnknown>(this)->getType(); 363 case scCouldNotCompute: 364 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 365 } 366 llvm_unreachable("Unknown SCEV kind!"); 367 } 368 369 bool SCEV::isZero() const { 370 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 371 return SC->getValue()->isZero(); 372 return false; 373 } 374 375 bool SCEV::isOne() const { 376 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 377 return SC->getValue()->isOne(); 378 return false; 379 } 380 381 bool SCEV::isAllOnesValue() const { 382 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 383 return SC->getValue()->isMinusOne(); 384 return false; 385 } 386 387 bool SCEV::isNonConstantNegative() const { 388 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 389 if (!Mul) return false; 390 391 // If there is a constant factor, it will be first. 392 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 393 if (!SC) return false; 394 395 // Return true if the value is negative, this matches things like (-42 * V). 396 return SC->getAPInt().isNegative(); 397 } 398 399 SCEVCouldNotCompute::SCEVCouldNotCompute() : 400 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 401 402 bool SCEVCouldNotCompute::classof(const SCEV *S) { 403 return S->getSCEVType() == scCouldNotCompute; 404 } 405 406 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 407 FoldingSetNodeID ID; 408 ID.AddInteger(scConstant); 409 ID.AddPointer(V); 410 void *IP = nullptr; 411 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 412 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 413 UniqueSCEVs.InsertNode(S, IP); 414 return S; 415 } 416 417 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 418 return getConstant(ConstantInt::get(getContext(), Val)); 419 } 420 421 const SCEV * 422 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 423 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 424 return getConstant(ConstantInt::get(ITy, V, isSigned)); 425 } 426 427 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 428 unsigned SCEVTy, const SCEV *op, Type *ty) 429 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {} 430 431 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 432 const SCEV *op, Type *ty) 433 : SCEVCastExpr(ID, scTruncate, op, ty) { 434 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 435 "Cannot truncate non-integer value!"); 436 } 437 438 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 439 const SCEV *op, Type *ty) 440 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 441 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 442 "Cannot zero extend non-integer value!"); 443 } 444 445 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 446 const SCEV *op, Type *ty) 447 : SCEVCastExpr(ID, scSignExtend, op, ty) { 448 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 449 "Cannot sign extend non-integer value!"); 450 } 451 452 void SCEVUnknown::deleted() { 453 // Clear this SCEVUnknown from various maps. 454 SE->forgetMemoizedResults(this); 455 456 // Remove this SCEVUnknown from the uniquing map. 457 SE->UniqueSCEVs.RemoveNode(this); 458 459 // Release the value. 460 setValPtr(nullptr); 461 } 462 463 void SCEVUnknown::allUsesReplacedWith(Value *New) { 464 // Remove this SCEVUnknown from the uniquing map. 465 SE->UniqueSCEVs.RemoveNode(this); 466 467 // Update this SCEVUnknown to point to the new value. This is needed 468 // because there may still be outstanding SCEVs which still point to 469 // this SCEVUnknown. 470 setValPtr(New); 471 } 472 473 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 474 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 475 if (VCE->getOpcode() == Instruction::PtrToInt) 476 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 477 if (CE->getOpcode() == Instruction::GetElementPtr && 478 CE->getOperand(0)->isNullValue() && 479 CE->getNumOperands() == 2) 480 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 481 if (CI->isOne()) { 482 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 483 ->getElementType(); 484 return true; 485 } 486 487 return false; 488 } 489 490 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 491 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 492 if (VCE->getOpcode() == Instruction::PtrToInt) 493 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 494 if (CE->getOpcode() == Instruction::GetElementPtr && 495 CE->getOperand(0)->isNullValue()) { 496 Type *Ty = 497 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 498 if (StructType *STy = dyn_cast<StructType>(Ty)) 499 if (!STy->isPacked() && 500 CE->getNumOperands() == 3 && 501 CE->getOperand(1)->isNullValue()) { 502 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 503 if (CI->isOne() && 504 STy->getNumElements() == 2 && 505 STy->getElementType(0)->isIntegerTy(1)) { 506 AllocTy = STy->getElementType(1); 507 return true; 508 } 509 } 510 } 511 512 return false; 513 } 514 515 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 516 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 517 if (VCE->getOpcode() == Instruction::PtrToInt) 518 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 519 if (CE->getOpcode() == Instruction::GetElementPtr && 520 CE->getNumOperands() == 3 && 521 CE->getOperand(0)->isNullValue() && 522 CE->getOperand(1)->isNullValue()) { 523 Type *Ty = 524 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 525 // Ignore vector types here so that ScalarEvolutionExpander doesn't 526 // emit getelementptrs that index into vectors. 527 if (Ty->isStructTy() || Ty->isArrayTy()) { 528 CTy = Ty; 529 FieldNo = CE->getOperand(2); 530 return true; 531 } 532 } 533 534 return false; 535 } 536 537 //===----------------------------------------------------------------------===// 538 // SCEV Utilities 539 //===----------------------------------------------------------------------===// 540 541 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 542 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 543 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 544 /// have been previously deemed to be "equally complex" by this routine. It is 545 /// intended to avoid exponential time complexity in cases like: 546 /// 547 /// %a = f(%x, %y) 548 /// %b = f(%a, %a) 549 /// %c = f(%b, %b) 550 /// 551 /// %d = f(%x, %y) 552 /// %e = f(%d, %d) 553 /// %f = f(%e, %e) 554 /// 555 /// CompareValueComplexity(%f, %c) 556 /// 557 /// Since we do not continue running this routine on expression trees once we 558 /// have seen unequal values, there is no need to track them in the cache. 559 static int 560 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 561 const LoopInfo *const LI, Value *LV, Value *RV, 562 unsigned Depth) { 563 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 564 return 0; 565 566 // Order pointer values after integer values. This helps SCEVExpander form 567 // GEPs. 568 bool LIsPointer = LV->getType()->isPointerTy(), 569 RIsPointer = RV->getType()->isPointerTy(); 570 if (LIsPointer != RIsPointer) 571 return (int)LIsPointer - (int)RIsPointer; 572 573 // Compare getValueID values. 574 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 575 if (LID != RID) 576 return (int)LID - (int)RID; 577 578 // Sort arguments by their position. 579 if (const auto *LA = dyn_cast<Argument>(LV)) { 580 const auto *RA = cast<Argument>(RV); 581 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 582 return (int)LArgNo - (int)RArgNo; 583 } 584 585 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 586 const auto *RGV = cast<GlobalValue>(RV); 587 588 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 589 auto LT = GV->getLinkage(); 590 return !(GlobalValue::isPrivateLinkage(LT) || 591 GlobalValue::isInternalLinkage(LT)); 592 }; 593 594 // Use the names to distinguish the two values, but only if the 595 // names are semantically important. 596 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 597 return LGV->getName().compare(RGV->getName()); 598 } 599 600 // For instructions, compare their loop depth, and their operand count. This 601 // is pretty loose. 602 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 603 const auto *RInst = cast<Instruction>(RV); 604 605 // Compare loop depths. 606 const BasicBlock *LParent = LInst->getParent(), 607 *RParent = RInst->getParent(); 608 if (LParent != RParent) { 609 unsigned LDepth = LI->getLoopDepth(LParent), 610 RDepth = LI->getLoopDepth(RParent); 611 if (LDepth != RDepth) 612 return (int)LDepth - (int)RDepth; 613 } 614 615 // Compare the number of operands. 616 unsigned LNumOps = LInst->getNumOperands(), 617 RNumOps = RInst->getNumOperands(); 618 if (LNumOps != RNumOps) 619 return (int)LNumOps - (int)RNumOps; 620 621 for (unsigned Idx : seq(0u, LNumOps)) { 622 int Result = 623 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 624 RInst->getOperand(Idx), Depth + 1); 625 if (Result != 0) 626 return Result; 627 } 628 } 629 630 EqCacheValue.unionSets(LV, RV); 631 return 0; 632 } 633 634 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 635 // than RHS, respectively. A three-way result allows recursive comparisons to be 636 // more efficient. 637 static int CompareSCEVComplexity( 638 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 639 EquivalenceClasses<const Value *> &EqCacheValue, 640 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 641 DominatorTree &DT, unsigned Depth = 0) { 642 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 643 if (LHS == RHS) 644 return 0; 645 646 // Primarily, sort the SCEVs by their getSCEVType(). 647 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 648 if (LType != RType) 649 return (int)LType - (int)RType; 650 651 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 652 return 0; 653 // Aside from the getSCEVType() ordering, the particular ordering 654 // isn't very important except that it's beneficial to be consistent, 655 // so that (a + b) and (b + a) don't end up as different expressions. 656 switch (static_cast<SCEVTypes>(LType)) { 657 case scUnknown: { 658 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 659 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 660 661 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 662 RU->getValue(), Depth + 1); 663 if (X == 0) 664 EqCacheSCEV.unionSets(LHS, RHS); 665 return X; 666 } 667 668 case scConstant: { 669 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 670 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 671 672 // Compare constant values. 673 const APInt &LA = LC->getAPInt(); 674 const APInt &RA = RC->getAPInt(); 675 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 676 if (LBitWidth != RBitWidth) 677 return (int)LBitWidth - (int)RBitWidth; 678 return LA.ult(RA) ? -1 : 1; 679 } 680 681 case scAddRecExpr: { 682 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 683 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 684 685 // There is always a dominance between two recs that are used by one SCEV, 686 // so we can safely sort recs by loop header dominance. We require such 687 // order in getAddExpr. 688 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 689 if (LLoop != RLoop) { 690 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 691 assert(LHead != RHead && "Two loops share the same header?"); 692 if (DT.dominates(LHead, RHead)) 693 return 1; 694 else 695 assert(DT.dominates(RHead, LHead) && 696 "No dominance between recurrences used by one SCEV?"); 697 return -1; 698 } 699 700 // Addrec complexity grows with operand count. 701 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 702 if (LNumOps != RNumOps) 703 return (int)LNumOps - (int)RNumOps; 704 705 // Lexicographically compare. 706 for (unsigned i = 0; i != LNumOps; ++i) { 707 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 708 LA->getOperand(i), RA->getOperand(i), DT, 709 Depth + 1); 710 if (X != 0) 711 return X; 712 } 713 EqCacheSCEV.unionSets(LHS, RHS); 714 return 0; 715 } 716 717 case scAddExpr: 718 case scMulExpr: 719 case scSMaxExpr: 720 case scUMaxExpr: { 721 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 722 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 723 724 // Lexicographically compare n-ary expressions. 725 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 726 if (LNumOps != RNumOps) 727 return (int)LNumOps - (int)RNumOps; 728 729 for (unsigned i = 0; i != LNumOps; ++i) { 730 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 731 LC->getOperand(i), RC->getOperand(i), DT, 732 Depth + 1); 733 if (X != 0) 734 return X; 735 } 736 EqCacheSCEV.unionSets(LHS, RHS); 737 return 0; 738 } 739 740 case scUDivExpr: { 741 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 742 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 743 744 // Lexicographically compare udiv expressions. 745 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 746 RC->getLHS(), DT, Depth + 1); 747 if (X != 0) 748 return X; 749 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 750 RC->getRHS(), DT, Depth + 1); 751 if (X == 0) 752 EqCacheSCEV.unionSets(LHS, RHS); 753 return X; 754 } 755 756 case scTruncate: 757 case scZeroExtend: 758 case scSignExtend: { 759 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 760 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 761 762 // Compare cast expressions by operand. 763 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 764 LC->getOperand(), RC->getOperand(), DT, 765 Depth + 1); 766 if (X == 0) 767 EqCacheSCEV.unionSets(LHS, RHS); 768 return X; 769 } 770 771 case scCouldNotCompute: 772 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 773 } 774 llvm_unreachable("Unknown SCEV kind!"); 775 } 776 777 /// Given a list of SCEV objects, order them by their complexity, and group 778 /// objects of the same complexity together by value. When this routine is 779 /// finished, we know that any duplicates in the vector are consecutive and that 780 /// complexity is monotonically increasing. 781 /// 782 /// Note that we go take special precautions to ensure that we get deterministic 783 /// results from this routine. In other words, we don't want the results of 784 /// this to depend on where the addresses of various SCEV objects happened to 785 /// land in memory. 786 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 787 LoopInfo *LI, DominatorTree &DT) { 788 if (Ops.size() < 2) return; // Noop 789 790 EquivalenceClasses<const SCEV *> EqCacheSCEV; 791 EquivalenceClasses<const Value *> EqCacheValue; 792 if (Ops.size() == 2) { 793 // This is the common case, which also happens to be trivially simple. 794 // Special case it. 795 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 796 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 797 std::swap(LHS, RHS); 798 return; 799 } 800 801 // Do the rough sort by complexity. 802 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 /// Returns true if the subtree of \p S contains at least HugeExprThreshold 854 /// nodes. 855 static bool isHugeExpression(const SCEV *S) { 856 return S->getExpressionSize() >= HugeExprThreshold; 857 } 858 859 /// Returns true of \p Ops contains a huge SCEV (see definition above). 860 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 861 return any_of(Ops, isHugeExpression); 862 } 863 864 namespace { 865 866 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 867 public: 868 // Computes the Quotient and Remainder of the division of Numerator by 869 // Denominator. 870 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 871 const SCEV *Denominator, const SCEV **Quotient, 872 const SCEV **Remainder) { 873 assert(Numerator && Denominator && "Uninitialized SCEV"); 874 875 SCEVDivision D(SE, Numerator, Denominator); 876 877 // Check for the trivial case here to avoid having to check for it in the 878 // rest of the code. 879 if (Numerator == Denominator) { 880 *Quotient = D.One; 881 *Remainder = D.Zero; 882 return; 883 } 884 885 if (Numerator->isZero()) { 886 *Quotient = D.Zero; 887 *Remainder = D.Zero; 888 return; 889 } 890 891 // A simple case when N/1. The quotient is N. 892 if (Denominator->isOne()) { 893 *Quotient = Numerator; 894 *Remainder = D.Zero; 895 return; 896 } 897 898 // Split the Denominator when it is a product. 899 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 900 const SCEV *Q, *R; 901 *Quotient = Numerator; 902 for (const SCEV *Op : T->operands()) { 903 divide(SE, *Quotient, Op, &Q, &R); 904 *Quotient = Q; 905 906 // Bail out when the Numerator is not divisible by one of the terms of 907 // the Denominator. 908 if (!R->isZero()) { 909 *Quotient = D.Zero; 910 *Remainder = Numerator; 911 return; 912 } 913 } 914 *Remainder = D.Zero; 915 return; 916 } 917 918 D.visit(Numerator); 919 *Quotient = D.Quotient; 920 *Remainder = D.Remainder; 921 } 922 923 // Except in the trivial case described above, we do not know how to divide 924 // Expr by Denominator for the following functions with empty implementation. 925 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 926 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 927 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 928 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 929 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 930 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 931 void visitUnknown(const SCEVUnknown *Numerator) {} 932 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 933 934 void visitConstant(const SCEVConstant *Numerator) { 935 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 936 APInt NumeratorVal = Numerator->getAPInt(); 937 APInt DenominatorVal = D->getAPInt(); 938 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 939 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 940 941 if (NumeratorBW > DenominatorBW) 942 DenominatorVal = DenominatorVal.sext(NumeratorBW); 943 else if (NumeratorBW < DenominatorBW) 944 NumeratorVal = NumeratorVal.sext(DenominatorBW); 945 946 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 947 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 948 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 949 Quotient = SE.getConstant(QuotientVal); 950 Remainder = SE.getConstant(RemainderVal); 951 return; 952 } 953 } 954 955 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 956 const SCEV *StartQ, *StartR, *StepQ, *StepR; 957 if (!Numerator->isAffine()) 958 return cannotDivide(Numerator); 959 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 960 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 961 // Bail out if the types do not match. 962 Type *Ty = Denominator->getType(); 963 if (Ty != StartQ->getType() || Ty != StartR->getType() || 964 Ty != StepQ->getType() || Ty != StepR->getType()) 965 return cannotDivide(Numerator); 966 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 967 Numerator->getNoWrapFlags()); 968 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 969 Numerator->getNoWrapFlags()); 970 } 971 972 void visitAddExpr(const SCEVAddExpr *Numerator) { 973 SmallVector<const SCEV *, 2> Qs, Rs; 974 Type *Ty = Denominator->getType(); 975 976 for (const SCEV *Op : Numerator->operands()) { 977 const SCEV *Q, *R; 978 divide(SE, Op, Denominator, &Q, &R); 979 980 // Bail out if types do not match. 981 if (Ty != Q->getType() || Ty != R->getType()) 982 return cannotDivide(Numerator); 983 984 Qs.push_back(Q); 985 Rs.push_back(R); 986 } 987 988 if (Qs.size() == 1) { 989 Quotient = Qs[0]; 990 Remainder = Rs[0]; 991 return; 992 } 993 994 Quotient = SE.getAddExpr(Qs); 995 Remainder = SE.getAddExpr(Rs); 996 } 997 998 void visitMulExpr(const SCEVMulExpr *Numerator) { 999 SmallVector<const SCEV *, 2> Qs; 1000 Type *Ty = Denominator->getType(); 1001 1002 bool FoundDenominatorTerm = false; 1003 for (const SCEV *Op : Numerator->operands()) { 1004 // Bail out if types do not match. 1005 if (Ty != Op->getType()) 1006 return cannotDivide(Numerator); 1007 1008 if (FoundDenominatorTerm) { 1009 Qs.push_back(Op); 1010 continue; 1011 } 1012 1013 // Check whether Denominator divides one of the product operands. 1014 const SCEV *Q, *R; 1015 divide(SE, Op, Denominator, &Q, &R); 1016 if (!R->isZero()) { 1017 Qs.push_back(Op); 1018 continue; 1019 } 1020 1021 // Bail out if types do not match. 1022 if (Ty != Q->getType()) 1023 return cannotDivide(Numerator); 1024 1025 FoundDenominatorTerm = true; 1026 Qs.push_back(Q); 1027 } 1028 1029 if (FoundDenominatorTerm) { 1030 Remainder = Zero; 1031 if (Qs.size() == 1) 1032 Quotient = Qs[0]; 1033 else 1034 Quotient = SE.getMulExpr(Qs); 1035 return; 1036 } 1037 1038 if (!isa<SCEVUnknown>(Denominator)) 1039 return cannotDivide(Numerator); 1040 1041 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1042 ValueToValueMap RewriteMap; 1043 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1044 cast<SCEVConstant>(Zero)->getValue(); 1045 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1046 1047 if (Remainder->isZero()) { 1048 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1049 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1050 cast<SCEVConstant>(One)->getValue(); 1051 Quotient = 1052 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1053 return; 1054 } 1055 1056 // Quotient is (Numerator - Remainder) divided by Denominator. 1057 const SCEV *Q, *R; 1058 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1059 // This SCEV does not seem to simplify: fail the division here. 1060 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1061 return cannotDivide(Numerator); 1062 divide(SE, Diff, Denominator, &Q, &R); 1063 if (R != Zero) 1064 return cannotDivide(Numerator); 1065 Quotient = Q; 1066 } 1067 1068 private: 1069 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1070 const SCEV *Denominator) 1071 : SE(S), Denominator(Denominator) { 1072 Zero = SE.getZero(Denominator->getType()); 1073 One = SE.getOne(Denominator->getType()); 1074 1075 // We generally do not know how to divide Expr by Denominator. We 1076 // initialize the division to a "cannot divide" state to simplify the rest 1077 // of the code. 1078 cannotDivide(Numerator); 1079 } 1080 1081 // Convenience function for giving up on the division. We set the quotient to 1082 // be equal to zero and the remainder to be equal to the numerator. 1083 void cannotDivide(const SCEV *Numerator) { 1084 Quotient = Zero; 1085 Remainder = Numerator; 1086 } 1087 1088 ScalarEvolution &SE; 1089 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1090 }; 1091 1092 } // end anonymous namespace 1093 1094 //===----------------------------------------------------------------------===// 1095 // Simple SCEV method implementations 1096 //===----------------------------------------------------------------------===// 1097 1098 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1099 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1100 ScalarEvolution &SE, 1101 Type *ResultTy) { 1102 // Handle the simplest case efficiently. 1103 if (K == 1) 1104 return SE.getTruncateOrZeroExtend(It, ResultTy); 1105 1106 // We are using the following formula for BC(It, K): 1107 // 1108 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1109 // 1110 // Suppose, W is the bitwidth of the return value. We must be prepared for 1111 // overflow. Hence, we must assure that the result of our computation is 1112 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1113 // safe in modular arithmetic. 1114 // 1115 // However, this code doesn't use exactly that formula; the formula it uses 1116 // is something like the following, where T is the number of factors of 2 in 1117 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1118 // exponentiation: 1119 // 1120 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1121 // 1122 // This formula is trivially equivalent to the previous formula. However, 1123 // this formula can be implemented much more efficiently. The trick is that 1124 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1125 // arithmetic. To do exact division in modular arithmetic, all we have 1126 // to do is multiply by the inverse. Therefore, this step can be done at 1127 // width W. 1128 // 1129 // The next issue is how to safely do the division by 2^T. The way this 1130 // is done is by doing the multiplication step at a width of at least W + T 1131 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1132 // when we perform the division by 2^T (which is equivalent to a right shift 1133 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1134 // truncated out after the division by 2^T. 1135 // 1136 // In comparison to just directly using the first formula, this technique 1137 // is much more efficient; using the first formula requires W * K bits, 1138 // but this formula less than W + K bits. Also, the first formula requires 1139 // a division step, whereas this formula only requires multiplies and shifts. 1140 // 1141 // It doesn't matter whether the subtraction step is done in the calculation 1142 // width or the input iteration count's width; if the subtraction overflows, 1143 // the result must be zero anyway. We prefer here to do it in the width of 1144 // the induction variable because it helps a lot for certain cases; CodeGen 1145 // isn't smart enough to ignore the overflow, which leads to much less 1146 // efficient code if the width of the subtraction is wider than the native 1147 // register width. 1148 // 1149 // (It's possible to not widen at all by pulling out factors of 2 before 1150 // the multiplication; for example, K=2 can be calculated as 1151 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1152 // extra arithmetic, so it's not an obvious win, and it gets 1153 // much more complicated for K > 3.) 1154 1155 // Protection from insane SCEVs; this bound is conservative, 1156 // but it probably doesn't matter. 1157 if (K > 1000) 1158 return SE.getCouldNotCompute(); 1159 1160 unsigned W = SE.getTypeSizeInBits(ResultTy); 1161 1162 // Calculate K! / 2^T and T; we divide out the factors of two before 1163 // multiplying for calculating K! / 2^T to avoid overflow. 1164 // Other overflow doesn't matter because we only care about the bottom 1165 // W bits of the result. 1166 APInt OddFactorial(W, 1); 1167 unsigned T = 1; 1168 for (unsigned i = 3; i <= K; ++i) { 1169 APInt Mult(W, i); 1170 unsigned TwoFactors = Mult.countTrailingZeros(); 1171 T += TwoFactors; 1172 Mult.lshrInPlace(TwoFactors); 1173 OddFactorial *= Mult; 1174 } 1175 1176 // We need at least W + T bits for the multiplication step 1177 unsigned CalculationBits = W + T; 1178 1179 // Calculate 2^T, at width T+W. 1180 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1181 1182 // Calculate the multiplicative inverse of K! / 2^T; 1183 // this multiplication factor will perform the exact division by 1184 // K! / 2^T. 1185 APInt Mod = APInt::getSignedMinValue(W+1); 1186 APInt MultiplyFactor = OddFactorial.zext(W+1); 1187 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1188 MultiplyFactor = MultiplyFactor.trunc(W); 1189 1190 // Calculate the product, at width T+W 1191 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1192 CalculationBits); 1193 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1194 for (unsigned i = 1; i != K; ++i) { 1195 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1196 Dividend = SE.getMulExpr(Dividend, 1197 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1198 } 1199 1200 // Divide by 2^T 1201 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1202 1203 // Truncate the result, and divide by K! / 2^T. 1204 1205 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1206 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1207 } 1208 1209 /// Return the value of this chain of recurrences at the specified iteration 1210 /// number. We can evaluate this recurrence by multiplying each element in the 1211 /// chain by the binomial coefficient corresponding to it. In other words, we 1212 /// can evaluate {A,+,B,+,C,+,D} as: 1213 /// 1214 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1215 /// 1216 /// where BC(It, k) stands for binomial coefficient. 1217 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1218 ScalarEvolution &SE) const { 1219 const SCEV *Result = getStart(); 1220 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1221 // The computation is correct in the face of overflow provided that the 1222 // multiplication is performed _after_ the evaluation of the binomial 1223 // coefficient. 1224 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1225 if (isa<SCEVCouldNotCompute>(Coeff)) 1226 return Coeff; 1227 1228 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1229 } 1230 return Result; 1231 } 1232 1233 //===----------------------------------------------------------------------===// 1234 // SCEV Expression folder implementations 1235 //===----------------------------------------------------------------------===// 1236 1237 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1238 unsigned Depth) { 1239 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1240 "This is not a truncating conversion!"); 1241 assert(isSCEVable(Ty) && 1242 "This is not a conversion to a SCEVable type!"); 1243 Ty = getEffectiveSCEVType(Ty); 1244 1245 FoldingSetNodeID ID; 1246 ID.AddInteger(scTruncate); 1247 ID.AddPointer(Op); 1248 ID.AddPointer(Ty); 1249 void *IP = nullptr; 1250 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1251 1252 // Fold if the operand is constant. 1253 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1254 return getConstant( 1255 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1256 1257 // trunc(trunc(x)) --> trunc(x) 1258 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1259 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1260 1261 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1262 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1263 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1264 1265 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1266 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1267 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1268 1269 if (Depth > MaxCastDepth) { 1270 SCEV *S = 1271 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1272 UniqueSCEVs.InsertNode(S, IP); 1273 addToLoopUseLists(S); 1274 return S; 1275 } 1276 1277 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1278 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1279 // if after transforming we have at most one truncate, not counting truncates 1280 // that replace other casts. 1281 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1282 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1283 SmallVector<const SCEV *, 4> Operands; 1284 unsigned numTruncs = 0; 1285 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1286 ++i) { 1287 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1288 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1289 numTruncs++; 1290 Operands.push_back(S); 1291 } 1292 if (numTruncs < 2) { 1293 if (isa<SCEVAddExpr>(Op)) 1294 return getAddExpr(Operands); 1295 else if (isa<SCEVMulExpr>(Op)) 1296 return getMulExpr(Operands); 1297 else 1298 llvm_unreachable("Unexpected SCEV type for Op."); 1299 } 1300 // Although we checked in the beginning that ID is not in the cache, it is 1301 // possible that during recursion and different modification ID was inserted 1302 // into the cache. So if we find it, just return it. 1303 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1304 return S; 1305 } 1306 1307 // If the input value is a chrec scev, truncate the chrec's operands. 1308 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1309 SmallVector<const SCEV *, 4> Operands; 1310 for (const SCEV *Op : AddRec->operands()) 1311 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1312 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1313 } 1314 1315 // The cast wasn't folded; create an explicit cast node. We can reuse 1316 // the existing insert position since if we get here, we won't have 1317 // made any changes which would invalidate it. 1318 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1319 Op, Ty); 1320 UniqueSCEVs.InsertNode(S, IP); 1321 addToLoopUseLists(S); 1322 return S; 1323 } 1324 1325 // Get the limit of a recurrence such that incrementing by Step cannot cause 1326 // signed overflow as long as the value of the recurrence within the 1327 // loop does not exceed this limit before incrementing. 1328 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1329 ICmpInst::Predicate *Pred, 1330 ScalarEvolution *SE) { 1331 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1332 if (SE->isKnownPositive(Step)) { 1333 *Pred = ICmpInst::ICMP_SLT; 1334 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1335 SE->getSignedRangeMax(Step)); 1336 } 1337 if (SE->isKnownNegative(Step)) { 1338 *Pred = ICmpInst::ICMP_SGT; 1339 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1340 SE->getSignedRangeMin(Step)); 1341 } 1342 return nullptr; 1343 } 1344 1345 // Get the limit of a recurrence such that incrementing by Step cannot cause 1346 // unsigned overflow as long as the value of the recurrence within the loop does 1347 // not exceed this limit before incrementing. 1348 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1349 ICmpInst::Predicate *Pred, 1350 ScalarEvolution *SE) { 1351 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1352 *Pred = ICmpInst::ICMP_ULT; 1353 1354 return SE->getConstant(APInt::getMinValue(BitWidth) - 1355 SE->getUnsignedRangeMax(Step)); 1356 } 1357 1358 namespace { 1359 1360 struct ExtendOpTraitsBase { 1361 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1362 unsigned); 1363 }; 1364 1365 // Used to make code generic over signed and unsigned overflow. 1366 template <typename ExtendOp> struct ExtendOpTraits { 1367 // Members present: 1368 // 1369 // static const SCEV::NoWrapFlags WrapType; 1370 // 1371 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1372 // 1373 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1374 // ICmpInst::Predicate *Pred, 1375 // ScalarEvolution *SE); 1376 }; 1377 1378 template <> 1379 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1380 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1381 1382 static const GetExtendExprTy GetExtendExpr; 1383 1384 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1385 ICmpInst::Predicate *Pred, 1386 ScalarEvolution *SE) { 1387 return getSignedOverflowLimitForStep(Step, Pred, SE); 1388 } 1389 }; 1390 1391 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1392 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1393 1394 template <> 1395 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1396 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1397 1398 static const GetExtendExprTy GetExtendExpr; 1399 1400 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1401 ICmpInst::Predicate *Pred, 1402 ScalarEvolution *SE) { 1403 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1404 } 1405 }; 1406 1407 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1408 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1409 1410 } // end anonymous namespace 1411 1412 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1413 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1414 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1415 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1416 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1417 // expression "Step + sext/zext(PreIncAR)" is congruent with 1418 // "sext/zext(PostIncAR)" 1419 template <typename ExtendOpTy> 1420 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1421 ScalarEvolution *SE, unsigned Depth) { 1422 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1423 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1424 1425 const Loop *L = AR->getLoop(); 1426 const SCEV *Start = AR->getStart(); 1427 const SCEV *Step = AR->getStepRecurrence(*SE); 1428 1429 // Check for a simple looking step prior to loop entry. 1430 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1431 if (!SA) 1432 return nullptr; 1433 1434 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1435 // subtraction is expensive. For this purpose, perform a quick and dirty 1436 // difference, by checking for Step in the operand list. 1437 SmallVector<const SCEV *, 4> DiffOps; 1438 for (const SCEV *Op : SA->operands()) 1439 if (Op != Step) 1440 DiffOps.push_back(Op); 1441 1442 if (DiffOps.size() == SA->getNumOperands()) 1443 return nullptr; 1444 1445 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1446 // `Step`: 1447 1448 // 1. NSW/NUW flags on the step increment. 1449 auto PreStartFlags = 1450 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1451 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1452 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1453 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1454 1455 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1456 // "S+X does not sign/unsign-overflow". 1457 // 1458 1459 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1460 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1461 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1462 return PreStart; 1463 1464 // 2. Direct overflow check on the step operation's expression. 1465 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1466 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1467 const SCEV *OperandExtendedStart = 1468 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1469 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1470 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1471 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1472 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1473 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1474 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1475 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1476 } 1477 return PreStart; 1478 } 1479 1480 // 3. Loop precondition. 1481 ICmpInst::Predicate Pred; 1482 const SCEV *OverflowLimit = 1483 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1484 1485 if (OverflowLimit && 1486 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1487 return PreStart; 1488 1489 return nullptr; 1490 } 1491 1492 // Get the normalized zero or sign extended expression for this AddRec's Start. 1493 template <typename ExtendOpTy> 1494 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1495 ScalarEvolution *SE, 1496 unsigned Depth) { 1497 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1498 1499 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1500 if (!PreStart) 1501 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1502 1503 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1504 Depth), 1505 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1506 } 1507 1508 // Try to prove away overflow by looking at "nearby" add recurrences. A 1509 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1510 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1511 // 1512 // Formally: 1513 // 1514 // {S,+,X} == {S-T,+,X} + T 1515 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1516 // 1517 // If ({S-T,+,X} + T) does not overflow ... (1) 1518 // 1519 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1520 // 1521 // If {S-T,+,X} does not overflow ... (2) 1522 // 1523 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1524 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1525 // 1526 // If (S-T)+T does not overflow ... (3) 1527 // 1528 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1529 // == {Ext(S),+,Ext(X)} == LHS 1530 // 1531 // Thus, if (1), (2) and (3) are true for some T, then 1532 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1533 // 1534 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1535 // does not overflow" restricted to the 0th iteration. Therefore we only need 1536 // to check for (1) and (2). 1537 // 1538 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1539 // is `Delta` (defined below). 1540 template <typename ExtendOpTy> 1541 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1542 const SCEV *Step, 1543 const Loop *L) { 1544 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1545 1546 // We restrict `Start` to a constant to prevent SCEV from spending too much 1547 // time here. It is correct (but more expensive) to continue with a 1548 // non-constant `Start` and do a general SCEV subtraction to compute 1549 // `PreStart` below. 1550 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1551 if (!StartC) 1552 return false; 1553 1554 APInt StartAI = StartC->getAPInt(); 1555 1556 for (unsigned Delta : {-2, -1, 1, 2}) { 1557 const SCEV *PreStart = getConstant(StartAI - Delta); 1558 1559 FoldingSetNodeID ID; 1560 ID.AddInteger(scAddRecExpr); 1561 ID.AddPointer(PreStart); 1562 ID.AddPointer(Step); 1563 ID.AddPointer(L); 1564 void *IP = nullptr; 1565 const auto *PreAR = 1566 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1567 1568 // Give up if we don't already have the add recurrence we need because 1569 // actually constructing an add recurrence is relatively expensive. 1570 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1571 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1572 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1573 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1574 DeltaS, &Pred, this); 1575 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1576 return true; 1577 } 1578 } 1579 1580 return false; 1581 } 1582 1583 // Finds an integer D for an expression (C + x + y + ...) such that the top 1584 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1585 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1586 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1587 // the (C + x + y + ...) expression is \p WholeAddExpr. 1588 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1589 const SCEVConstant *ConstantTerm, 1590 const SCEVAddExpr *WholeAddExpr) { 1591 const APInt C = ConstantTerm->getAPInt(); 1592 const unsigned BitWidth = C.getBitWidth(); 1593 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1594 uint32_t TZ = BitWidth; 1595 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1596 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1597 if (TZ) { 1598 // Set D to be as many least significant bits of C as possible while still 1599 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1600 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1601 } 1602 return APInt(BitWidth, 0); 1603 } 1604 1605 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1606 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1607 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1608 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1609 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1610 const APInt &ConstantStart, 1611 const SCEV *Step) { 1612 const unsigned BitWidth = ConstantStart.getBitWidth(); 1613 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1614 if (TZ) 1615 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1616 : ConstantStart; 1617 return APInt(BitWidth, 0); 1618 } 1619 1620 const SCEV * 1621 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1622 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1623 "This is not an extending conversion!"); 1624 assert(isSCEVable(Ty) && 1625 "This is not a conversion to a SCEVable type!"); 1626 Ty = getEffectiveSCEVType(Ty); 1627 1628 // Fold if the operand is constant. 1629 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1630 return getConstant( 1631 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1632 1633 // zext(zext(x)) --> zext(x) 1634 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1635 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1636 1637 // Before doing any expensive analysis, check to see if we've already 1638 // computed a SCEV for this Op and Ty. 1639 FoldingSetNodeID ID; 1640 ID.AddInteger(scZeroExtend); 1641 ID.AddPointer(Op); 1642 ID.AddPointer(Ty); 1643 void *IP = nullptr; 1644 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1645 if (Depth > MaxCastDepth) { 1646 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1647 Op, Ty); 1648 UniqueSCEVs.InsertNode(S, IP); 1649 addToLoopUseLists(S); 1650 return S; 1651 } 1652 1653 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1654 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1655 // It's possible the bits taken off by the truncate were all zero bits. If 1656 // so, we should be able to simplify this further. 1657 const SCEV *X = ST->getOperand(); 1658 ConstantRange CR = getUnsignedRange(X); 1659 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1660 unsigned NewBits = getTypeSizeInBits(Ty); 1661 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1662 CR.zextOrTrunc(NewBits))) 1663 return getTruncateOrZeroExtend(X, Ty, Depth); 1664 } 1665 1666 // If the input value is a chrec scev, and we can prove that the value 1667 // did not overflow the old, smaller, value, we can zero extend all of the 1668 // operands (often constants). This allows analysis of something like 1669 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1670 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1671 if (AR->isAffine()) { 1672 const SCEV *Start = AR->getStart(); 1673 const SCEV *Step = AR->getStepRecurrence(*this); 1674 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1675 const Loop *L = AR->getLoop(); 1676 1677 if (!AR->hasNoUnsignedWrap()) { 1678 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1679 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1680 } 1681 1682 // If we have special knowledge that this addrec won't overflow, 1683 // we don't need to do any further analysis. 1684 if (AR->hasNoUnsignedWrap()) 1685 return getAddRecExpr( 1686 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1687 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1688 1689 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1690 // Note that this serves two purposes: It filters out loops that are 1691 // simply not analyzable, and it covers the case where this code is 1692 // being called from within backedge-taken count analysis, such that 1693 // attempting to ask for the backedge-taken count would likely result 1694 // in infinite recursion. In the later case, the analysis code will 1695 // cope with a conservative value, and it will take care to purge 1696 // that value once it has finished. 1697 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1698 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1699 // Manually compute the final value for AR, checking for 1700 // overflow. 1701 1702 // Check whether the backedge-taken count can be losslessly casted to 1703 // the addrec's type. The count is always unsigned. 1704 const SCEV *CastedMaxBECount = 1705 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1706 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1707 CastedMaxBECount, MaxBECount->getType(), Depth); 1708 if (MaxBECount == RecastedMaxBECount) { 1709 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1710 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1711 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1712 SCEV::FlagAnyWrap, Depth + 1); 1713 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1714 SCEV::FlagAnyWrap, 1715 Depth + 1), 1716 WideTy, Depth + 1); 1717 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1718 const SCEV *WideMaxBECount = 1719 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1720 const SCEV *OperandExtendedAdd = 1721 getAddExpr(WideStart, 1722 getMulExpr(WideMaxBECount, 1723 getZeroExtendExpr(Step, WideTy, Depth + 1), 1724 SCEV::FlagAnyWrap, Depth + 1), 1725 SCEV::FlagAnyWrap, Depth + 1); 1726 if (ZAdd == OperandExtendedAdd) { 1727 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1728 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1729 // Return the expression with the addrec on the outside. 1730 return getAddRecExpr( 1731 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1732 Depth + 1), 1733 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1734 AR->getNoWrapFlags()); 1735 } 1736 // Similar to above, only this time treat the step value as signed. 1737 // This covers loops that count down. 1738 OperandExtendedAdd = 1739 getAddExpr(WideStart, 1740 getMulExpr(WideMaxBECount, 1741 getSignExtendExpr(Step, WideTy, Depth + 1), 1742 SCEV::FlagAnyWrap, Depth + 1), 1743 SCEV::FlagAnyWrap, Depth + 1); 1744 if (ZAdd == OperandExtendedAdd) { 1745 // Cache knowledge of AR NW, which is propagated to this AddRec. 1746 // Negative step causes unsigned wrap, but it still can't self-wrap. 1747 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1748 // Return the expression with the addrec on the outside. 1749 return getAddRecExpr( 1750 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1751 Depth + 1), 1752 getSignExtendExpr(Step, Ty, Depth + 1), L, 1753 AR->getNoWrapFlags()); 1754 } 1755 } 1756 } 1757 1758 // Normally, in the cases we can prove no-overflow via a 1759 // backedge guarding condition, we can also compute a backedge 1760 // taken count for the loop. The exceptions are assumptions and 1761 // guards present in the loop -- SCEV is not great at exploiting 1762 // these to compute max backedge taken counts, but can still use 1763 // these to prove lack of overflow. Use this fact to avoid 1764 // doing extra work that may not pay off. 1765 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1766 !AC.assumptions().empty()) { 1767 // If the backedge is guarded by a comparison with the pre-inc 1768 // value the addrec is safe. Also, if the entry is guarded by 1769 // a comparison with the start value and the backedge is 1770 // guarded by a comparison with the post-inc value, the addrec 1771 // is safe. 1772 if (isKnownPositive(Step)) { 1773 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1774 getUnsignedRangeMax(Step)); 1775 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1776 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1777 // Cache knowledge of AR NUW, which is propagated to this 1778 // AddRec. 1779 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1780 // Return the expression with the addrec on the outside. 1781 return getAddRecExpr( 1782 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1783 Depth + 1), 1784 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1785 AR->getNoWrapFlags()); 1786 } 1787 } else if (isKnownNegative(Step)) { 1788 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1789 getSignedRangeMin(Step)); 1790 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1791 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1792 // Cache knowledge of AR NW, which is propagated to this 1793 // AddRec. Negative step causes unsigned wrap, but it 1794 // still can't self-wrap. 1795 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1796 // Return the expression with the addrec on the outside. 1797 return getAddRecExpr( 1798 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1799 Depth + 1), 1800 getSignExtendExpr(Step, Ty, Depth + 1), L, 1801 AR->getNoWrapFlags()); 1802 } 1803 } 1804 } 1805 1806 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1807 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1808 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1809 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1810 const APInt &C = SC->getAPInt(); 1811 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1812 if (D != 0) { 1813 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1814 const SCEV *SResidual = 1815 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1816 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1817 return getAddExpr(SZExtD, SZExtR, 1818 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1819 Depth + 1); 1820 } 1821 } 1822 1823 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1824 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1825 return getAddRecExpr( 1826 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1827 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1828 } 1829 } 1830 1831 // zext(A % B) --> zext(A) % zext(B) 1832 { 1833 const SCEV *LHS; 1834 const SCEV *RHS; 1835 if (matchURem(Op, LHS, RHS)) 1836 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1837 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1838 } 1839 1840 // zext(A / B) --> zext(A) / zext(B). 1841 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1842 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1843 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1844 1845 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1846 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1847 if (SA->hasNoUnsignedWrap()) { 1848 // If the addition does not unsign overflow then we can, by definition, 1849 // commute the zero extension with the addition operation. 1850 SmallVector<const SCEV *, 4> Ops; 1851 for (const auto *Op : SA->operands()) 1852 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1853 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1854 } 1855 1856 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1857 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1858 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1859 // 1860 // Often address arithmetics contain expressions like 1861 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1862 // This transformation is useful while proving that such expressions are 1863 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1864 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1865 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1866 if (D != 0) { 1867 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1868 const SCEV *SResidual = 1869 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1870 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1871 return getAddExpr(SZExtD, SZExtR, 1872 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1873 Depth + 1); 1874 } 1875 } 1876 } 1877 1878 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1879 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1880 if (SM->hasNoUnsignedWrap()) { 1881 // If the multiply does not unsign overflow then we can, by definition, 1882 // commute the zero extension with the multiply operation. 1883 SmallVector<const SCEV *, 4> Ops; 1884 for (const auto *Op : SM->operands()) 1885 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1886 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1887 } 1888 1889 // zext(2^K * (trunc X to iN)) to iM -> 1890 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1891 // 1892 // Proof: 1893 // 1894 // zext(2^K * (trunc X to iN)) to iM 1895 // = zext((trunc X to iN) << K) to iM 1896 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1897 // (because shl removes the top K bits) 1898 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1899 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1900 // 1901 if (SM->getNumOperands() == 2) 1902 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1903 if (MulLHS->getAPInt().isPowerOf2()) 1904 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1905 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1906 MulLHS->getAPInt().logBase2(); 1907 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1908 return getMulExpr( 1909 getZeroExtendExpr(MulLHS, Ty), 1910 getZeroExtendExpr( 1911 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1912 SCEV::FlagNUW, Depth + 1); 1913 } 1914 } 1915 1916 // The cast wasn't folded; create an explicit cast node. 1917 // Recompute the insert position, as it may have been invalidated. 1918 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1919 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1920 Op, Ty); 1921 UniqueSCEVs.InsertNode(S, IP); 1922 addToLoopUseLists(S); 1923 return S; 1924 } 1925 1926 const SCEV * 1927 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1928 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1929 "This is not an extending conversion!"); 1930 assert(isSCEVable(Ty) && 1931 "This is not a conversion to a SCEVable type!"); 1932 Ty = getEffectiveSCEVType(Ty); 1933 1934 // Fold if the operand is constant. 1935 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1936 return getConstant( 1937 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1938 1939 // sext(sext(x)) --> sext(x) 1940 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1941 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1942 1943 // sext(zext(x)) --> zext(x) 1944 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1945 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1946 1947 // Before doing any expensive analysis, check to see if we've already 1948 // computed a SCEV for this Op and Ty. 1949 FoldingSetNodeID ID; 1950 ID.AddInteger(scSignExtend); 1951 ID.AddPointer(Op); 1952 ID.AddPointer(Ty); 1953 void *IP = nullptr; 1954 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1955 // Limit recursion depth. 1956 if (Depth > MaxCastDepth) { 1957 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1958 Op, Ty); 1959 UniqueSCEVs.InsertNode(S, IP); 1960 addToLoopUseLists(S); 1961 return S; 1962 } 1963 1964 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1965 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1966 // It's possible the bits taken off by the truncate were all sign bits. If 1967 // so, we should be able to simplify this further. 1968 const SCEV *X = ST->getOperand(); 1969 ConstantRange CR = getSignedRange(X); 1970 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1971 unsigned NewBits = getTypeSizeInBits(Ty); 1972 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1973 CR.sextOrTrunc(NewBits))) 1974 return getTruncateOrSignExtend(X, Ty, Depth); 1975 } 1976 1977 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1978 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1979 if (SA->hasNoSignedWrap()) { 1980 // If the addition does not sign overflow then we can, by definition, 1981 // commute the sign extension with the addition operation. 1982 SmallVector<const SCEV *, 4> Ops; 1983 for (const auto *Op : SA->operands()) 1984 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1985 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1986 } 1987 1988 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1989 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1990 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1991 // 1992 // For instance, this will bring two seemingly different expressions: 1993 // 1 + sext(5 + 20 * %x + 24 * %y) and 1994 // sext(6 + 20 * %x + 24 * %y) 1995 // to the same form: 1996 // 2 + sext(4 + 20 * %x + 24 * %y) 1997 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1998 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1999 if (D != 0) { 2000 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2001 const SCEV *SResidual = 2002 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 2003 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2004 return getAddExpr(SSExtD, SSExtR, 2005 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2006 Depth + 1); 2007 } 2008 } 2009 } 2010 // If the input value is a chrec scev, and we can prove that the value 2011 // did not overflow the old, smaller, value, we can sign extend all of the 2012 // operands (often constants). This allows analysis of something like 2013 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 2014 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 2015 if (AR->isAffine()) { 2016 const SCEV *Start = AR->getStart(); 2017 const SCEV *Step = AR->getStepRecurrence(*this); 2018 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 2019 const Loop *L = AR->getLoop(); 2020 2021 if (!AR->hasNoSignedWrap()) { 2022 auto NewFlags = proveNoWrapViaConstantRanges(AR); 2023 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 2024 } 2025 2026 // If we have special knowledge that this addrec won't overflow, 2027 // we don't need to do any further analysis. 2028 if (AR->hasNoSignedWrap()) 2029 return getAddRecExpr( 2030 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2031 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 2032 2033 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2034 // Note that this serves two purposes: It filters out loops that are 2035 // simply not analyzable, and it covers the case where this code is 2036 // being called from within backedge-taken count analysis, such that 2037 // attempting to ask for the backedge-taken count would likely result 2038 // in infinite recursion. In the later case, the analysis code will 2039 // cope with a conservative value, and it will take care to purge 2040 // that value once it has finished. 2041 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 2042 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2043 // Manually compute the final value for AR, checking for 2044 // overflow. 2045 2046 // Check whether the backedge-taken count can be losslessly casted to 2047 // the addrec's type. The count is always unsigned. 2048 const SCEV *CastedMaxBECount = 2049 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2050 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2051 CastedMaxBECount, MaxBECount->getType(), Depth); 2052 if (MaxBECount == RecastedMaxBECount) { 2053 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2054 // Check whether Start+Step*MaxBECount has no signed overflow. 2055 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2056 SCEV::FlagAnyWrap, Depth + 1); 2057 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2058 SCEV::FlagAnyWrap, 2059 Depth + 1), 2060 WideTy, Depth + 1); 2061 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2062 const SCEV *WideMaxBECount = 2063 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2064 const SCEV *OperandExtendedAdd = 2065 getAddExpr(WideStart, 2066 getMulExpr(WideMaxBECount, 2067 getSignExtendExpr(Step, WideTy, Depth + 1), 2068 SCEV::FlagAnyWrap, Depth + 1), 2069 SCEV::FlagAnyWrap, Depth + 1); 2070 if (SAdd == OperandExtendedAdd) { 2071 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2072 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2073 // Return the expression with the addrec on the outside. 2074 return getAddRecExpr( 2075 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2076 Depth + 1), 2077 getSignExtendExpr(Step, Ty, Depth + 1), L, 2078 AR->getNoWrapFlags()); 2079 } 2080 // Similar to above, only this time treat the step value as unsigned. 2081 // This covers loops that count up with an unsigned step. 2082 OperandExtendedAdd = 2083 getAddExpr(WideStart, 2084 getMulExpr(WideMaxBECount, 2085 getZeroExtendExpr(Step, WideTy, Depth + 1), 2086 SCEV::FlagAnyWrap, Depth + 1), 2087 SCEV::FlagAnyWrap, Depth + 1); 2088 if (SAdd == OperandExtendedAdd) { 2089 // If AR wraps around then 2090 // 2091 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2092 // => SAdd != OperandExtendedAdd 2093 // 2094 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2095 // (SAdd == OperandExtendedAdd => AR is NW) 2096 2097 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2098 2099 // Return the expression with the addrec on the outside. 2100 return getAddRecExpr( 2101 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2102 Depth + 1), 2103 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2104 AR->getNoWrapFlags()); 2105 } 2106 } 2107 } 2108 2109 // Normally, in the cases we can prove no-overflow via a 2110 // backedge guarding condition, we can also compute a backedge 2111 // taken count for the loop. The exceptions are assumptions and 2112 // guards present in the loop -- SCEV is not great at exploiting 2113 // these to compute max backedge taken counts, but can still use 2114 // these to prove lack of overflow. Use this fact to avoid 2115 // doing extra work that may not pay off. 2116 2117 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2118 !AC.assumptions().empty()) { 2119 // If the backedge is guarded by a comparison with the pre-inc 2120 // value the addrec is safe. Also, if the entry is guarded by 2121 // a comparison with the start value and the backedge is 2122 // guarded by a comparison with the post-inc value, the addrec 2123 // is safe. 2124 ICmpInst::Predicate Pred; 2125 const SCEV *OverflowLimit = 2126 getSignedOverflowLimitForStep(Step, &Pred, this); 2127 if (OverflowLimit && 2128 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2129 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2130 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2131 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2132 return getAddRecExpr( 2133 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2134 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2135 } 2136 } 2137 2138 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2139 // if D + (C - D + Step * n) could be proven to not signed wrap 2140 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2141 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2142 const APInt &C = SC->getAPInt(); 2143 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2144 if (D != 0) { 2145 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2146 const SCEV *SResidual = 2147 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2148 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2149 return getAddExpr(SSExtD, SSExtR, 2150 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2151 Depth + 1); 2152 } 2153 } 2154 2155 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2156 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2157 return getAddRecExpr( 2158 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2159 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2160 } 2161 } 2162 2163 // If the input value is provably positive and we could not simplify 2164 // away the sext build a zext instead. 2165 if (isKnownNonNegative(Op)) 2166 return getZeroExtendExpr(Op, Ty, Depth + 1); 2167 2168 // The cast wasn't folded; create an explicit cast node. 2169 // Recompute the insert position, as it may have been invalidated. 2170 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2171 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2172 Op, Ty); 2173 UniqueSCEVs.InsertNode(S, IP); 2174 addToLoopUseLists(S); 2175 return S; 2176 } 2177 2178 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2179 /// unspecified bits out to the given type. 2180 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2181 Type *Ty) { 2182 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2183 "This is not an extending conversion!"); 2184 assert(isSCEVable(Ty) && 2185 "This is not a conversion to a SCEVable type!"); 2186 Ty = getEffectiveSCEVType(Ty); 2187 2188 // Sign-extend negative constants. 2189 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2190 if (SC->getAPInt().isNegative()) 2191 return getSignExtendExpr(Op, Ty); 2192 2193 // Peel off a truncate cast. 2194 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2195 const SCEV *NewOp = T->getOperand(); 2196 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2197 return getAnyExtendExpr(NewOp, Ty); 2198 return getTruncateOrNoop(NewOp, Ty); 2199 } 2200 2201 // Next try a zext cast. If the cast is folded, use it. 2202 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2203 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2204 return ZExt; 2205 2206 // Next try a sext cast. If the cast is folded, use it. 2207 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2208 if (!isa<SCEVSignExtendExpr>(SExt)) 2209 return SExt; 2210 2211 // Force the cast to be folded into the operands of an addrec. 2212 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2213 SmallVector<const SCEV *, 4> Ops; 2214 for (const SCEV *Op : AR->operands()) 2215 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2216 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2217 } 2218 2219 // If the expression is obviously signed, use the sext cast value. 2220 if (isa<SCEVSMaxExpr>(Op)) 2221 return SExt; 2222 2223 // Absent any other information, use the zext cast value. 2224 return ZExt; 2225 } 2226 2227 /// Process the given Ops list, which is a list of operands to be added under 2228 /// the given scale, update the given map. This is a helper function for 2229 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2230 /// that would form an add expression like this: 2231 /// 2232 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2233 /// 2234 /// where A and B are constants, update the map with these values: 2235 /// 2236 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2237 /// 2238 /// and add 13 + A*B*29 to AccumulatedConstant. 2239 /// This will allow getAddRecExpr to produce this: 2240 /// 2241 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2242 /// 2243 /// This form often exposes folding opportunities that are hidden in 2244 /// the original operand list. 2245 /// 2246 /// Return true iff it appears that any interesting folding opportunities 2247 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2248 /// the common case where no interesting opportunities are present, and 2249 /// is also used as a check to avoid infinite recursion. 2250 static bool 2251 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2252 SmallVectorImpl<const SCEV *> &NewOps, 2253 APInt &AccumulatedConstant, 2254 const SCEV *const *Ops, size_t NumOperands, 2255 const APInt &Scale, 2256 ScalarEvolution &SE) { 2257 bool Interesting = false; 2258 2259 // Iterate over the add operands. They are sorted, with constants first. 2260 unsigned i = 0; 2261 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2262 ++i; 2263 // Pull a buried constant out to the outside. 2264 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2265 Interesting = true; 2266 AccumulatedConstant += Scale * C->getAPInt(); 2267 } 2268 2269 // Next comes everything else. We're especially interested in multiplies 2270 // here, but they're in the middle, so just visit the rest with one loop. 2271 for (; i != NumOperands; ++i) { 2272 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2273 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2274 APInt NewScale = 2275 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2276 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2277 // A multiplication of a constant with another add; recurse. 2278 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2279 Interesting |= 2280 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2281 Add->op_begin(), Add->getNumOperands(), 2282 NewScale, SE); 2283 } else { 2284 // A multiplication of a constant with some other value. Update 2285 // the map. 2286 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2287 const SCEV *Key = SE.getMulExpr(MulOps); 2288 auto Pair = M.insert({Key, NewScale}); 2289 if (Pair.second) { 2290 NewOps.push_back(Pair.first->first); 2291 } else { 2292 Pair.first->second += NewScale; 2293 // The map already had an entry for this value, which may indicate 2294 // a folding opportunity. 2295 Interesting = true; 2296 } 2297 } 2298 } else { 2299 // An ordinary operand. Update the map. 2300 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2301 M.insert({Ops[i], Scale}); 2302 if (Pair.second) { 2303 NewOps.push_back(Pair.first->first); 2304 } else { 2305 Pair.first->second += Scale; 2306 // The map already had an entry for this value, which may indicate 2307 // a folding opportunity. 2308 Interesting = true; 2309 } 2310 } 2311 } 2312 2313 return Interesting; 2314 } 2315 2316 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2317 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2318 // can't-overflow flags for the operation if possible. 2319 static SCEV::NoWrapFlags 2320 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2321 const ArrayRef<const SCEV *> Ops, 2322 SCEV::NoWrapFlags Flags) { 2323 using namespace std::placeholders; 2324 2325 using OBO = OverflowingBinaryOperator; 2326 2327 bool CanAnalyze = 2328 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2329 (void)CanAnalyze; 2330 assert(CanAnalyze && "don't call from other places!"); 2331 2332 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2333 SCEV::NoWrapFlags SignOrUnsignWrap = 2334 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2335 2336 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2337 auto IsKnownNonNegative = [&](const SCEV *S) { 2338 return SE->isKnownNonNegative(S); 2339 }; 2340 2341 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2342 Flags = 2343 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2344 2345 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2346 2347 if (SignOrUnsignWrap != SignOrUnsignMask && 2348 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2349 isa<SCEVConstant>(Ops[0])) { 2350 2351 auto Opcode = [&] { 2352 switch (Type) { 2353 case scAddExpr: 2354 return Instruction::Add; 2355 case scMulExpr: 2356 return Instruction::Mul; 2357 default: 2358 llvm_unreachable("Unexpected SCEV op."); 2359 } 2360 }(); 2361 2362 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2363 2364 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2365 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2366 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2367 Opcode, C, OBO::NoSignedWrap); 2368 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2369 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2370 } 2371 2372 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2373 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2374 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2375 Opcode, C, OBO::NoUnsignedWrap); 2376 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2377 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2378 } 2379 } 2380 2381 return Flags; 2382 } 2383 2384 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2385 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2386 } 2387 2388 /// Get a canonical add expression, or something simpler if possible. 2389 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2390 SCEV::NoWrapFlags Flags, 2391 unsigned Depth) { 2392 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2393 "only nuw or nsw allowed"); 2394 assert(!Ops.empty() && "Cannot get empty add!"); 2395 if (Ops.size() == 1) return Ops[0]; 2396 #ifndef NDEBUG 2397 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2398 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2399 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2400 "SCEVAddExpr operand types don't match!"); 2401 #endif 2402 2403 // Sort by complexity, this groups all similar expression types together. 2404 GroupByComplexity(Ops, &LI, DT); 2405 2406 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2407 2408 // If there are any constants, fold them together. 2409 unsigned Idx = 0; 2410 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2411 ++Idx; 2412 assert(Idx < Ops.size()); 2413 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2414 // We found two constants, fold them together! 2415 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2416 if (Ops.size() == 2) return Ops[0]; 2417 Ops.erase(Ops.begin()+1); // Erase the folded element 2418 LHSC = cast<SCEVConstant>(Ops[0]); 2419 } 2420 2421 // If we are left with a constant zero being added, strip it off. 2422 if (LHSC->getValue()->isZero()) { 2423 Ops.erase(Ops.begin()); 2424 --Idx; 2425 } 2426 2427 if (Ops.size() == 1) return Ops[0]; 2428 } 2429 2430 // Limit recursion calls depth. 2431 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2432 return getOrCreateAddExpr(Ops, Flags); 2433 2434 // Okay, check to see if the same value occurs in the operand list more than 2435 // once. If so, merge them together into an multiply expression. Since we 2436 // sorted the list, these values are required to be adjacent. 2437 Type *Ty = Ops[0]->getType(); 2438 bool FoundMatch = false; 2439 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2440 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2441 // Scan ahead to count how many equal operands there are. 2442 unsigned Count = 2; 2443 while (i+Count != e && Ops[i+Count] == Ops[i]) 2444 ++Count; 2445 // Merge the values into a multiply. 2446 const SCEV *Scale = getConstant(Ty, Count); 2447 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2448 if (Ops.size() == Count) 2449 return Mul; 2450 Ops[i] = Mul; 2451 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2452 --i; e -= Count - 1; 2453 FoundMatch = true; 2454 } 2455 if (FoundMatch) 2456 return getAddExpr(Ops, Flags, Depth + 1); 2457 2458 // Check for truncates. If all the operands are truncated from the same 2459 // type, see if factoring out the truncate would permit the result to be 2460 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2461 // if the contents of the resulting outer trunc fold to something simple. 2462 auto FindTruncSrcType = [&]() -> Type * { 2463 // We're ultimately looking to fold an addrec of truncs and muls of only 2464 // constants and truncs, so if we find any other types of SCEV 2465 // as operands of the addrec then we bail and return nullptr here. 2466 // Otherwise, we return the type of the operand of a trunc that we find. 2467 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2468 return T->getOperand()->getType(); 2469 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2470 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2471 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2472 return T->getOperand()->getType(); 2473 } 2474 return nullptr; 2475 }; 2476 if (auto *SrcType = FindTruncSrcType()) { 2477 SmallVector<const SCEV *, 8> LargeOps; 2478 bool Ok = true; 2479 // Check all the operands to see if they can be represented in the 2480 // source type of the truncate. 2481 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2482 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2483 if (T->getOperand()->getType() != SrcType) { 2484 Ok = false; 2485 break; 2486 } 2487 LargeOps.push_back(T->getOperand()); 2488 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2489 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2490 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2491 SmallVector<const SCEV *, 8> LargeMulOps; 2492 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2493 if (const SCEVTruncateExpr *T = 2494 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2495 if (T->getOperand()->getType() != SrcType) { 2496 Ok = false; 2497 break; 2498 } 2499 LargeMulOps.push_back(T->getOperand()); 2500 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2501 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2502 } else { 2503 Ok = false; 2504 break; 2505 } 2506 } 2507 if (Ok) 2508 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2509 } else { 2510 Ok = false; 2511 break; 2512 } 2513 } 2514 if (Ok) { 2515 // Evaluate the expression in the larger type. 2516 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2517 // If it folds to something simple, use it. Otherwise, don't. 2518 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2519 return getTruncateExpr(Fold, Ty); 2520 } 2521 } 2522 2523 // Skip past any other cast SCEVs. 2524 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2525 ++Idx; 2526 2527 // If there are add operands they would be next. 2528 if (Idx < Ops.size()) { 2529 bool DeletedAdd = false; 2530 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2531 if (Ops.size() > AddOpsInlineThreshold || 2532 Add->getNumOperands() > AddOpsInlineThreshold) 2533 break; 2534 // If we have an add, expand the add operands onto the end of the operands 2535 // list. 2536 Ops.erase(Ops.begin()+Idx); 2537 Ops.append(Add->op_begin(), Add->op_end()); 2538 DeletedAdd = true; 2539 } 2540 2541 // If we deleted at least one add, we added operands to the end of the list, 2542 // and they are not necessarily sorted. Recurse to resort and resimplify 2543 // any operands we just acquired. 2544 if (DeletedAdd) 2545 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2546 } 2547 2548 // Skip over the add expression until we get to a multiply. 2549 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2550 ++Idx; 2551 2552 // Check to see if there are any folding opportunities present with 2553 // operands multiplied by constant values. 2554 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2555 uint64_t BitWidth = getTypeSizeInBits(Ty); 2556 DenseMap<const SCEV *, APInt> M; 2557 SmallVector<const SCEV *, 8> NewOps; 2558 APInt AccumulatedConstant(BitWidth, 0); 2559 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2560 Ops.data(), Ops.size(), 2561 APInt(BitWidth, 1), *this)) { 2562 struct APIntCompare { 2563 bool operator()(const APInt &LHS, const APInt &RHS) const { 2564 return LHS.ult(RHS); 2565 } 2566 }; 2567 2568 // Some interesting folding opportunity is present, so its worthwhile to 2569 // re-generate the operands list. Group the operands by constant scale, 2570 // to avoid multiplying by the same constant scale multiple times. 2571 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2572 for (const SCEV *NewOp : NewOps) 2573 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2574 // Re-generate the operands list. 2575 Ops.clear(); 2576 if (AccumulatedConstant != 0) 2577 Ops.push_back(getConstant(AccumulatedConstant)); 2578 for (auto &MulOp : MulOpLists) 2579 if (MulOp.first != 0) 2580 Ops.push_back(getMulExpr( 2581 getConstant(MulOp.first), 2582 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2583 SCEV::FlagAnyWrap, Depth + 1)); 2584 if (Ops.empty()) 2585 return getZero(Ty); 2586 if (Ops.size() == 1) 2587 return Ops[0]; 2588 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2589 } 2590 } 2591 2592 // If we are adding something to a multiply expression, make sure the 2593 // something is not already an operand of the multiply. If so, merge it into 2594 // the multiply. 2595 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2596 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2597 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2598 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2599 if (isa<SCEVConstant>(MulOpSCEV)) 2600 continue; 2601 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2602 if (MulOpSCEV == Ops[AddOp]) { 2603 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2604 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2605 if (Mul->getNumOperands() != 2) { 2606 // If the multiply has more than two operands, we must get the 2607 // Y*Z term. 2608 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2609 Mul->op_begin()+MulOp); 2610 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2611 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2612 } 2613 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2614 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2615 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2616 SCEV::FlagAnyWrap, Depth + 1); 2617 if (Ops.size() == 2) return OuterMul; 2618 if (AddOp < Idx) { 2619 Ops.erase(Ops.begin()+AddOp); 2620 Ops.erase(Ops.begin()+Idx-1); 2621 } else { 2622 Ops.erase(Ops.begin()+Idx); 2623 Ops.erase(Ops.begin()+AddOp-1); 2624 } 2625 Ops.push_back(OuterMul); 2626 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2627 } 2628 2629 // Check this multiply against other multiplies being added together. 2630 for (unsigned OtherMulIdx = Idx+1; 2631 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2632 ++OtherMulIdx) { 2633 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2634 // If MulOp occurs in OtherMul, we can fold the two multiplies 2635 // together. 2636 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2637 OMulOp != e; ++OMulOp) 2638 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2639 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2640 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2641 if (Mul->getNumOperands() != 2) { 2642 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2643 Mul->op_begin()+MulOp); 2644 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2645 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2646 } 2647 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2648 if (OtherMul->getNumOperands() != 2) { 2649 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2650 OtherMul->op_begin()+OMulOp); 2651 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2652 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2653 } 2654 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2655 const SCEV *InnerMulSum = 2656 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2657 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2658 SCEV::FlagAnyWrap, Depth + 1); 2659 if (Ops.size() == 2) return OuterMul; 2660 Ops.erase(Ops.begin()+Idx); 2661 Ops.erase(Ops.begin()+OtherMulIdx-1); 2662 Ops.push_back(OuterMul); 2663 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2664 } 2665 } 2666 } 2667 } 2668 2669 // If there are any add recurrences in the operands list, see if any other 2670 // added values are loop invariant. If so, we can fold them into the 2671 // recurrence. 2672 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2673 ++Idx; 2674 2675 // Scan over all recurrences, trying to fold loop invariants into them. 2676 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2677 // Scan all of the other operands to this add and add them to the vector if 2678 // they are loop invariant w.r.t. the recurrence. 2679 SmallVector<const SCEV *, 8> LIOps; 2680 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2681 const Loop *AddRecLoop = AddRec->getLoop(); 2682 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2683 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2684 LIOps.push_back(Ops[i]); 2685 Ops.erase(Ops.begin()+i); 2686 --i; --e; 2687 } 2688 2689 // If we found some loop invariants, fold them into the recurrence. 2690 if (!LIOps.empty()) { 2691 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2692 LIOps.push_back(AddRec->getStart()); 2693 2694 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2695 AddRec->op_end()); 2696 // This follows from the fact that the no-wrap flags on the outer add 2697 // expression are applicable on the 0th iteration, when the add recurrence 2698 // will be equal to its start value. 2699 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2700 2701 // Build the new addrec. Propagate the NUW and NSW flags if both the 2702 // outer add and the inner addrec are guaranteed to have no overflow. 2703 // Always propagate NW. 2704 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2705 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2706 2707 // If all of the other operands were loop invariant, we are done. 2708 if (Ops.size() == 1) return NewRec; 2709 2710 // Otherwise, add the folded AddRec by the non-invariant parts. 2711 for (unsigned i = 0;; ++i) 2712 if (Ops[i] == AddRec) { 2713 Ops[i] = NewRec; 2714 break; 2715 } 2716 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2717 } 2718 2719 // Okay, if there weren't any loop invariants to be folded, check to see if 2720 // there are multiple AddRec's with the same loop induction variable being 2721 // added together. If so, we can fold them. 2722 for (unsigned OtherIdx = Idx+1; 2723 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2724 ++OtherIdx) { 2725 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2726 // so that the 1st found AddRecExpr is dominated by all others. 2727 assert(DT.dominates( 2728 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2729 AddRec->getLoop()->getHeader()) && 2730 "AddRecExprs are not sorted in reverse dominance order?"); 2731 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2732 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2733 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2734 AddRec->op_end()); 2735 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2736 ++OtherIdx) { 2737 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2738 if (OtherAddRec->getLoop() == AddRecLoop) { 2739 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2740 i != e; ++i) { 2741 if (i >= AddRecOps.size()) { 2742 AddRecOps.append(OtherAddRec->op_begin()+i, 2743 OtherAddRec->op_end()); 2744 break; 2745 } 2746 SmallVector<const SCEV *, 2> TwoOps = { 2747 AddRecOps[i], OtherAddRec->getOperand(i)}; 2748 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2749 } 2750 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2751 } 2752 } 2753 // Step size has changed, so we cannot guarantee no self-wraparound. 2754 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2755 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2756 } 2757 } 2758 2759 // Otherwise couldn't fold anything into this recurrence. Move onto the 2760 // next one. 2761 } 2762 2763 // Okay, it looks like we really DO need an add expr. Check to see if we 2764 // already have one, otherwise create a new one. 2765 return getOrCreateAddExpr(Ops, Flags); 2766 } 2767 2768 const SCEV * 2769 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2770 SCEV::NoWrapFlags Flags) { 2771 FoldingSetNodeID ID; 2772 ID.AddInteger(scAddExpr); 2773 for (const SCEV *Op : Ops) 2774 ID.AddPointer(Op); 2775 void *IP = nullptr; 2776 SCEVAddExpr *S = 2777 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2778 if (!S) { 2779 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2780 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2781 S = new (SCEVAllocator) 2782 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2783 UniqueSCEVs.InsertNode(S, IP); 2784 addToLoopUseLists(S); 2785 } 2786 S->setNoWrapFlags(Flags); 2787 return S; 2788 } 2789 2790 const SCEV * 2791 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2792 const Loop *L, SCEV::NoWrapFlags Flags) { 2793 FoldingSetNodeID ID; 2794 ID.AddInteger(scAddRecExpr); 2795 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2796 ID.AddPointer(Ops[i]); 2797 ID.AddPointer(L); 2798 void *IP = nullptr; 2799 SCEVAddRecExpr *S = 2800 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2801 if (!S) { 2802 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2803 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2804 S = new (SCEVAllocator) 2805 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2806 UniqueSCEVs.InsertNode(S, IP); 2807 addToLoopUseLists(S); 2808 } 2809 S->setNoWrapFlags(Flags); 2810 return S; 2811 } 2812 2813 const SCEV * 2814 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2815 SCEV::NoWrapFlags Flags) { 2816 FoldingSetNodeID ID; 2817 ID.AddInteger(scMulExpr); 2818 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2819 ID.AddPointer(Ops[i]); 2820 void *IP = nullptr; 2821 SCEVMulExpr *S = 2822 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2823 if (!S) { 2824 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2825 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2826 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2827 O, Ops.size()); 2828 UniqueSCEVs.InsertNode(S, IP); 2829 addToLoopUseLists(S); 2830 } 2831 S->setNoWrapFlags(Flags); 2832 return S; 2833 } 2834 2835 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2836 uint64_t k = i*j; 2837 if (j > 1 && k / j != i) Overflow = true; 2838 return k; 2839 } 2840 2841 /// Compute the result of "n choose k", the binomial coefficient. If an 2842 /// intermediate computation overflows, Overflow will be set and the return will 2843 /// be garbage. Overflow is not cleared on absence of overflow. 2844 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2845 // We use the multiplicative formula: 2846 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2847 // At each iteration, we take the n-th term of the numeral and divide by the 2848 // (k-n)th term of the denominator. This division will always produce an 2849 // integral result, and helps reduce the chance of overflow in the 2850 // intermediate computations. However, we can still overflow even when the 2851 // final result would fit. 2852 2853 if (n == 0 || n == k) return 1; 2854 if (k > n) return 0; 2855 2856 if (k > n/2) 2857 k = n-k; 2858 2859 uint64_t r = 1; 2860 for (uint64_t i = 1; i <= k; ++i) { 2861 r = umul_ov(r, n-(i-1), Overflow); 2862 r /= i; 2863 } 2864 return r; 2865 } 2866 2867 /// Determine if any of the operands in this SCEV are a constant or if 2868 /// any of the add or multiply expressions in this SCEV contain a constant. 2869 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2870 struct FindConstantInAddMulChain { 2871 bool FoundConstant = false; 2872 2873 bool follow(const SCEV *S) { 2874 FoundConstant |= isa<SCEVConstant>(S); 2875 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2876 } 2877 2878 bool isDone() const { 2879 return FoundConstant; 2880 } 2881 }; 2882 2883 FindConstantInAddMulChain F; 2884 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2885 ST.visitAll(StartExpr); 2886 return F.FoundConstant; 2887 } 2888 2889 /// Get a canonical multiply expression, or something simpler if possible. 2890 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2891 SCEV::NoWrapFlags Flags, 2892 unsigned Depth) { 2893 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2894 "only nuw or nsw allowed"); 2895 assert(!Ops.empty() && "Cannot get empty mul!"); 2896 if (Ops.size() == 1) return Ops[0]; 2897 #ifndef NDEBUG 2898 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2899 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2900 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2901 "SCEVMulExpr operand types don't match!"); 2902 #endif 2903 2904 // Sort by complexity, this groups all similar expression types together. 2905 GroupByComplexity(Ops, &LI, DT); 2906 2907 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2908 2909 // Limit recursion calls depth. 2910 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2911 return getOrCreateMulExpr(Ops, Flags); 2912 2913 // If there are any constants, fold them together. 2914 unsigned Idx = 0; 2915 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2916 2917 if (Ops.size() == 2) 2918 // C1*(C2+V) -> C1*C2 + C1*V 2919 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2920 // If any of Add's ops are Adds or Muls with a constant, apply this 2921 // transformation as well. 2922 // 2923 // TODO: There are some cases where this transformation is not 2924 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2925 // this transformation should be narrowed down. 2926 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2927 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2928 SCEV::FlagAnyWrap, Depth + 1), 2929 getMulExpr(LHSC, Add->getOperand(1), 2930 SCEV::FlagAnyWrap, Depth + 1), 2931 SCEV::FlagAnyWrap, Depth + 1); 2932 2933 ++Idx; 2934 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2935 // We found two constants, fold them together! 2936 ConstantInt *Fold = 2937 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2938 Ops[0] = getConstant(Fold); 2939 Ops.erase(Ops.begin()+1); // Erase the folded element 2940 if (Ops.size() == 1) return Ops[0]; 2941 LHSC = cast<SCEVConstant>(Ops[0]); 2942 } 2943 2944 // If we are left with a constant one being multiplied, strip it off. 2945 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2946 Ops.erase(Ops.begin()); 2947 --Idx; 2948 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2949 // If we have a multiply of zero, it will always be zero. 2950 return Ops[0]; 2951 } else if (Ops[0]->isAllOnesValue()) { 2952 // If we have a mul by -1 of an add, try distributing the -1 among the 2953 // add operands. 2954 if (Ops.size() == 2) { 2955 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2956 SmallVector<const SCEV *, 4> NewOps; 2957 bool AnyFolded = false; 2958 for (const SCEV *AddOp : Add->operands()) { 2959 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2960 Depth + 1); 2961 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2962 NewOps.push_back(Mul); 2963 } 2964 if (AnyFolded) 2965 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2966 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2967 // Negation preserves a recurrence's no self-wrap property. 2968 SmallVector<const SCEV *, 4> Operands; 2969 for (const SCEV *AddRecOp : AddRec->operands()) 2970 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2971 Depth + 1)); 2972 2973 return getAddRecExpr(Operands, AddRec->getLoop(), 2974 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2975 } 2976 } 2977 } 2978 2979 if (Ops.size() == 1) 2980 return Ops[0]; 2981 } 2982 2983 // Skip over the add expression until we get to a multiply. 2984 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2985 ++Idx; 2986 2987 // If there are mul operands inline them all into this expression. 2988 if (Idx < Ops.size()) { 2989 bool DeletedMul = false; 2990 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2991 if (Ops.size() > MulOpsInlineThreshold) 2992 break; 2993 // If we have an mul, expand the mul operands onto the end of the 2994 // operands list. 2995 Ops.erase(Ops.begin()+Idx); 2996 Ops.append(Mul->op_begin(), Mul->op_end()); 2997 DeletedMul = true; 2998 } 2999 3000 // If we deleted at least one mul, we added operands to the end of the 3001 // list, and they are not necessarily sorted. Recurse to resort and 3002 // resimplify any operands we just acquired. 3003 if (DeletedMul) 3004 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3005 } 3006 3007 // If there are any add recurrences in the operands list, see if any other 3008 // added values are loop invariant. If so, we can fold them into the 3009 // recurrence. 3010 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3011 ++Idx; 3012 3013 // Scan over all recurrences, trying to fold loop invariants into them. 3014 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3015 // Scan all of the other operands to this mul and add them to the vector 3016 // if they are loop invariant w.r.t. the recurrence. 3017 SmallVector<const SCEV *, 8> LIOps; 3018 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3019 const Loop *AddRecLoop = AddRec->getLoop(); 3020 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3021 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3022 LIOps.push_back(Ops[i]); 3023 Ops.erase(Ops.begin()+i); 3024 --i; --e; 3025 } 3026 3027 // If we found some loop invariants, fold them into the recurrence. 3028 if (!LIOps.empty()) { 3029 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3030 SmallVector<const SCEV *, 4> NewOps; 3031 NewOps.reserve(AddRec->getNumOperands()); 3032 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3033 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3034 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3035 SCEV::FlagAnyWrap, Depth + 1)); 3036 3037 // Build the new addrec. Propagate the NUW and NSW flags if both the 3038 // outer mul and the inner addrec are guaranteed to have no overflow. 3039 // 3040 // No self-wrap cannot be guaranteed after changing the step size, but 3041 // will be inferred if either NUW or NSW is true. 3042 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 3043 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 3044 3045 // If all of the other operands were loop invariant, we are done. 3046 if (Ops.size() == 1) return NewRec; 3047 3048 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3049 for (unsigned i = 0;; ++i) 3050 if (Ops[i] == AddRec) { 3051 Ops[i] = NewRec; 3052 break; 3053 } 3054 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3055 } 3056 3057 // Okay, if there weren't any loop invariants to be folded, check to see 3058 // if there are multiple AddRec's with the same loop induction variable 3059 // being multiplied together. If so, we can fold them. 3060 3061 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3062 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3063 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3064 // ]]],+,...up to x=2n}. 3065 // Note that the arguments to choose() are always integers with values 3066 // known at compile time, never SCEV objects. 3067 // 3068 // The implementation avoids pointless extra computations when the two 3069 // addrec's are of different length (mathematically, it's equivalent to 3070 // an infinite stream of zeros on the right). 3071 bool OpsModified = false; 3072 for (unsigned OtherIdx = Idx+1; 3073 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3074 ++OtherIdx) { 3075 const SCEVAddRecExpr *OtherAddRec = 3076 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3077 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3078 continue; 3079 3080 // Limit max number of arguments to avoid creation of unreasonably big 3081 // SCEVAddRecs with very complex operands. 3082 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3083 MaxAddRecSize || isHugeExpression(AddRec) || 3084 isHugeExpression(OtherAddRec)) 3085 continue; 3086 3087 bool Overflow = false; 3088 Type *Ty = AddRec->getType(); 3089 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3090 SmallVector<const SCEV*, 7> AddRecOps; 3091 for (int x = 0, xe = AddRec->getNumOperands() + 3092 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3093 SmallVector <const SCEV *, 7> SumOps; 3094 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3095 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3096 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3097 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3098 z < ze && !Overflow; ++z) { 3099 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3100 uint64_t Coeff; 3101 if (LargerThan64Bits) 3102 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3103 else 3104 Coeff = Coeff1*Coeff2; 3105 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3106 const SCEV *Term1 = AddRec->getOperand(y-z); 3107 const SCEV *Term2 = OtherAddRec->getOperand(z); 3108 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3109 SCEV::FlagAnyWrap, Depth + 1)); 3110 } 3111 } 3112 if (SumOps.empty()) 3113 SumOps.push_back(getZero(Ty)); 3114 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3115 } 3116 if (!Overflow) { 3117 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3118 SCEV::FlagAnyWrap); 3119 if (Ops.size() == 2) return NewAddRec; 3120 Ops[Idx] = NewAddRec; 3121 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3122 OpsModified = true; 3123 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3124 if (!AddRec) 3125 break; 3126 } 3127 } 3128 if (OpsModified) 3129 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3130 3131 // Otherwise couldn't fold anything into this recurrence. Move onto the 3132 // next one. 3133 } 3134 3135 // Okay, it looks like we really DO need an mul expr. Check to see if we 3136 // already have one, otherwise create a new one. 3137 return getOrCreateMulExpr(Ops, Flags); 3138 } 3139 3140 /// Represents an unsigned remainder expression based on unsigned division. 3141 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3142 const SCEV *RHS) { 3143 assert(getEffectiveSCEVType(LHS->getType()) == 3144 getEffectiveSCEVType(RHS->getType()) && 3145 "SCEVURemExpr operand types don't match!"); 3146 3147 // Short-circuit easy cases 3148 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3149 // If constant is one, the result is trivial 3150 if (RHSC->getValue()->isOne()) 3151 return getZero(LHS->getType()); // X urem 1 --> 0 3152 3153 // If constant is a power of two, fold into a zext(trunc(LHS)). 3154 if (RHSC->getAPInt().isPowerOf2()) { 3155 Type *FullTy = LHS->getType(); 3156 Type *TruncTy = 3157 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3158 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3159 } 3160 } 3161 3162 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3163 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3164 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3165 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3166 } 3167 3168 /// Get a canonical unsigned division expression, or something simpler if 3169 /// possible. 3170 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3171 const SCEV *RHS) { 3172 assert(getEffectiveSCEVType(LHS->getType()) == 3173 getEffectiveSCEVType(RHS->getType()) && 3174 "SCEVUDivExpr operand types don't match!"); 3175 3176 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3177 if (RHSC->getValue()->isOne()) 3178 return LHS; // X udiv 1 --> x 3179 // If the denominator is zero, the result of the udiv is undefined. Don't 3180 // try to analyze it, because the resolution chosen here may differ from 3181 // the resolution chosen in other parts of the compiler. 3182 if (!RHSC->getValue()->isZero()) { 3183 // Determine if the division can be folded into the operands of 3184 // its operands. 3185 // TODO: Generalize this to non-constants by using known-bits information. 3186 Type *Ty = LHS->getType(); 3187 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3188 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3189 // For non-power-of-two values, effectively round the value up to the 3190 // nearest power of two. 3191 if (!RHSC->getAPInt().isPowerOf2()) 3192 ++MaxShiftAmt; 3193 IntegerType *ExtTy = 3194 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3195 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3196 if (const SCEVConstant *Step = 3197 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3198 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3199 const APInt &StepInt = Step->getAPInt(); 3200 const APInt &DivInt = RHSC->getAPInt(); 3201 if (!StepInt.urem(DivInt) && 3202 getZeroExtendExpr(AR, ExtTy) == 3203 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3204 getZeroExtendExpr(Step, ExtTy), 3205 AR->getLoop(), SCEV::FlagAnyWrap)) { 3206 SmallVector<const SCEV *, 4> Operands; 3207 for (const SCEV *Op : AR->operands()) 3208 Operands.push_back(getUDivExpr(Op, RHS)); 3209 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3210 } 3211 /// Get a canonical UDivExpr for a recurrence. 3212 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3213 // We can currently only fold X%N if X is constant. 3214 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3215 if (StartC && !DivInt.urem(StepInt) && 3216 getZeroExtendExpr(AR, ExtTy) == 3217 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3218 getZeroExtendExpr(Step, ExtTy), 3219 AR->getLoop(), SCEV::FlagAnyWrap)) { 3220 const APInt &StartInt = StartC->getAPInt(); 3221 const APInt &StartRem = StartInt.urem(StepInt); 3222 if (StartRem != 0) 3223 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3224 AR->getLoop(), SCEV::FlagNW); 3225 } 3226 } 3227 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3228 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3229 SmallVector<const SCEV *, 4> Operands; 3230 for (const SCEV *Op : M->operands()) 3231 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3232 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3233 // Find an operand that's safely divisible. 3234 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3235 const SCEV *Op = M->getOperand(i); 3236 const SCEV *Div = getUDivExpr(Op, RHSC); 3237 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3238 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3239 M->op_end()); 3240 Operands[i] = Div; 3241 return getMulExpr(Operands); 3242 } 3243 } 3244 } 3245 3246 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3247 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3248 if (auto *DivisorConstant = 3249 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3250 bool Overflow = false; 3251 APInt NewRHS = 3252 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3253 if (Overflow) { 3254 return getConstant(RHSC->getType(), 0, false); 3255 } 3256 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3257 } 3258 } 3259 3260 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3261 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3262 SmallVector<const SCEV *, 4> Operands; 3263 for (const SCEV *Op : A->operands()) 3264 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3265 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3266 Operands.clear(); 3267 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3268 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3269 if (isa<SCEVUDivExpr>(Op) || 3270 getMulExpr(Op, RHS) != A->getOperand(i)) 3271 break; 3272 Operands.push_back(Op); 3273 } 3274 if (Operands.size() == A->getNumOperands()) 3275 return getAddExpr(Operands); 3276 } 3277 } 3278 3279 // Fold if both operands are constant. 3280 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3281 Constant *LHSCV = LHSC->getValue(); 3282 Constant *RHSCV = RHSC->getValue(); 3283 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3284 RHSCV))); 3285 } 3286 } 3287 } 3288 3289 FoldingSetNodeID ID; 3290 ID.AddInteger(scUDivExpr); 3291 ID.AddPointer(LHS); 3292 ID.AddPointer(RHS); 3293 void *IP = nullptr; 3294 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3295 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3296 LHS, RHS); 3297 UniqueSCEVs.InsertNode(S, IP); 3298 addToLoopUseLists(S); 3299 return S; 3300 } 3301 3302 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3303 APInt A = C1->getAPInt().abs(); 3304 APInt B = C2->getAPInt().abs(); 3305 uint32_t ABW = A.getBitWidth(); 3306 uint32_t BBW = B.getBitWidth(); 3307 3308 if (ABW > BBW) 3309 B = B.zext(ABW); 3310 else if (ABW < BBW) 3311 A = A.zext(BBW); 3312 3313 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3314 } 3315 3316 /// Get a canonical unsigned division expression, or something simpler if 3317 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3318 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3319 /// it's not exact because the udiv may be clearing bits. 3320 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3321 const SCEV *RHS) { 3322 // TODO: we could try to find factors in all sorts of things, but for now we 3323 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3324 // end of this file for inspiration. 3325 3326 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3327 if (!Mul || !Mul->hasNoUnsignedWrap()) 3328 return getUDivExpr(LHS, RHS); 3329 3330 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3331 // If the mulexpr multiplies by a constant, then that constant must be the 3332 // first element of the mulexpr. 3333 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3334 if (LHSCst == RHSCst) { 3335 SmallVector<const SCEV *, 2> Operands; 3336 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3337 return getMulExpr(Operands); 3338 } 3339 3340 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3341 // that there's a factor provided by one of the other terms. We need to 3342 // check. 3343 APInt Factor = gcd(LHSCst, RHSCst); 3344 if (!Factor.isIntN(1)) { 3345 LHSCst = 3346 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3347 RHSCst = 3348 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3349 SmallVector<const SCEV *, 2> Operands; 3350 Operands.push_back(LHSCst); 3351 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3352 LHS = getMulExpr(Operands); 3353 RHS = RHSCst; 3354 Mul = dyn_cast<SCEVMulExpr>(LHS); 3355 if (!Mul) 3356 return getUDivExactExpr(LHS, RHS); 3357 } 3358 } 3359 } 3360 3361 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3362 if (Mul->getOperand(i) == RHS) { 3363 SmallVector<const SCEV *, 2> Operands; 3364 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3365 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3366 return getMulExpr(Operands); 3367 } 3368 } 3369 3370 return getUDivExpr(LHS, RHS); 3371 } 3372 3373 /// Get an add recurrence expression for the specified loop. Simplify the 3374 /// expression as much as possible. 3375 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3376 const Loop *L, 3377 SCEV::NoWrapFlags Flags) { 3378 SmallVector<const SCEV *, 4> Operands; 3379 Operands.push_back(Start); 3380 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3381 if (StepChrec->getLoop() == L) { 3382 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3383 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3384 } 3385 3386 Operands.push_back(Step); 3387 return getAddRecExpr(Operands, L, Flags); 3388 } 3389 3390 /// Get an add recurrence expression for the specified loop. Simplify the 3391 /// expression as much as possible. 3392 const SCEV * 3393 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3394 const Loop *L, SCEV::NoWrapFlags Flags) { 3395 if (Operands.size() == 1) return Operands[0]; 3396 #ifndef NDEBUG 3397 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3398 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3399 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3400 "SCEVAddRecExpr operand types don't match!"); 3401 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3402 assert(isLoopInvariant(Operands[i], L) && 3403 "SCEVAddRecExpr operand is not loop-invariant!"); 3404 #endif 3405 3406 if (Operands.back()->isZero()) { 3407 Operands.pop_back(); 3408 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3409 } 3410 3411 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3412 // use that information to infer NUW and NSW flags. However, computing a 3413 // BE count requires calling getAddRecExpr, so we may not yet have a 3414 // meaningful BE count at this point (and if we don't, we'd be stuck 3415 // with a SCEVCouldNotCompute as the cached BE count). 3416 3417 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3418 3419 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3420 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3421 const Loop *NestedLoop = NestedAR->getLoop(); 3422 if (L->contains(NestedLoop) 3423 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3424 : (!NestedLoop->contains(L) && 3425 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3426 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3427 NestedAR->op_end()); 3428 Operands[0] = NestedAR->getStart(); 3429 // AddRecs require their operands be loop-invariant with respect to their 3430 // loops. Don't perform this transformation if it would break this 3431 // requirement. 3432 bool AllInvariant = all_of( 3433 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3434 3435 if (AllInvariant) { 3436 // Create a recurrence for the outer loop with the same step size. 3437 // 3438 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3439 // inner recurrence has the same property. 3440 SCEV::NoWrapFlags OuterFlags = 3441 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3442 3443 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3444 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3445 return isLoopInvariant(Op, NestedLoop); 3446 }); 3447 3448 if (AllInvariant) { 3449 // Ok, both add recurrences are valid after the transformation. 3450 // 3451 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3452 // the outer recurrence has the same property. 3453 SCEV::NoWrapFlags InnerFlags = 3454 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3455 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3456 } 3457 } 3458 // Reset Operands to its original state. 3459 Operands[0] = NestedAR; 3460 } 3461 } 3462 3463 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3464 // already have one, otherwise create a new one. 3465 return getOrCreateAddRecExpr(Operands, L, Flags); 3466 } 3467 3468 const SCEV * 3469 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3470 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3471 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3472 // getSCEV(Base)->getType() has the same address space as Base->getType() 3473 // because SCEV::getType() preserves the address space. 3474 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3475 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3476 // instruction to its SCEV, because the Instruction may be guarded by control 3477 // flow and the no-overflow bits may not be valid for the expression in any 3478 // context. This can be fixed similarly to how these flags are handled for 3479 // adds. 3480 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3481 : SCEV::FlagAnyWrap; 3482 3483 const SCEV *TotalOffset = getZero(IntPtrTy); 3484 // The array size is unimportant. The first thing we do on CurTy is getting 3485 // its element type. 3486 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3487 for (const SCEV *IndexExpr : IndexExprs) { 3488 // Compute the (potentially symbolic) offset in bytes for this index. 3489 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3490 // For a struct, add the member offset. 3491 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3492 unsigned FieldNo = Index->getZExtValue(); 3493 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3494 3495 // Add the field offset to the running total offset. 3496 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3497 3498 // Update CurTy to the type of the field at Index. 3499 CurTy = STy->getTypeAtIndex(Index); 3500 } else { 3501 // Update CurTy to its element type. 3502 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3503 // For an array, add the element offset, explicitly scaled. 3504 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3505 // Getelementptr indices are signed. 3506 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3507 3508 // Multiply the index by the element size to compute the element offset. 3509 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3510 3511 // Add the element offset to the running total offset. 3512 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3513 } 3514 } 3515 3516 // Add the total offset from all the GEP indices to the base. 3517 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3518 } 3519 3520 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3521 const SCEV *RHS) { 3522 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3523 return getSMaxExpr(Ops); 3524 } 3525 3526 std::tuple<const SCEV *, FoldingSetNodeID, void *> 3527 ScalarEvolution::findExistingSCEVInCache(int SCEVType, 3528 ArrayRef<const SCEV *> Ops) { 3529 FoldingSetNodeID ID; 3530 void *IP = nullptr; 3531 ID.AddInteger(SCEVType); 3532 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3533 ID.AddPointer(Ops[i]); 3534 return std::tuple<const SCEV *, FoldingSetNodeID, void *>( 3535 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3536 } 3537 3538 const SCEV * 3539 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3540 assert(!Ops.empty() && "Cannot get empty smax!"); 3541 if (Ops.size() == 1) return Ops[0]; 3542 #ifndef NDEBUG 3543 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3544 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3545 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3546 "SCEVSMaxExpr operand types don't match!"); 3547 #endif 3548 3549 // Sort by complexity, this groups all similar expression types together. 3550 GroupByComplexity(Ops, &LI, DT); 3551 3552 // Check if we have created the same SMax expression before. 3553 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(scSMaxExpr, Ops))) { 3554 return S; 3555 } 3556 3557 // If there are any constants, fold them together. 3558 unsigned Idx = 0; 3559 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3560 ++Idx; 3561 assert(Idx < Ops.size()); 3562 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3563 // We found two constants, fold them together! 3564 ConstantInt *Fold = ConstantInt::get( 3565 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3566 Ops[0] = getConstant(Fold); 3567 Ops.erase(Ops.begin()+1); // Erase the folded element 3568 if (Ops.size() == 1) return Ops[0]; 3569 LHSC = cast<SCEVConstant>(Ops[0]); 3570 } 3571 3572 // If we are left with a constant minimum-int, strip it off. 3573 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3574 Ops.erase(Ops.begin()); 3575 --Idx; 3576 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3577 // If we have an smax with a constant maximum-int, it will always be 3578 // maximum-int. 3579 return Ops[0]; 3580 } 3581 3582 if (Ops.size() == 1) return Ops[0]; 3583 } 3584 3585 // Find the first SMax 3586 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3587 ++Idx; 3588 3589 // Check to see if one of the operands is an SMax. If so, expand its operands 3590 // onto our operand list, and recurse to simplify. 3591 if (Idx < Ops.size()) { 3592 bool DeletedSMax = false; 3593 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3594 Ops.erase(Ops.begin()+Idx); 3595 Ops.append(SMax->op_begin(), SMax->op_end()); 3596 DeletedSMax = true; 3597 } 3598 3599 if (DeletedSMax) 3600 return getSMaxExpr(Ops); 3601 } 3602 3603 // Okay, check to see if the same value occurs in the operand list twice. If 3604 // so, delete one. Since we sorted the list, these values are required to 3605 // be adjacent. 3606 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3607 // X smax Y smax Y --> X smax Y 3608 // X smax Y --> X, if X is always greater than Y 3609 if (Ops[i] == Ops[i+1] || 3610 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3611 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3612 --i; --e; 3613 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3614 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3615 --i; --e; 3616 } 3617 3618 if (Ops.size() == 1) return Ops[0]; 3619 3620 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3621 3622 // Okay, it looks like we really DO need an smax expr. Check to see if we 3623 // already have one, otherwise create a new one. 3624 const SCEV *ExistingSCEV; 3625 FoldingSetNodeID ID; 3626 void *IP; 3627 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(scSMaxExpr, Ops); 3628 if (ExistingSCEV) 3629 return ExistingSCEV; 3630 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3631 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3632 SCEV *S = 3633 new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 3634 UniqueSCEVs.InsertNode(S, IP); 3635 addToLoopUseLists(S); 3636 return S; 3637 } 3638 3639 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3640 const SCEV *RHS) { 3641 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3642 return getUMaxExpr(Ops); 3643 } 3644 3645 const SCEV * 3646 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3647 assert(!Ops.empty() && "Cannot get empty umax!"); 3648 if (Ops.size() == 1) return Ops[0]; 3649 #ifndef NDEBUG 3650 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3651 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3652 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3653 "SCEVUMaxExpr operand types don't match!"); 3654 #endif 3655 3656 // Sort by complexity, this groups all similar expression types together. 3657 GroupByComplexity(Ops, &LI, DT); 3658 3659 // Check if we have created the same UMax expression before. 3660 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(scUMaxExpr, Ops))) { 3661 return S; 3662 } 3663 3664 // If there are any constants, fold them together. 3665 unsigned Idx = 0; 3666 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3667 ++Idx; 3668 assert(Idx < Ops.size()); 3669 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3670 // We found two constants, fold them together! 3671 ConstantInt *Fold = ConstantInt::get( 3672 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3673 Ops[0] = getConstant(Fold); 3674 Ops.erase(Ops.begin()+1); // Erase the folded element 3675 if (Ops.size() == 1) return Ops[0]; 3676 LHSC = cast<SCEVConstant>(Ops[0]); 3677 } 3678 3679 // If we are left with a constant minimum-int, strip it off. 3680 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3681 Ops.erase(Ops.begin()); 3682 --Idx; 3683 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3684 // If we have an umax with a constant maximum-int, it will always be 3685 // maximum-int. 3686 return Ops[0]; 3687 } 3688 3689 if (Ops.size() == 1) return Ops[0]; 3690 } 3691 3692 // Find the first UMax 3693 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3694 ++Idx; 3695 3696 // Check to see if one of the operands is a UMax. If so, expand its operands 3697 // onto our operand list, and recurse to simplify. 3698 if (Idx < Ops.size()) { 3699 bool DeletedUMax = false; 3700 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3701 Ops.erase(Ops.begin()+Idx); 3702 Ops.append(UMax->op_begin(), UMax->op_end()); 3703 DeletedUMax = true; 3704 } 3705 3706 if (DeletedUMax) 3707 return getUMaxExpr(Ops); 3708 } 3709 3710 // Okay, check to see if the same value occurs in the operand list twice. If 3711 // so, delete one. Since we sorted the list, these values are required to 3712 // be adjacent. 3713 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3714 // X umax Y umax Y --> X umax Y 3715 // X umax Y --> X, if X is always greater than Y 3716 if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning( 3717 ICmpInst::ICMP_UGE, Ops[i], Ops[i + 1])) { 3718 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3719 --i; --e; 3720 } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, Ops[i], 3721 Ops[i + 1])) { 3722 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3723 --i; --e; 3724 } 3725 3726 if (Ops.size() == 1) return Ops[0]; 3727 3728 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3729 3730 // Okay, it looks like we really DO need a umax expr. Check to see if we 3731 // already have one, otherwise create a new one. 3732 const SCEV *ExistingSCEV; 3733 FoldingSetNodeID ID; 3734 void *IP; 3735 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(scUMaxExpr, Ops); 3736 if (ExistingSCEV) 3737 return ExistingSCEV; 3738 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3739 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3740 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3741 O, Ops.size()); 3742 UniqueSCEVs.InsertNode(S, IP); 3743 addToLoopUseLists(S); 3744 return S; 3745 } 3746 3747 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3748 const SCEV *RHS) { 3749 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3750 return getSMinExpr(Ops); 3751 } 3752 3753 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3754 // ~smax(~x, ~y, ~z) == smin(x, y, z). 3755 SmallVector<const SCEV *, 2> NotOps; 3756 for (auto *S : Ops) 3757 NotOps.push_back(getNotSCEV(S)); 3758 return getNotSCEV(getSMaxExpr(NotOps)); 3759 } 3760 3761 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3762 const SCEV *RHS) { 3763 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3764 return getUMinExpr(Ops); 3765 } 3766 3767 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3768 assert(!Ops.empty() && "At least one operand must be!"); 3769 // Trivial case. 3770 if (Ops.size() == 1) 3771 return Ops[0]; 3772 3773 // ~umax(~x, ~y, ~z) == umin(x, y, z). 3774 SmallVector<const SCEV *, 2> NotOps; 3775 for (auto *S : Ops) 3776 NotOps.push_back(getNotSCEV(S)); 3777 return getNotSCEV(getUMaxExpr(NotOps)); 3778 } 3779 3780 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3781 // We can bypass creating a target-independent 3782 // constant expression and then folding it back into a ConstantInt. 3783 // This is just a compile-time optimization. 3784 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3785 } 3786 3787 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3788 StructType *STy, 3789 unsigned FieldNo) { 3790 // We can bypass creating a target-independent 3791 // constant expression and then folding it back into a ConstantInt. 3792 // This is just a compile-time optimization. 3793 return getConstant( 3794 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3795 } 3796 3797 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3798 // Don't attempt to do anything other than create a SCEVUnknown object 3799 // here. createSCEV only calls getUnknown after checking for all other 3800 // interesting possibilities, and any other code that calls getUnknown 3801 // is doing so in order to hide a value from SCEV canonicalization. 3802 3803 FoldingSetNodeID ID; 3804 ID.AddInteger(scUnknown); 3805 ID.AddPointer(V); 3806 void *IP = nullptr; 3807 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3808 assert(cast<SCEVUnknown>(S)->getValue() == V && 3809 "Stale SCEVUnknown in uniquing map!"); 3810 return S; 3811 } 3812 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3813 FirstUnknown); 3814 FirstUnknown = cast<SCEVUnknown>(S); 3815 UniqueSCEVs.InsertNode(S, IP); 3816 return S; 3817 } 3818 3819 //===----------------------------------------------------------------------===// 3820 // Basic SCEV Analysis and PHI Idiom Recognition Code 3821 // 3822 3823 /// Test if values of the given type are analyzable within the SCEV 3824 /// framework. This primarily includes integer types, and it can optionally 3825 /// include pointer types if the ScalarEvolution class has access to 3826 /// target-specific information. 3827 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3828 // Integers and pointers are always SCEVable. 3829 return Ty->isIntOrPtrTy(); 3830 } 3831 3832 /// Return the size in bits of the specified type, for which isSCEVable must 3833 /// return true. 3834 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3835 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3836 if (Ty->isPointerTy()) 3837 return getDataLayout().getIndexTypeSizeInBits(Ty); 3838 return getDataLayout().getTypeSizeInBits(Ty); 3839 } 3840 3841 /// Return a type with the same bitwidth as the given type and which represents 3842 /// how SCEV will treat the given type, for which isSCEVable must return 3843 /// true. For pointer types, this is the pointer-sized integer type. 3844 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3845 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3846 3847 if (Ty->isIntegerTy()) 3848 return Ty; 3849 3850 // The only other support type is pointer. 3851 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3852 return getDataLayout().getIntPtrType(Ty); 3853 } 3854 3855 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3856 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3857 } 3858 3859 const SCEV *ScalarEvolution::getCouldNotCompute() { 3860 return CouldNotCompute.get(); 3861 } 3862 3863 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3864 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3865 auto *SU = dyn_cast<SCEVUnknown>(S); 3866 return SU && SU->getValue() == nullptr; 3867 }); 3868 3869 return !ContainsNulls; 3870 } 3871 3872 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3873 HasRecMapType::iterator I = HasRecMap.find(S); 3874 if (I != HasRecMap.end()) 3875 return I->second; 3876 3877 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3878 HasRecMap.insert({S, FoundAddRec}); 3879 return FoundAddRec; 3880 } 3881 3882 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3883 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3884 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3885 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3886 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3887 if (!Add) 3888 return {S, nullptr}; 3889 3890 if (Add->getNumOperands() != 2) 3891 return {S, nullptr}; 3892 3893 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3894 if (!ConstOp) 3895 return {S, nullptr}; 3896 3897 return {Add->getOperand(1), ConstOp->getValue()}; 3898 } 3899 3900 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3901 /// by the value and offset from any ValueOffsetPair in the set. 3902 SetVector<ScalarEvolution::ValueOffsetPair> * 3903 ScalarEvolution::getSCEVValues(const SCEV *S) { 3904 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3905 if (SI == ExprValueMap.end()) 3906 return nullptr; 3907 #ifndef NDEBUG 3908 if (VerifySCEVMap) { 3909 // Check there is no dangling Value in the set returned. 3910 for (const auto &VE : SI->second) 3911 assert(ValueExprMap.count(VE.first)); 3912 } 3913 #endif 3914 return &SI->second; 3915 } 3916 3917 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3918 /// cannot be used separately. eraseValueFromMap should be used to remove 3919 /// V from ValueExprMap and ExprValueMap at the same time. 3920 void ScalarEvolution::eraseValueFromMap(Value *V) { 3921 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3922 if (I != ValueExprMap.end()) { 3923 const SCEV *S = I->second; 3924 // Remove {V, 0} from the set of ExprValueMap[S] 3925 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3926 SV->remove({V, nullptr}); 3927 3928 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3929 const SCEV *Stripped; 3930 ConstantInt *Offset; 3931 std::tie(Stripped, Offset) = splitAddExpr(S); 3932 if (Offset != nullptr) { 3933 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3934 SV->remove({V, Offset}); 3935 } 3936 ValueExprMap.erase(V); 3937 } 3938 } 3939 3940 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3941 /// TODO: In reality it is better to check the poison recursively 3942 /// but this is better than nothing. 3943 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3944 if (auto *I = dyn_cast<Instruction>(V)) { 3945 if (isa<OverflowingBinaryOperator>(I)) { 3946 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3947 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3948 return true; 3949 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3950 return true; 3951 } 3952 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3953 return true; 3954 } 3955 return false; 3956 } 3957 3958 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3959 /// create a new one. 3960 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3961 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3962 3963 const SCEV *S = getExistingSCEV(V); 3964 if (S == nullptr) { 3965 S = createSCEV(V); 3966 // During PHI resolution, it is possible to create two SCEVs for the same 3967 // V, so it is needed to double check whether V->S is inserted into 3968 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3969 std::pair<ValueExprMapType::iterator, bool> Pair = 3970 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3971 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3972 ExprValueMap[S].insert({V, nullptr}); 3973 3974 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3975 // ExprValueMap. 3976 const SCEV *Stripped = S; 3977 ConstantInt *Offset = nullptr; 3978 std::tie(Stripped, Offset) = splitAddExpr(S); 3979 // If stripped is SCEVUnknown, don't bother to save 3980 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3981 // increase the complexity of the expansion code. 3982 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3983 // because it may generate add/sub instead of GEP in SCEV expansion. 3984 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3985 !isa<GetElementPtrInst>(V)) 3986 ExprValueMap[Stripped].insert({V, Offset}); 3987 } 3988 } 3989 return S; 3990 } 3991 3992 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3993 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3994 3995 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3996 if (I != ValueExprMap.end()) { 3997 const SCEV *S = I->second; 3998 if (checkValidity(S)) 3999 return S; 4000 eraseValueFromMap(V); 4001 forgetMemoizedResults(S); 4002 } 4003 return nullptr; 4004 } 4005 4006 /// Return a SCEV corresponding to -V = -1*V 4007 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4008 SCEV::NoWrapFlags Flags) { 4009 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4010 return getConstant( 4011 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4012 4013 Type *Ty = V->getType(); 4014 Ty = getEffectiveSCEVType(Ty); 4015 return getMulExpr( 4016 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 4017 } 4018 4019 /// Return a SCEV corresponding to ~V = -1-V 4020 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4021 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4022 return getConstant( 4023 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4024 4025 Type *Ty = V->getType(); 4026 Ty = getEffectiveSCEVType(Ty); 4027 const SCEV *AllOnes = 4028 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 4029 return getMinusSCEV(AllOnes, V); 4030 } 4031 4032 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4033 SCEV::NoWrapFlags Flags, 4034 unsigned Depth) { 4035 // Fast path: X - X --> 0. 4036 if (LHS == RHS) 4037 return getZero(LHS->getType()); 4038 4039 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4040 // makes it so that we cannot make much use of NUW. 4041 auto AddFlags = SCEV::FlagAnyWrap; 4042 const bool RHSIsNotMinSigned = 4043 !getSignedRangeMin(RHS).isMinSignedValue(); 4044 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4045 // Let M be the minimum representable signed value. Then (-1)*RHS 4046 // signed-wraps if and only if RHS is M. That can happen even for 4047 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4048 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4049 // (-1)*RHS, we need to prove that RHS != M. 4050 // 4051 // If LHS is non-negative and we know that LHS - RHS does not 4052 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4053 // either by proving that RHS > M or that LHS >= 0. 4054 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4055 AddFlags = SCEV::FlagNSW; 4056 } 4057 } 4058 4059 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4060 // RHS is NSW and LHS >= 0. 4061 // 4062 // The difficulty here is that the NSW flag may have been proven 4063 // relative to a loop that is to be found in a recurrence in LHS and 4064 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4065 // larger scope than intended. 4066 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4067 4068 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4069 } 4070 4071 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4072 unsigned Depth) { 4073 Type *SrcTy = V->getType(); 4074 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4075 "Cannot truncate or zero extend with non-integer arguments!"); 4076 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4077 return V; // No conversion 4078 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4079 return getTruncateExpr(V, Ty, Depth); 4080 return getZeroExtendExpr(V, Ty, Depth); 4081 } 4082 4083 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4084 unsigned Depth) { 4085 Type *SrcTy = V->getType(); 4086 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4087 "Cannot truncate or zero extend with non-integer arguments!"); 4088 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4089 return V; // No conversion 4090 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4091 return getTruncateExpr(V, Ty, Depth); 4092 return getSignExtendExpr(V, Ty, Depth); 4093 } 4094 4095 const SCEV * 4096 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4097 Type *SrcTy = V->getType(); 4098 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4099 "Cannot noop or zero extend with non-integer arguments!"); 4100 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4101 "getNoopOrZeroExtend cannot truncate!"); 4102 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4103 return V; // No conversion 4104 return getZeroExtendExpr(V, Ty); 4105 } 4106 4107 const SCEV * 4108 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4109 Type *SrcTy = V->getType(); 4110 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4111 "Cannot noop or sign extend with non-integer arguments!"); 4112 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4113 "getNoopOrSignExtend cannot truncate!"); 4114 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4115 return V; // No conversion 4116 return getSignExtendExpr(V, Ty); 4117 } 4118 4119 const SCEV * 4120 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4121 Type *SrcTy = V->getType(); 4122 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4123 "Cannot noop or any extend with non-integer arguments!"); 4124 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4125 "getNoopOrAnyExtend cannot truncate!"); 4126 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4127 return V; // No conversion 4128 return getAnyExtendExpr(V, Ty); 4129 } 4130 4131 const SCEV * 4132 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4133 Type *SrcTy = V->getType(); 4134 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4135 "Cannot truncate or noop with non-integer arguments!"); 4136 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4137 "getTruncateOrNoop cannot extend!"); 4138 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4139 return V; // No conversion 4140 return getTruncateExpr(V, Ty); 4141 } 4142 4143 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4144 const SCEV *RHS) { 4145 const SCEV *PromotedLHS = LHS; 4146 const SCEV *PromotedRHS = RHS; 4147 4148 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4149 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4150 else 4151 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4152 4153 return getUMaxExpr(PromotedLHS, PromotedRHS); 4154 } 4155 4156 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4157 const SCEV *RHS) { 4158 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4159 return getUMinFromMismatchedTypes(Ops); 4160 } 4161 4162 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4163 SmallVectorImpl<const SCEV *> &Ops) { 4164 assert(!Ops.empty() && "At least one operand must be!"); 4165 // Trivial case. 4166 if (Ops.size() == 1) 4167 return Ops[0]; 4168 4169 // Find the max type first. 4170 Type *MaxType = nullptr; 4171 for (auto *S : Ops) 4172 if (MaxType) 4173 MaxType = getWiderType(MaxType, S->getType()); 4174 else 4175 MaxType = S->getType(); 4176 4177 // Extend all ops to max type. 4178 SmallVector<const SCEV *, 2> PromotedOps; 4179 for (auto *S : Ops) 4180 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4181 4182 // Generate umin. 4183 return getUMinExpr(PromotedOps); 4184 } 4185 4186 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4187 // A pointer operand may evaluate to a nonpointer expression, such as null. 4188 if (!V->getType()->isPointerTy()) 4189 return V; 4190 4191 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4192 return getPointerBase(Cast->getOperand()); 4193 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4194 const SCEV *PtrOp = nullptr; 4195 for (const SCEV *NAryOp : NAry->operands()) { 4196 if (NAryOp->getType()->isPointerTy()) { 4197 // Cannot find the base of an expression with multiple pointer operands. 4198 if (PtrOp) 4199 return V; 4200 PtrOp = NAryOp; 4201 } 4202 } 4203 if (!PtrOp) 4204 return V; 4205 return getPointerBase(PtrOp); 4206 } 4207 return V; 4208 } 4209 4210 /// Push users of the given Instruction onto the given Worklist. 4211 static void 4212 PushDefUseChildren(Instruction *I, 4213 SmallVectorImpl<Instruction *> &Worklist) { 4214 // Push the def-use children onto the Worklist stack. 4215 for (User *U : I->users()) 4216 Worklist.push_back(cast<Instruction>(U)); 4217 } 4218 4219 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4220 SmallVector<Instruction *, 16> Worklist; 4221 PushDefUseChildren(PN, Worklist); 4222 4223 SmallPtrSet<Instruction *, 8> Visited; 4224 Visited.insert(PN); 4225 while (!Worklist.empty()) { 4226 Instruction *I = Worklist.pop_back_val(); 4227 if (!Visited.insert(I).second) 4228 continue; 4229 4230 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4231 if (It != ValueExprMap.end()) { 4232 const SCEV *Old = It->second; 4233 4234 // Short-circuit the def-use traversal if the symbolic name 4235 // ceases to appear in expressions. 4236 if (Old != SymName && !hasOperand(Old, SymName)) 4237 continue; 4238 4239 // SCEVUnknown for a PHI either means that it has an unrecognized 4240 // structure, it's a PHI that's in the progress of being computed 4241 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4242 // additional loop trip count information isn't going to change anything. 4243 // In the second case, createNodeForPHI will perform the necessary 4244 // updates on its own when it gets to that point. In the third, we do 4245 // want to forget the SCEVUnknown. 4246 if (!isa<PHINode>(I) || 4247 !isa<SCEVUnknown>(Old) || 4248 (I != PN && Old == SymName)) { 4249 eraseValueFromMap(It->first); 4250 forgetMemoizedResults(Old); 4251 } 4252 } 4253 4254 PushDefUseChildren(I, Worklist); 4255 } 4256 } 4257 4258 namespace { 4259 4260 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4261 /// expression in case its Loop is L. If it is not L then 4262 /// if IgnoreOtherLoops is true then use AddRec itself 4263 /// otherwise rewrite cannot be done. 4264 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4265 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4266 public: 4267 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4268 bool IgnoreOtherLoops = true) { 4269 SCEVInitRewriter Rewriter(L, SE); 4270 const SCEV *Result = Rewriter.visit(S); 4271 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4272 return SE.getCouldNotCompute(); 4273 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4274 ? SE.getCouldNotCompute() 4275 : Result; 4276 } 4277 4278 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4279 if (!SE.isLoopInvariant(Expr, L)) 4280 SeenLoopVariantSCEVUnknown = true; 4281 return Expr; 4282 } 4283 4284 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4285 // Only re-write AddRecExprs for this loop. 4286 if (Expr->getLoop() == L) 4287 return Expr->getStart(); 4288 SeenOtherLoops = true; 4289 return Expr; 4290 } 4291 4292 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4293 4294 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4295 4296 private: 4297 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4298 : SCEVRewriteVisitor(SE), L(L) {} 4299 4300 const Loop *L; 4301 bool SeenLoopVariantSCEVUnknown = false; 4302 bool SeenOtherLoops = false; 4303 }; 4304 4305 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4306 /// increment expression in case its Loop is L. If it is not L then 4307 /// use AddRec itself. 4308 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4309 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4310 public: 4311 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4312 SCEVPostIncRewriter Rewriter(L, SE); 4313 const SCEV *Result = Rewriter.visit(S); 4314 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4315 ? SE.getCouldNotCompute() 4316 : Result; 4317 } 4318 4319 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4320 if (!SE.isLoopInvariant(Expr, L)) 4321 SeenLoopVariantSCEVUnknown = true; 4322 return Expr; 4323 } 4324 4325 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4326 // Only re-write AddRecExprs for this loop. 4327 if (Expr->getLoop() == L) 4328 return Expr->getPostIncExpr(SE); 4329 SeenOtherLoops = true; 4330 return Expr; 4331 } 4332 4333 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4334 4335 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4336 4337 private: 4338 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4339 : SCEVRewriteVisitor(SE), L(L) {} 4340 4341 const Loop *L; 4342 bool SeenLoopVariantSCEVUnknown = false; 4343 bool SeenOtherLoops = false; 4344 }; 4345 4346 /// This class evaluates the compare condition by matching it against the 4347 /// condition of loop latch. If there is a match we assume a true value 4348 /// for the condition while building SCEV nodes. 4349 class SCEVBackedgeConditionFolder 4350 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4351 public: 4352 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4353 ScalarEvolution &SE) { 4354 bool IsPosBECond = false; 4355 Value *BECond = nullptr; 4356 if (BasicBlock *Latch = L->getLoopLatch()) { 4357 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4358 if (BI && BI->isConditional()) { 4359 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4360 "Both outgoing branches should not target same header!"); 4361 BECond = BI->getCondition(); 4362 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4363 } else { 4364 return S; 4365 } 4366 } 4367 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4368 return Rewriter.visit(S); 4369 } 4370 4371 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4372 const SCEV *Result = Expr; 4373 bool InvariantF = SE.isLoopInvariant(Expr, L); 4374 4375 if (!InvariantF) { 4376 Instruction *I = cast<Instruction>(Expr->getValue()); 4377 switch (I->getOpcode()) { 4378 case Instruction::Select: { 4379 SelectInst *SI = cast<SelectInst>(I); 4380 Optional<const SCEV *> Res = 4381 compareWithBackedgeCondition(SI->getCondition()); 4382 if (Res.hasValue()) { 4383 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4384 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4385 } 4386 break; 4387 } 4388 default: { 4389 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4390 if (Res.hasValue()) 4391 Result = Res.getValue(); 4392 break; 4393 } 4394 } 4395 } 4396 return Result; 4397 } 4398 4399 private: 4400 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4401 bool IsPosBECond, ScalarEvolution &SE) 4402 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4403 IsPositiveBECond(IsPosBECond) {} 4404 4405 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4406 4407 const Loop *L; 4408 /// Loop back condition. 4409 Value *BackedgeCond = nullptr; 4410 /// Set to true if loop back is on positive branch condition. 4411 bool IsPositiveBECond; 4412 }; 4413 4414 Optional<const SCEV *> 4415 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4416 4417 // If value matches the backedge condition for loop latch, 4418 // then return a constant evolution node based on loopback 4419 // branch taken. 4420 if (BackedgeCond == IC) 4421 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4422 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4423 return None; 4424 } 4425 4426 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4427 public: 4428 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4429 ScalarEvolution &SE) { 4430 SCEVShiftRewriter Rewriter(L, SE); 4431 const SCEV *Result = Rewriter.visit(S); 4432 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4433 } 4434 4435 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4436 // Only allow AddRecExprs for this loop. 4437 if (!SE.isLoopInvariant(Expr, L)) 4438 Valid = false; 4439 return Expr; 4440 } 4441 4442 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4443 if (Expr->getLoop() == L && Expr->isAffine()) 4444 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4445 Valid = false; 4446 return Expr; 4447 } 4448 4449 bool isValid() { return Valid; } 4450 4451 private: 4452 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4453 : SCEVRewriteVisitor(SE), L(L) {} 4454 4455 const Loop *L; 4456 bool Valid = true; 4457 }; 4458 4459 } // end anonymous namespace 4460 4461 SCEV::NoWrapFlags 4462 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4463 if (!AR->isAffine()) 4464 return SCEV::FlagAnyWrap; 4465 4466 using OBO = OverflowingBinaryOperator; 4467 4468 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4469 4470 if (!AR->hasNoSignedWrap()) { 4471 ConstantRange AddRecRange = getSignedRange(AR); 4472 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4473 4474 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4475 Instruction::Add, IncRange, OBO::NoSignedWrap); 4476 if (NSWRegion.contains(AddRecRange)) 4477 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4478 } 4479 4480 if (!AR->hasNoUnsignedWrap()) { 4481 ConstantRange AddRecRange = getUnsignedRange(AR); 4482 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4483 4484 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4485 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4486 if (NUWRegion.contains(AddRecRange)) 4487 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4488 } 4489 4490 return Result; 4491 } 4492 4493 namespace { 4494 4495 /// Represents an abstract binary operation. This may exist as a 4496 /// normal instruction or constant expression, or may have been 4497 /// derived from an expression tree. 4498 struct BinaryOp { 4499 unsigned Opcode; 4500 Value *LHS; 4501 Value *RHS; 4502 bool IsNSW = false; 4503 bool IsNUW = false; 4504 4505 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4506 /// constant expression. 4507 Operator *Op = nullptr; 4508 4509 explicit BinaryOp(Operator *Op) 4510 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4511 Op(Op) { 4512 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4513 IsNSW = OBO->hasNoSignedWrap(); 4514 IsNUW = OBO->hasNoUnsignedWrap(); 4515 } 4516 } 4517 4518 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4519 bool IsNUW = false) 4520 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4521 }; 4522 4523 } // end anonymous namespace 4524 4525 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4526 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4527 auto *Op = dyn_cast<Operator>(V); 4528 if (!Op) 4529 return None; 4530 4531 // Implementation detail: all the cleverness here should happen without 4532 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4533 // SCEV expressions when possible, and we should not break that. 4534 4535 switch (Op->getOpcode()) { 4536 case Instruction::Add: 4537 case Instruction::Sub: 4538 case Instruction::Mul: 4539 case Instruction::UDiv: 4540 case Instruction::URem: 4541 case Instruction::And: 4542 case Instruction::Or: 4543 case Instruction::AShr: 4544 case Instruction::Shl: 4545 return BinaryOp(Op); 4546 4547 case Instruction::Xor: 4548 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4549 // If the RHS of the xor is a signmask, then this is just an add. 4550 // Instcombine turns add of signmask into xor as a strength reduction step. 4551 if (RHSC->getValue().isSignMask()) 4552 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4553 return BinaryOp(Op); 4554 4555 case Instruction::LShr: 4556 // Turn logical shift right of a constant into a unsigned divide. 4557 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4558 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4559 4560 // If the shift count is not less than the bitwidth, the result of 4561 // the shift is undefined. Don't try to analyze it, because the 4562 // resolution chosen here may differ from the resolution chosen in 4563 // other parts of the compiler. 4564 if (SA->getValue().ult(BitWidth)) { 4565 Constant *X = 4566 ConstantInt::get(SA->getContext(), 4567 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4568 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4569 } 4570 } 4571 return BinaryOp(Op); 4572 4573 case Instruction::ExtractValue: { 4574 auto *EVI = cast<ExtractValueInst>(Op); 4575 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4576 break; 4577 4578 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 4579 if (!CI) 4580 break; 4581 4582 if (auto *F = CI->getCalledFunction()) 4583 switch (F->getIntrinsicID()) { 4584 case Intrinsic::sadd_with_overflow: 4585 case Intrinsic::uadd_with_overflow: 4586 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4587 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4588 CI->getArgOperand(1)); 4589 4590 // Now that we know that all uses of the arithmetic-result component of 4591 // CI are guarded by the overflow check, we can go ahead and pretend 4592 // that the arithmetic is non-overflowing. 4593 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 4594 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4595 CI->getArgOperand(1), /* IsNSW = */ true, 4596 /* IsNUW = */ false); 4597 else 4598 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4599 CI->getArgOperand(1), /* IsNSW = */ false, 4600 /* IsNUW*/ true); 4601 case Intrinsic::ssub_with_overflow: 4602 case Intrinsic::usub_with_overflow: 4603 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4604 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4605 CI->getArgOperand(1)); 4606 4607 // The same reasoning as sadd/uadd above. 4608 if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow) 4609 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4610 CI->getArgOperand(1), /* IsNSW = */ true, 4611 /* IsNUW = */ false); 4612 else 4613 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4614 CI->getArgOperand(1), /* IsNSW = */ false, 4615 /* IsNUW = */ true); 4616 case Intrinsic::smul_with_overflow: 4617 case Intrinsic::umul_with_overflow: 4618 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4619 CI->getArgOperand(1)); 4620 default: 4621 break; 4622 } 4623 break; 4624 } 4625 4626 default: 4627 break; 4628 } 4629 4630 return None; 4631 } 4632 4633 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4634 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4635 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4636 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4637 /// follows one of the following patterns: 4638 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4639 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4640 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4641 /// we return the type of the truncation operation, and indicate whether the 4642 /// truncated type should be treated as signed/unsigned by setting 4643 /// \p Signed to true/false, respectively. 4644 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4645 bool &Signed, ScalarEvolution &SE) { 4646 // The case where Op == SymbolicPHI (that is, with no type conversions on 4647 // the way) is handled by the regular add recurrence creating logic and 4648 // would have already been triggered in createAddRecForPHI. Reaching it here 4649 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4650 // because one of the other operands of the SCEVAddExpr updating this PHI is 4651 // not invariant). 4652 // 4653 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4654 // this case predicates that allow us to prove that Op == SymbolicPHI will 4655 // be added. 4656 if (Op == SymbolicPHI) 4657 return nullptr; 4658 4659 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4660 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4661 if (SourceBits != NewBits) 4662 return nullptr; 4663 4664 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4665 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4666 if (!SExt && !ZExt) 4667 return nullptr; 4668 const SCEVTruncateExpr *Trunc = 4669 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4670 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4671 if (!Trunc) 4672 return nullptr; 4673 const SCEV *X = Trunc->getOperand(); 4674 if (X != SymbolicPHI) 4675 return nullptr; 4676 Signed = SExt != nullptr; 4677 return Trunc->getType(); 4678 } 4679 4680 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4681 if (!PN->getType()->isIntegerTy()) 4682 return nullptr; 4683 const Loop *L = LI.getLoopFor(PN->getParent()); 4684 if (!L || L->getHeader() != PN->getParent()) 4685 return nullptr; 4686 return L; 4687 } 4688 4689 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4690 // computation that updates the phi follows the following pattern: 4691 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4692 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4693 // If so, try to see if it can be rewritten as an AddRecExpr under some 4694 // Predicates. If successful, return them as a pair. Also cache the results 4695 // of the analysis. 4696 // 4697 // Example usage scenario: 4698 // Say the Rewriter is called for the following SCEV: 4699 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4700 // where: 4701 // %X = phi i64 (%Start, %BEValue) 4702 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4703 // and call this function with %SymbolicPHI = %X. 4704 // 4705 // The analysis will find that the value coming around the backedge has 4706 // the following SCEV: 4707 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4708 // Upon concluding that this matches the desired pattern, the function 4709 // will return the pair {NewAddRec, SmallPredsVec} where: 4710 // NewAddRec = {%Start,+,%Step} 4711 // SmallPredsVec = {P1, P2, P3} as follows: 4712 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4713 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4714 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4715 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4716 // under the predicates {P1,P2,P3}. 4717 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4718 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4719 // 4720 // TODO's: 4721 // 4722 // 1) Extend the Induction descriptor to also support inductions that involve 4723 // casts: When needed (namely, when we are called in the context of the 4724 // vectorizer induction analysis), a Set of cast instructions will be 4725 // populated by this method, and provided back to isInductionPHI. This is 4726 // needed to allow the vectorizer to properly record them to be ignored by 4727 // the cost model and to avoid vectorizing them (otherwise these casts, 4728 // which are redundant under the runtime overflow checks, will be 4729 // vectorized, which can be costly). 4730 // 4731 // 2) Support additional induction/PHISCEV patterns: We also want to support 4732 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4733 // after the induction update operation (the induction increment): 4734 // 4735 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4736 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4737 // 4738 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4739 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4740 // 4741 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4742 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4743 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4744 SmallVector<const SCEVPredicate *, 3> Predicates; 4745 4746 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4747 // return an AddRec expression under some predicate. 4748 4749 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4750 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4751 assert(L && "Expecting an integer loop header phi"); 4752 4753 // The loop may have multiple entrances or multiple exits; we can analyze 4754 // this phi as an addrec if it has a unique entry value and a unique 4755 // backedge value. 4756 Value *BEValueV = nullptr, *StartValueV = nullptr; 4757 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4758 Value *V = PN->getIncomingValue(i); 4759 if (L->contains(PN->getIncomingBlock(i))) { 4760 if (!BEValueV) { 4761 BEValueV = V; 4762 } else if (BEValueV != V) { 4763 BEValueV = nullptr; 4764 break; 4765 } 4766 } else if (!StartValueV) { 4767 StartValueV = V; 4768 } else if (StartValueV != V) { 4769 StartValueV = nullptr; 4770 break; 4771 } 4772 } 4773 if (!BEValueV || !StartValueV) 4774 return None; 4775 4776 const SCEV *BEValue = getSCEV(BEValueV); 4777 4778 // If the value coming around the backedge is an add with the symbolic 4779 // value we just inserted, possibly with casts that we can ignore under 4780 // an appropriate runtime guard, then we found a simple induction variable! 4781 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4782 if (!Add) 4783 return None; 4784 4785 // If there is a single occurrence of the symbolic value, possibly 4786 // casted, replace it with a recurrence. 4787 unsigned FoundIndex = Add->getNumOperands(); 4788 Type *TruncTy = nullptr; 4789 bool Signed; 4790 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4791 if ((TruncTy = 4792 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4793 if (FoundIndex == e) { 4794 FoundIndex = i; 4795 break; 4796 } 4797 4798 if (FoundIndex == Add->getNumOperands()) 4799 return None; 4800 4801 // Create an add with everything but the specified operand. 4802 SmallVector<const SCEV *, 8> Ops; 4803 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4804 if (i != FoundIndex) 4805 Ops.push_back(Add->getOperand(i)); 4806 const SCEV *Accum = getAddExpr(Ops); 4807 4808 // The runtime checks will not be valid if the step amount is 4809 // varying inside the loop. 4810 if (!isLoopInvariant(Accum, L)) 4811 return None; 4812 4813 // *** Part2: Create the predicates 4814 4815 // Analysis was successful: we have a phi-with-cast pattern for which we 4816 // can return an AddRec expression under the following predicates: 4817 // 4818 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4819 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4820 // P2: An Equal predicate that guarantees that 4821 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4822 // P3: An Equal predicate that guarantees that 4823 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4824 // 4825 // As we next prove, the above predicates guarantee that: 4826 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4827 // 4828 // 4829 // More formally, we want to prove that: 4830 // Expr(i+1) = Start + (i+1) * Accum 4831 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4832 // 4833 // Given that: 4834 // 1) Expr(0) = Start 4835 // 2) Expr(1) = Start + Accum 4836 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4837 // 3) Induction hypothesis (step i): 4838 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4839 // 4840 // Proof: 4841 // Expr(i+1) = 4842 // = Start + (i+1)*Accum 4843 // = (Start + i*Accum) + Accum 4844 // = Expr(i) + Accum 4845 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4846 // :: from step i 4847 // 4848 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4849 // 4850 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4851 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4852 // + Accum :: from P3 4853 // 4854 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4855 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4856 // 4857 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4858 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4859 // 4860 // By induction, the same applies to all iterations 1<=i<n: 4861 // 4862 4863 // Create a truncated addrec for which we will add a no overflow check (P1). 4864 const SCEV *StartVal = getSCEV(StartValueV); 4865 const SCEV *PHISCEV = 4866 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4867 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4868 4869 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4870 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4871 // will be constant. 4872 // 4873 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4874 // add P1. 4875 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4876 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4877 Signed ? SCEVWrapPredicate::IncrementNSSW 4878 : SCEVWrapPredicate::IncrementNUSW; 4879 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4880 Predicates.push_back(AddRecPred); 4881 } 4882 4883 // Create the Equal Predicates P2,P3: 4884 4885 // It is possible that the predicates P2 and/or P3 are computable at 4886 // compile time due to StartVal and/or Accum being constants. 4887 // If either one is, then we can check that now and escape if either P2 4888 // or P3 is false. 4889 4890 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4891 // for each of StartVal and Accum 4892 auto getExtendedExpr = [&](const SCEV *Expr, 4893 bool CreateSignExtend) -> const SCEV * { 4894 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4895 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4896 const SCEV *ExtendedExpr = 4897 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4898 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4899 return ExtendedExpr; 4900 }; 4901 4902 // Given: 4903 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4904 // = getExtendedExpr(Expr) 4905 // Determine whether the predicate P: Expr == ExtendedExpr 4906 // is known to be false at compile time 4907 auto PredIsKnownFalse = [&](const SCEV *Expr, 4908 const SCEV *ExtendedExpr) -> bool { 4909 return Expr != ExtendedExpr && 4910 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4911 }; 4912 4913 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4914 if (PredIsKnownFalse(StartVal, StartExtended)) { 4915 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4916 return None; 4917 } 4918 4919 // The Step is always Signed (because the overflow checks are either 4920 // NSSW or NUSW) 4921 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4922 if (PredIsKnownFalse(Accum, AccumExtended)) { 4923 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4924 return None; 4925 } 4926 4927 auto AppendPredicate = [&](const SCEV *Expr, 4928 const SCEV *ExtendedExpr) -> void { 4929 if (Expr != ExtendedExpr && 4930 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4931 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4932 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4933 Predicates.push_back(Pred); 4934 } 4935 }; 4936 4937 AppendPredicate(StartVal, StartExtended); 4938 AppendPredicate(Accum, AccumExtended); 4939 4940 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4941 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4942 // into NewAR if it will also add the runtime overflow checks specified in 4943 // Predicates. 4944 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4945 4946 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4947 std::make_pair(NewAR, Predicates); 4948 // Remember the result of the analysis for this SCEV at this locayyytion. 4949 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4950 return PredRewrite; 4951 } 4952 4953 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4954 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4955 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4956 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4957 if (!L) 4958 return None; 4959 4960 // Check to see if we already analyzed this PHI. 4961 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4962 if (I != PredicatedSCEVRewrites.end()) { 4963 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4964 I->second; 4965 // Analysis was done before and failed to create an AddRec: 4966 if (Rewrite.first == SymbolicPHI) 4967 return None; 4968 // Analysis was done before and succeeded to create an AddRec under 4969 // a predicate: 4970 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4971 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4972 return Rewrite; 4973 } 4974 4975 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4976 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4977 4978 // Record in the cache that the analysis failed 4979 if (!Rewrite) { 4980 SmallVector<const SCEVPredicate *, 3> Predicates; 4981 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4982 return None; 4983 } 4984 4985 return Rewrite; 4986 } 4987 4988 // FIXME: This utility is currently required because the Rewriter currently 4989 // does not rewrite this expression: 4990 // {0, +, (sext ix (trunc iy to ix) to iy)} 4991 // into {0, +, %step}, 4992 // even when the following Equal predicate exists: 4993 // "%step == (sext ix (trunc iy to ix) to iy)". 4994 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4995 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4996 if (AR1 == AR2) 4997 return true; 4998 4999 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5000 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 5001 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 5002 return false; 5003 return true; 5004 }; 5005 5006 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5007 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5008 return false; 5009 return true; 5010 } 5011 5012 /// A helper function for createAddRecFromPHI to handle simple cases. 5013 /// 5014 /// This function tries to find an AddRec expression for the simplest (yet most 5015 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5016 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5017 /// technique for finding the AddRec expression. 5018 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5019 Value *BEValueV, 5020 Value *StartValueV) { 5021 const Loop *L = LI.getLoopFor(PN->getParent()); 5022 assert(L && L->getHeader() == PN->getParent()); 5023 assert(BEValueV && StartValueV); 5024 5025 auto BO = MatchBinaryOp(BEValueV, DT); 5026 if (!BO) 5027 return nullptr; 5028 5029 if (BO->Opcode != Instruction::Add) 5030 return nullptr; 5031 5032 const SCEV *Accum = nullptr; 5033 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5034 Accum = getSCEV(BO->RHS); 5035 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5036 Accum = getSCEV(BO->LHS); 5037 5038 if (!Accum) 5039 return nullptr; 5040 5041 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5042 if (BO->IsNUW) 5043 Flags = setFlags(Flags, SCEV::FlagNUW); 5044 if (BO->IsNSW) 5045 Flags = setFlags(Flags, SCEV::FlagNSW); 5046 5047 const SCEV *StartVal = getSCEV(StartValueV); 5048 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5049 5050 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5051 5052 // We can add Flags to the post-inc expression only if we 5053 // know that it is *undefined behavior* for BEValueV to 5054 // overflow. 5055 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5056 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5057 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5058 5059 return PHISCEV; 5060 } 5061 5062 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5063 const Loop *L = LI.getLoopFor(PN->getParent()); 5064 if (!L || L->getHeader() != PN->getParent()) 5065 return nullptr; 5066 5067 // The loop may have multiple entrances or multiple exits; we can analyze 5068 // this phi as an addrec if it has a unique entry value and a unique 5069 // backedge value. 5070 Value *BEValueV = nullptr, *StartValueV = nullptr; 5071 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5072 Value *V = PN->getIncomingValue(i); 5073 if (L->contains(PN->getIncomingBlock(i))) { 5074 if (!BEValueV) { 5075 BEValueV = V; 5076 } else if (BEValueV != V) { 5077 BEValueV = nullptr; 5078 break; 5079 } 5080 } else if (!StartValueV) { 5081 StartValueV = V; 5082 } else if (StartValueV != V) { 5083 StartValueV = nullptr; 5084 break; 5085 } 5086 } 5087 if (!BEValueV || !StartValueV) 5088 return nullptr; 5089 5090 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5091 "PHI node already processed?"); 5092 5093 // First, try to find AddRec expression without creating a fictituos symbolic 5094 // value for PN. 5095 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5096 return S; 5097 5098 // Handle PHI node value symbolically. 5099 const SCEV *SymbolicName = getUnknown(PN); 5100 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5101 5102 // Using this symbolic name for the PHI, analyze the value coming around 5103 // the back-edge. 5104 const SCEV *BEValue = getSCEV(BEValueV); 5105 5106 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5107 // has a special value for the first iteration of the loop. 5108 5109 // If the value coming around the backedge is an add with the symbolic 5110 // value we just inserted, then we found a simple induction variable! 5111 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5112 // If there is a single occurrence of the symbolic value, replace it 5113 // with a recurrence. 5114 unsigned FoundIndex = Add->getNumOperands(); 5115 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5116 if (Add->getOperand(i) == SymbolicName) 5117 if (FoundIndex == e) { 5118 FoundIndex = i; 5119 break; 5120 } 5121 5122 if (FoundIndex != Add->getNumOperands()) { 5123 // Create an add with everything but the specified operand. 5124 SmallVector<const SCEV *, 8> Ops; 5125 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5126 if (i != FoundIndex) 5127 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5128 L, *this)); 5129 const SCEV *Accum = getAddExpr(Ops); 5130 5131 // This is not a valid addrec if the step amount is varying each 5132 // loop iteration, but is not itself an addrec in this loop. 5133 if (isLoopInvariant(Accum, L) || 5134 (isa<SCEVAddRecExpr>(Accum) && 5135 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5136 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5137 5138 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5139 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5140 if (BO->IsNUW) 5141 Flags = setFlags(Flags, SCEV::FlagNUW); 5142 if (BO->IsNSW) 5143 Flags = setFlags(Flags, SCEV::FlagNSW); 5144 } 5145 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5146 // If the increment is an inbounds GEP, then we know the address 5147 // space cannot be wrapped around. We cannot make any guarantee 5148 // about signed or unsigned overflow because pointers are 5149 // unsigned but we may have a negative index from the base 5150 // pointer. We can guarantee that no unsigned wrap occurs if the 5151 // indices form a positive value. 5152 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5153 Flags = setFlags(Flags, SCEV::FlagNW); 5154 5155 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5156 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5157 Flags = setFlags(Flags, SCEV::FlagNUW); 5158 } 5159 5160 // We cannot transfer nuw and nsw flags from subtraction 5161 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5162 // for instance. 5163 } 5164 5165 const SCEV *StartVal = getSCEV(StartValueV); 5166 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5167 5168 // Okay, for the entire analysis of this edge we assumed the PHI 5169 // to be symbolic. We now need to go back and purge all of the 5170 // entries for the scalars that use the symbolic expression. 5171 forgetSymbolicName(PN, SymbolicName); 5172 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5173 5174 // We can add Flags to the post-inc expression only if we 5175 // know that it is *undefined behavior* for BEValueV to 5176 // overflow. 5177 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5178 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5179 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5180 5181 return PHISCEV; 5182 } 5183 } 5184 } else { 5185 // Otherwise, this could be a loop like this: 5186 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5187 // In this case, j = {1,+,1} and BEValue is j. 5188 // Because the other in-value of i (0) fits the evolution of BEValue 5189 // i really is an addrec evolution. 5190 // 5191 // We can generalize this saying that i is the shifted value of BEValue 5192 // by one iteration: 5193 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5194 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5195 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5196 if (Shifted != getCouldNotCompute() && 5197 Start != getCouldNotCompute()) { 5198 const SCEV *StartVal = getSCEV(StartValueV); 5199 if (Start == StartVal) { 5200 // Okay, for the entire analysis of this edge we assumed the PHI 5201 // to be symbolic. We now need to go back and purge all of the 5202 // entries for the scalars that use the symbolic expression. 5203 forgetSymbolicName(PN, SymbolicName); 5204 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5205 return Shifted; 5206 } 5207 } 5208 } 5209 5210 // Remove the temporary PHI node SCEV that has been inserted while intending 5211 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5212 // as it will prevent later (possibly simpler) SCEV expressions to be added 5213 // to the ValueExprMap. 5214 eraseValueFromMap(PN); 5215 5216 return nullptr; 5217 } 5218 5219 // Checks if the SCEV S is available at BB. S is considered available at BB 5220 // if S can be materialized at BB without introducing a fault. 5221 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5222 BasicBlock *BB) { 5223 struct CheckAvailable { 5224 bool TraversalDone = false; 5225 bool Available = true; 5226 5227 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5228 BasicBlock *BB = nullptr; 5229 DominatorTree &DT; 5230 5231 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5232 : L(L), BB(BB), DT(DT) {} 5233 5234 bool setUnavailable() { 5235 TraversalDone = true; 5236 Available = false; 5237 return false; 5238 } 5239 5240 bool follow(const SCEV *S) { 5241 switch (S->getSCEVType()) { 5242 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5243 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5244 // These expressions are available if their operand(s) is/are. 5245 return true; 5246 5247 case scAddRecExpr: { 5248 // We allow add recurrences that are on the loop BB is in, or some 5249 // outer loop. This guarantees availability because the value of the 5250 // add recurrence at BB is simply the "current" value of the induction 5251 // variable. We can relax this in the future; for instance an add 5252 // recurrence on a sibling dominating loop is also available at BB. 5253 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5254 if (L && (ARLoop == L || ARLoop->contains(L))) 5255 return true; 5256 5257 return setUnavailable(); 5258 } 5259 5260 case scUnknown: { 5261 // For SCEVUnknown, we check for simple dominance. 5262 const auto *SU = cast<SCEVUnknown>(S); 5263 Value *V = SU->getValue(); 5264 5265 if (isa<Argument>(V)) 5266 return false; 5267 5268 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5269 return false; 5270 5271 return setUnavailable(); 5272 } 5273 5274 case scUDivExpr: 5275 case scCouldNotCompute: 5276 // We do not try to smart about these at all. 5277 return setUnavailable(); 5278 } 5279 llvm_unreachable("switch should be fully covered!"); 5280 } 5281 5282 bool isDone() { return TraversalDone; } 5283 }; 5284 5285 CheckAvailable CA(L, BB, DT); 5286 SCEVTraversal<CheckAvailable> ST(CA); 5287 5288 ST.visitAll(S); 5289 return CA.Available; 5290 } 5291 5292 // Try to match a control flow sequence that branches out at BI and merges back 5293 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5294 // match. 5295 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5296 Value *&C, Value *&LHS, Value *&RHS) { 5297 C = BI->getCondition(); 5298 5299 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5300 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5301 5302 if (!LeftEdge.isSingleEdge()) 5303 return false; 5304 5305 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5306 5307 Use &LeftUse = Merge->getOperandUse(0); 5308 Use &RightUse = Merge->getOperandUse(1); 5309 5310 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5311 LHS = LeftUse; 5312 RHS = RightUse; 5313 return true; 5314 } 5315 5316 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5317 LHS = RightUse; 5318 RHS = LeftUse; 5319 return true; 5320 } 5321 5322 return false; 5323 } 5324 5325 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5326 auto IsReachable = 5327 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5328 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5329 const Loop *L = LI.getLoopFor(PN->getParent()); 5330 5331 // We don't want to break LCSSA, even in a SCEV expression tree. 5332 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5333 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5334 return nullptr; 5335 5336 // Try to match 5337 // 5338 // br %cond, label %left, label %right 5339 // left: 5340 // br label %merge 5341 // right: 5342 // br label %merge 5343 // merge: 5344 // V = phi [ %x, %left ], [ %y, %right ] 5345 // 5346 // as "select %cond, %x, %y" 5347 5348 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5349 assert(IDom && "At least the entry block should dominate PN"); 5350 5351 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5352 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5353 5354 if (BI && BI->isConditional() && 5355 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5356 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5357 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5358 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5359 } 5360 5361 return nullptr; 5362 } 5363 5364 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5365 if (const SCEV *S = createAddRecFromPHI(PN)) 5366 return S; 5367 5368 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5369 return S; 5370 5371 // If the PHI has a single incoming value, follow that value, unless the 5372 // PHI's incoming blocks are in a different loop, in which case doing so 5373 // risks breaking LCSSA form. Instcombine would normally zap these, but 5374 // it doesn't have DominatorTree information, so it may miss cases. 5375 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5376 if (LI.replacementPreservesLCSSAForm(PN, V)) 5377 return getSCEV(V); 5378 5379 // If it's not a loop phi, we can't handle it yet. 5380 return getUnknown(PN); 5381 } 5382 5383 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5384 Value *Cond, 5385 Value *TrueVal, 5386 Value *FalseVal) { 5387 // Handle "constant" branch or select. This can occur for instance when a 5388 // loop pass transforms an inner loop and moves on to process the outer loop. 5389 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5390 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5391 5392 // Try to match some simple smax or umax patterns. 5393 auto *ICI = dyn_cast<ICmpInst>(Cond); 5394 if (!ICI) 5395 return getUnknown(I); 5396 5397 Value *LHS = ICI->getOperand(0); 5398 Value *RHS = ICI->getOperand(1); 5399 5400 switch (ICI->getPredicate()) { 5401 case ICmpInst::ICMP_SLT: 5402 case ICmpInst::ICMP_SLE: 5403 std::swap(LHS, RHS); 5404 LLVM_FALLTHROUGH; 5405 case ICmpInst::ICMP_SGT: 5406 case ICmpInst::ICMP_SGE: 5407 // a >s b ? a+x : b+x -> smax(a, b)+x 5408 // a >s b ? b+x : a+x -> smin(a, b)+x 5409 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5410 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5411 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5412 const SCEV *LA = getSCEV(TrueVal); 5413 const SCEV *RA = getSCEV(FalseVal); 5414 const SCEV *LDiff = getMinusSCEV(LA, LS); 5415 const SCEV *RDiff = getMinusSCEV(RA, RS); 5416 if (LDiff == RDiff) 5417 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5418 LDiff = getMinusSCEV(LA, RS); 5419 RDiff = getMinusSCEV(RA, LS); 5420 if (LDiff == RDiff) 5421 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5422 } 5423 break; 5424 case ICmpInst::ICMP_ULT: 5425 case ICmpInst::ICMP_ULE: 5426 std::swap(LHS, RHS); 5427 LLVM_FALLTHROUGH; 5428 case ICmpInst::ICMP_UGT: 5429 case ICmpInst::ICMP_UGE: 5430 // a >u b ? a+x : b+x -> umax(a, b)+x 5431 // a >u b ? b+x : a+x -> umin(a, b)+x 5432 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5433 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5434 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5435 const SCEV *LA = getSCEV(TrueVal); 5436 const SCEV *RA = getSCEV(FalseVal); 5437 const SCEV *LDiff = getMinusSCEV(LA, LS); 5438 const SCEV *RDiff = getMinusSCEV(RA, RS); 5439 if (LDiff == RDiff) 5440 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5441 LDiff = getMinusSCEV(LA, RS); 5442 RDiff = getMinusSCEV(RA, LS); 5443 if (LDiff == RDiff) 5444 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5445 } 5446 break; 5447 case ICmpInst::ICMP_NE: 5448 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5449 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5450 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5451 const SCEV *One = getOne(I->getType()); 5452 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5453 const SCEV *LA = getSCEV(TrueVal); 5454 const SCEV *RA = getSCEV(FalseVal); 5455 const SCEV *LDiff = getMinusSCEV(LA, LS); 5456 const SCEV *RDiff = getMinusSCEV(RA, One); 5457 if (LDiff == RDiff) 5458 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5459 } 5460 break; 5461 case ICmpInst::ICMP_EQ: 5462 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5463 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5464 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5465 const SCEV *One = getOne(I->getType()); 5466 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5467 const SCEV *LA = getSCEV(TrueVal); 5468 const SCEV *RA = getSCEV(FalseVal); 5469 const SCEV *LDiff = getMinusSCEV(LA, One); 5470 const SCEV *RDiff = getMinusSCEV(RA, LS); 5471 if (LDiff == RDiff) 5472 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5473 } 5474 break; 5475 default: 5476 break; 5477 } 5478 5479 return getUnknown(I); 5480 } 5481 5482 /// Expand GEP instructions into add and multiply operations. This allows them 5483 /// to be analyzed by regular SCEV code. 5484 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5485 // Don't attempt to analyze GEPs over unsized objects. 5486 if (!GEP->getSourceElementType()->isSized()) 5487 return getUnknown(GEP); 5488 5489 SmallVector<const SCEV *, 4> IndexExprs; 5490 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5491 IndexExprs.push_back(getSCEV(*Index)); 5492 return getGEPExpr(GEP, IndexExprs); 5493 } 5494 5495 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5496 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5497 return C->getAPInt().countTrailingZeros(); 5498 5499 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5500 return std::min(GetMinTrailingZeros(T->getOperand()), 5501 (uint32_t)getTypeSizeInBits(T->getType())); 5502 5503 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5504 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5505 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5506 ? getTypeSizeInBits(E->getType()) 5507 : OpRes; 5508 } 5509 5510 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5511 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5512 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5513 ? getTypeSizeInBits(E->getType()) 5514 : OpRes; 5515 } 5516 5517 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5518 // The result is the min of all operands results. 5519 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5520 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5521 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5522 return MinOpRes; 5523 } 5524 5525 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5526 // The result is the sum of all operands results. 5527 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5528 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5529 for (unsigned i = 1, e = M->getNumOperands(); 5530 SumOpRes != BitWidth && i != e; ++i) 5531 SumOpRes = 5532 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5533 return SumOpRes; 5534 } 5535 5536 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5537 // The result is the min of all operands results. 5538 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5539 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5540 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5541 return MinOpRes; 5542 } 5543 5544 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5545 // The result is the min of all operands results. 5546 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5547 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5548 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5549 return MinOpRes; 5550 } 5551 5552 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5553 // The result is the min of all operands results. 5554 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5555 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5556 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5557 return MinOpRes; 5558 } 5559 5560 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5561 // For a SCEVUnknown, ask ValueTracking. 5562 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5563 return Known.countMinTrailingZeros(); 5564 } 5565 5566 // SCEVUDivExpr 5567 return 0; 5568 } 5569 5570 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5571 auto I = MinTrailingZerosCache.find(S); 5572 if (I != MinTrailingZerosCache.end()) 5573 return I->second; 5574 5575 uint32_t Result = GetMinTrailingZerosImpl(S); 5576 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5577 assert(InsertPair.second && "Should insert a new key"); 5578 return InsertPair.first->second; 5579 } 5580 5581 /// Helper method to assign a range to V from metadata present in the IR. 5582 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5583 if (Instruction *I = dyn_cast<Instruction>(V)) 5584 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5585 return getConstantRangeFromMetadata(*MD); 5586 5587 return None; 5588 } 5589 5590 /// Determine the range for a particular SCEV. If SignHint is 5591 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5592 /// with a "cleaner" unsigned (resp. signed) representation. 5593 const ConstantRange & 5594 ScalarEvolution::getRangeRef(const SCEV *S, 5595 ScalarEvolution::RangeSignHint SignHint) { 5596 DenseMap<const SCEV *, ConstantRange> &Cache = 5597 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5598 : SignedRanges; 5599 5600 // See if we've computed this range already. 5601 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5602 if (I != Cache.end()) 5603 return I->second; 5604 5605 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5606 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5607 5608 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5609 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5610 5611 // If the value has known zeros, the maximum value will have those known zeros 5612 // as well. 5613 uint32_t TZ = GetMinTrailingZeros(S); 5614 if (TZ != 0) { 5615 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5616 ConservativeResult = 5617 ConstantRange(APInt::getMinValue(BitWidth), 5618 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5619 else 5620 ConservativeResult = ConstantRange( 5621 APInt::getSignedMinValue(BitWidth), 5622 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5623 } 5624 5625 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5626 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5627 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5628 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5629 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 5630 } 5631 5632 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5633 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5634 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5635 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5636 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 5637 } 5638 5639 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5640 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5641 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5642 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5643 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 5644 } 5645 5646 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5647 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5648 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5649 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5650 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 5651 } 5652 5653 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5654 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5655 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5656 return setRange(UDiv, SignHint, 5657 ConservativeResult.intersectWith(X.udiv(Y))); 5658 } 5659 5660 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5661 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5662 return setRange(ZExt, SignHint, 5663 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 5664 } 5665 5666 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5667 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5668 return setRange(SExt, SignHint, 5669 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 5670 } 5671 5672 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5673 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5674 return setRange(Trunc, SignHint, 5675 ConservativeResult.intersectWith(X.truncate(BitWidth))); 5676 } 5677 5678 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5679 // If there's no unsigned wrap, the value will never be less than its 5680 // initial value. 5681 if (AddRec->hasNoUnsignedWrap()) 5682 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5683 if (!C->getValue()->isZero()) 5684 ConservativeResult = ConservativeResult.intersectWith( 5685 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 5686 5687 // If there's no signed wrap, and all the operands have the same sign or 5688 // zero, the value won't ever change sign. 5689 if (AddRec->hasNoSignedWrap()) { 5690 bool AllNonNeg = true; 5691 bool AllNonPos = true; 5692 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5693 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5694 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5695 } 5696 if (AllNonNeg) 5697 ConservativeResult = ConservativeResult.intersectWith( 5698 ConstantRange(APInt(BitWidth, 0), 5699 APInt::getSignedMinValue(BitWidth))); 5700 else if (AllNonPos) 5701 ConservativeResult = ConservativeResult.intersectWith( 5702 ConstantRange(APInt::getSignedMinValue(BitWidth), 5703 APInt(BitWidth, 1))); 5704 } 5705 5706 // TODO: non-affine addrec 5707 if (AddRec->isAffine()) { 5708 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 5709 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5710 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5711 auto RangeFromAffine = getRangeForAffineAR( 5712 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5713 BitWidth); 5714 if (!RangeFromAffine.isFullSet()) 5715 ConservativeResult = 5716 ConservativeResult.intersectWith(RangeFromAffine); 5717 5718 auto RangeFromFactoring = getRangeViaFactoring( 5719 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5720 BitWidth); 5721 if (!RangeFromFactoring.isFullSet()) 5722 ConservativeResult = 5723 ConservativeResult.intersectWith(RangeFromFactoring); 5724 } 5725 } 5726 5727 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5728 } 5729 5730 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5731 // Check if the IR explicitly contains !range metadata. 5732 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5733 if (MDRange.hasValue()) 5734 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 5735 5736 // Split here to avoid paying the compile-time cost of calling both 5737 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5738 // if needed. 5739 const DataLayout &DL = getDataLayout(); 5740 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5741 // For a SCEVUnknown, ask ValueTracking. 5742 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5743 if (Known.One != ~Known.Zero + 1) 5744 ConservativeResult = 5745 ConservativeResult.intersectWith(ConstantRange(Known.One, 5746 ~Known.Zero + 1)); 5747 } else { 5748 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5749 "generalize as needed!"); 5750 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5751 if (NS > 1) 5752 ConservativeResult = ConservativeResult.intersectWith( 5753 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5754 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 5755 } 5756 5757 // A range of Phi is a subset of union of all ranges of its input. 5758 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5759 // Make sure that we do not run over cycled Phis. 5760 if (PendingPhiRanges.insert(Phi).second) { 5761 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5762 for (auto &Op : Phi->operands()) { 5763 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5764 RangeFromOps = RangeFromOps.unionWith(OpRange); 5765 // No point to continue if we already have a full set. 5766 if (RangeFromOps.isFullSet()) 5767 break; 5768 } 5769 ConservativeResult = ConservativeResult.intersectWith(RangeFromOps); 5770 bool Erased = PendingPhiRanges.erase(Phi); 5771 assert(Erased && "Failed to erase Phi properly?"); 5772 (void) Erased; 5773 } 5774 } 5775 5776 return setRange(U, SignHint, std::move(ConservativeResult)); 5777 } 5778 5779 return setRange(S, SignHint, std::move(ConservativeResult)); 5780 } 5781 5782 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5783 // values that the expression can take. Initially, the expression has a value 5784 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5785 // argument defines if we treat Step as signed or unsigned. 5786 static ConstantRange getRangeForAffineARHelper(APInt Step, 5787 const ConstantRange &StartRange, 5788 const APInt &MaxBECount, 5789 unsigned BitWidth, bool Signed) { 5790 // If either Step or MaxBECount is 0, then the expression won't change, and we 5791 // just need to return the initial range. 5792 if (Step == 0 || MaxBECount == 0) 5793 return StartRange; 5794 5795 // If we don't know anything about the initial value (i.e. StartRange is 5796 // FullRange), then we don't know anything about the final range either. 5797 // Return FullRange. 5798 if (StartRange.isFullSet()) 5799 return ConstantRange::getFull(BitWidth); 5800 5801 // If Step is signed and negative, then we use its absolute value, but we also 5802 // note that we're moving in the opposite direction. 5803 bool Descending = Signed && Step.isNegative(); 5804 5805 if (Signed) 5806 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5807 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5808 // This equations hold true due to the well-defined wrap-around behavior of 5809 // APInt. 5810 Step = Step.abs(); 5811 5812 // Check if Offset is more than full span of BitWidth. If it is, the 5813 // expression is guaranteed to overflow. 5814 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5815 return ConstantRange::getFull(BitWidth); 5816 5817 // Offset is by how much the expression can change. Checks above guarantee no 5818 // overflow here. 5819 APInt Offset = Step * MaxBECount; 5820 5821 // Minimum value of the final range will match the minimal value of StartRange 5822 // if the expression is increasing and will be decreased by Offset otherwise. 5823 // Maximum value of the final range will match the maximal value of StartRange 5824 // if the expression is decreasing and will be increased by Offset otherwise. 5825 APInt StartLower = StartRange.getLower(); 5826 APInt StartUpper = StartRange.getUpper() - 1; 5827 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5828 : (StartUpper + std::move(Offset)); 5829 5830 // It's possible that the new minimum/maximum value will fall into the initial 5831 // range (due to wrap around). This means that the expression can take any 5832 // value in this bitwidth, and we have to return full range. 5833 if (StartRange.contains(MovedBoundary)) 5834 return ConstantRange::getFull(BitWidth); 5835 5836 APInt NewLower = 5837 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5838 APInt NewUpper = 5839 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5840 NewUpper += 1; 5841 5842 // If we end up with full range, return a proper full range. 5843 if (NewLower == NewUpper) 5844 return ConstantRange::getFull(BitWidth); 5845 5846 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5847 return ConstantRange(std::move(NewLower), std::move(NewUpper)); 5848 } 5849 5850 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5851 const SCEV *Step, 5852 const SCEV *MaxBECount, 5853 unsigned BitWidth) { 5854 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5855 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5856 "Precondition!"); 5857 5858 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5859 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5860 5861 // First, consider step signed. 5862 ConstantRange StartSRange = getSignedRange(Start); 5863 ConstantRange StepSRange = getSignedRange(Step); 5864 5865 // If Step can be both positive and negative, we need to find ranges for the 5866 // maximum absolute step values in both directions and union them. 5867 ConstantRange SR = 5868 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5869 MaxBECountValue, BitWidth, /* Signed = */ true); 5870 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5871 StartSRange, MaxBECountValue, 5872 BitWidth, /* Signed = */ true)); 5873 5874 // Next, consider step unsigned. 5875 ConstantRange UR = getRangeForAffineARHelper( 5876 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5877 MaxBECountValue, BitWidth, /* Signed = */ false); 5878 5879 // Finally, intersect signed and unsigned ranges. 5880 return SR.intersectWith(UR); 5881 } 5882 5883 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5884 const SCEV *Step, 5885 const SCEV *MaxBECount, 5886 unsigned BitWidth) { 5887 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5888 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5889 5890 struct SelectPattern { 5891 Value *Condition = nullptr; 5892 APInt TrueValue; 5893 APInt FalseValue; 5894 5895 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5896 const SCEV *S) { 5897 Optional<unsigned> CastOp; 5898 APInt Offset(BitWidth, 0); 5899 5900 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5901 "Should be!"); 5902 5903 // Peel off a constant offset: 5904 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5905 // In the future we could consider being smarter here and handle 5906 // {Start+Step,+,Step} too. 5907 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5908 return; 5909 5910 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5911 S = SA->getOperand(1); 5912 } 5913 5914 // Peel off a cast operation 5915 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5916 CastOp = SCast->getSCEVType(); 5917 S = SCast->getOperand(); 5918 } 5919 5920 using namespace llvm::PatternMatch; 5921 5922 auto *SU = dyn_cast<SCEVUnknown>(S); 5923 const APInt *TrueVal, *FalseVal; 5924 if (!SU || 5925 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5926 m_APInt(FalseVal)))) { 5927 Condition = nullptr; 5928 return; 5929 } 5930 5931 TrueValue = *TrueVal; 5932 FalseValue = *FalseVal; 5933 5934 // Re-apply the cast we peeled off earlier 5935 if (CastOp.hasValue()) 5936 switch (*CastOp) { 5937 default: 5938 llvm_unreachable("Unknown SCEV cast type!"); 5939 5940 case scTruncate: 5941 TrueValue = TrueValue.trunc(BitWidth); 5942 FalseValue = FalseValue.trunc(BitWidth); 5943 break; 5944 case scZeroExtend: 5945 TrueValue = TrueValue.zext(BitWidth); 5946 FalseValue = FalseValue.zext(BitWidth); 5947 break; 5948 case scSignExtend: 5949 TrueValue = TrueValue.sext(BitWidth); 5950 FalseValue = FalseValue.sext(BitWidth); 5951 break; 5952 } 5953 5954 // Re-apply the constant offset we peeled off earlier 5955 TrueValue += Offset; 5956 FalseValue += Offset; 5957 } 5958 5959 bool isRecognized() { return Condition != nullptr; } 5960 }; 5961 5962 SelectPattern StartPattern(*this, BitWidth, Start); 5963 if (!StartPattern.isRecognized()) 5964 return ConstantRange::getFull(BitWidth); 5965 5966 SelectPattern StepPattern(*this, BitWidth, Step); 5967 if (!StepPattern.isRecognized()) 5968 return ConstantRange::getFull(BitWidth); 5969 5970 if (StartPattern.Condition != StepPattern.Condition) { 5971 // We don't handle this case today; but we could, by considering four 5972 // possibilities below instead of two. I'm not sure if there are cases where 5973 // that will help over what getRange already does, though. 5974 return ConstantRange::getFull(BitWidth); 5975 } 5976 5977 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5978 // construct arbitrary general SCEV expressions here. This function is called 5979 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5980 // say) can end up caching a suboptimal value. 5981 5982 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5983 // C2352 and C2512 (otherwise it isn't needed). 5984 5985 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5986 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5987 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5988 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5989 5990 ConstantRange TrueRange = 5991 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5992 ConstantRange FalseRange = 5993 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5994 5995 return TrueRange.unionWith(FalseRange); 5996 } 5997 5998 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5999 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6000 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6001 6002 // Return early if there are no flags to propagate to the SCEV. 6003 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6004 if (BinOp->hasNoUnsignedWrap()) 6005 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6006 if (BinOp->hasNoSignedWrap()) 6007 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6008 if (Flags == SCEV::FlagAnyWrap) 6009 return SCEV::FlagAnyWrap; 6010 6011 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6012 } 6013 6014 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6015 // Here we check that I is in the header of the innermost loop containing I, 6016 // since we only deal with instructions in the loop header. The actual loop we 6017 // need to check later will come from an add recurrence, but getting that 6018 // requires computing the SCEV of the operands, which can be expensive. This 6019 // check we can do cheaply to rule out some cases early. 6020 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6021 if (InnermostContainingLoop == nullptr || 6022 InnermostContainingLoop->getHeader() != I->getParent()) 6023 return false; 6024 6025 // Only proceed if we can prove that I does not yield poison. 6026 if (!programUndefinedIfFullPoison(I)) 6027 return false; 6028 6029 // At this point we know that if I is executed, then it does not wrap 6030 // according to at least one of NSW or NUW. If I is not executed, then we do 6031 // not know if the calculation that I represents would wrap. Multiple 6032 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6033 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6034 // derived from other instructions that map to the same SCEV. We cannot make 6035 // that guarantee for cases where I is not executed. So we need to find the 6036 // loop that I is considered in relation to and prove that I is executed for 6037 // every iteration of that loop. That implies that the value that I 6038 // calculates does not wrap anywhere in the loop, so then we can apply the 6039 // flags to the SCEV. 6040 // 6041 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6042 // from different loops, so that we know which loop to prove that I is 6043 // executed in. 6044 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6045 // I could be an extractvalue from a call to an overflow intrinsic. 6046 // TODO: We can do better here in some cases. 6047 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6048 return false; 6049 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6050 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6051 bool AllOtherOpsLoopInvariant = true; 6052 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6053 ++OtherOpIndex) { 6054 if (OtherOpIndex != OpIndex) { 6055 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6056 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6057 AllOtherOpsLoopInvariant = false; 6058 break; 6059 } 6060 } 6061 } 6062 if (AllOtherOpsLoopInvariant && 6063 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6064 return true; 6065 } 6066 } 6067 return false; 6068 } 6069 6070 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6071 // If we know that \c I can never be poison period, then that's enough. 6072 if (isSCEVExprNeverPoison(I)) 6073 return true; 6074 6075 // For an add recurrence specifically, we assume that infinite loops without 6076 // side effects are undefined behavior, and then reason as follows: 6077 // 6078 // If the add recurrence is poison in any iteration, it is poison on all 6079 // future iterations (since incrementing poison yields poison). If the result 6080 // of the add recurrence is fed into the loop latch condition and the loop 6081 // does not contain any throws or exiting blocks other than the latch, we now 6082 // have the ability to "choose" whether the backedge is taken or not (by 6083 // choosing a sufficiently evil value for the poison feeding into the branch) 6084 // for every iteration including and after the one in which \p I first became 6085 // poison. There are two possibilities (let's call the iteration in which \p 6086 // I first became poison as K): 6087 // 6088 // 1. In the set of iterations including and after K, the loop body executes 6089 // no side effects. In this case executing the backege an infinte number 6090 // of times will yield undefined behavior. 6091 // 6092 // 2. In the set of iterations including and after K, the loop body executes 6093 // at least one side effect. In this case, that specific instance of side 6094 // effect is control dependent on poison, which also yields undefined 6095 // behavior. 6096 6097 auto *ExitingBB = L->getExitingBlock(); 6098 auto *LatchBB = L->getLoopLatch(); 6099 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6100 return false; 6101 6102 SmallPtrSet<const Instruction *, 16> Pushed; 6103 SmallVector<const Instruction *, 8> PoisonStack; 6104 6105 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6106 // things that are known to be fully poison under that assumption go on the 6107 // PoisonStack. 6108 Pushed.insert(I); 6109 PoisonStack.push_back(I); 6110 6111 bool LatchControlDependentOnPoison = false; 6112 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6113 const Instruction *Poison = PoisonStack.pop_back_val(); 6114 6115 for (auto *PoisonUser : Poison->users()) { 6116 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 6117 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6118 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6119 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6120 assert(BI->isConditional() && "Only possibility!"); 6121 if (BI->getParent() == LatchBB) { 6122 LatchControlDependentOnPoison = true; 6123 break; 6124 } 6125 } 6126 } 6127 } 6128 6129 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6130 } 6131 6132 ScalarEvolution::LoopProperties 6133 ScalarEvolution::getLoopProperties(const Loop *L) { 6134 using LoopProperties = ScalarEvolution::LoopProperties; 6135 6136 auto Itr = LoopPropertiesCache.find(L); 6137 if (Itr == LoopPropertiesCache.end()) { 6138 auto HasSideEffects = [](Instruction *I) { 6139 if (auto *SI = dyn_cast<StoreInst>(I)) 6140 return !SI->isSimple(); 6141 6142 return I->mayHaveSideEffects(); 6143 }; 6144 6145 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6146 /*HasNoSideEffects*/ true}; 6147 6148 for (auto *BB : L->getBlocks()) 6149 for (auto &I : *BB) { 6150 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6151 LP.HasNoAbnormalExits = false; 6152 if (HasSideEffects(&I)) 6153 LP.HasNoSideEffects = false; 6154 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6155 break; // We're already as pessimistic as we can get. 6156 } 6157 6158 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6159 assert(InsertPair.second && "We just checked!"); 6160 Itr = InsertPair.first; 6161 } 6162 6163 return Itr->second; 6164 } 6165 6166 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6167 if (!isSCEVable(V->getType())) 6168 return getUnknown(V); 6169 6170 if (Instruction *I = dyn_cast<Instruction>(V)) { 6171 // Don't attempt to analyze instructions in blocks that aren't 6172 // reachable. Such instructions don't matter, and they aren't required 6173 // to obey basic rules for definitions dominating uses which this 6174 // analysis depends on. 6175 if (!DT.isReachableFromEntry(I->getParent())) 6176 return getUnknown(UndefValue::get(V->getType())); 6177 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6178 return getConstant(CI); 6179 else if (isa<ConstantPointerNull>(V)) 6180 return getZero(V->getType()); 6181 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6182 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6183 else if (!isa<ConstantExpr>(V)) 6184 return getUnknown(V); 6185 6186 Operator *U = cast<Operator>(V); 6187 if (auto BO = MatchBinaryOp(U, DT)) { 6188 switch (BO->Opcode) { 6189 case Instruction::Add: { 6190 // The simple thing to do would be to just call getSCEV on both operands 6191 // and call getAddExpr with the result. However if we're looking at a 6192 // bunch of things all added together, this can be quite inefficient, 6193 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6194 // Instead, gather up all the operands and make a single getAddExpr call. 6195 // LLVM IR canonical form means we need only traverse the left operands. 6196 SmallVector<const SCEV *, 4> AddOps; 6197 do { 6198 if (BO->Op) { 6199 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6200 AddOps.push_back(OpSCEV); 6201 break; 6202 } 6203 6204 // If a NUW or NSW flag can be applied to the SCEV for this 6205 // addition, then compute the SCEV for this addition by itself 6206 // with a separate call to getAddExpr. We need to do that 6207 // instead of pushing the operands of the addition onto AddOps, 6208 // since the flags are only known to apply to this particular 6209 // addition - they may not apply to other additions that can be 6210 // formed with operands from AddOps. 6211 const SCEV *RHS = getSCEV(BO->RHS); 6212 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6213 if (Flags != SCEV::FlagAnyWrap) { 6214 const SCEV *LHS = getSCEV(BO->LHS); 6215 if (BO->Opcode == Instruction::Sub) 6216 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6217 else 6218 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6219 break; 6220 } 6221 } 6222 6223 if (BO->Opcode == Instruction::Sub) 6224 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6225 else 6226 AddOps.push_back(getSCEV(BO->RHS)); 6227 6228 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6229 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6230 NewBO->Opcode != Instruction::Sub)) { 6231 AddOps.push_back(getSCEV(BO->LHS)); 6232 break; 6233 } 6234 BO = NewBO; 6235 } while (true); 6236 6237 return getAddExpr(AddOps); 6238 } 6239 6240 case Instruction::Mul: { 6241 SmallVector<const SCEV *, 4> MulOps; 6242 do { 6243 if (BO->Op) { 6244 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6245 MulOps.push_back(OpSCEV); 6246 break; 6247 } 6248 6249 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6250 if (Flags != SCEV::FlagAnyWrap) { 6251 MulOps.push_back( 6252 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6253 break; 6254 } 6255 } 6256 6257 MulOps.push_back(getSCEV(BO->RHS)); 6258 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6259 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6260 MulOps.push_back(getSCEV(BO->LHS)); 6261 break; 6262 } 6263 BO = NewBO; 6264 } while (true); 6265 6266 return getMulExpr(MulOps); 6267 } 6268 case Instruction::UDiv: 6269 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6270 case Instruction::URem: 6271 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6272 case Instruction::Sub: { 6273 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6274 if (BO->Op) 6275 Flags = getNoWrapFlagsFromUB(BO->Op); 6276 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6277 } 6278 case Instruction::And: 6279 // For an expression like x&255 that merely masks off the high bits, 6280 // use zext(trunc(x)) as the SCEV expression. 6281 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6282 if (CI->isZero()) 6283 return getSCEV(BO->RHS); 6284 if (CI->isMinusOne()) 6285 return getSCEV(BO->LHS); 6286 const APInt &A = CI->getValue(); 6287 6288 // Instcombine's ShrinkDemandedConstant may strip bits out of 6289 // constants, obscuring what would otherwise be a low-bits mask. 6290 // Use computeKnownBits to compute what ShrinkDemandedConstant 6291 // knew about to reconstruct a low-bits mask value. 6292 unsigned LZ = A.countLeadingZeros(); 6293 unsigned TZ = A.countTrailingZeros(); 6294 unsigned BitWidth = A.getBitWidth(); 6295 KnownBits Known(BitWidth); 6296 computeKnownBits(BO->LHS, Known, getDataLayout(), 6297 0, &AC, nullptr, &DT); 6298 6299 APInt EffectiveMask = 6300 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6301 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6302 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6303 const SCEV *LHS = getSCEV(BO->LHS); 6304 const SCEV *ShiftedLHS = nullptr; 6305 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6306 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6307 // For an expression like (x * 8) & 8, simplify the multiply. 6308 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6309 unsigned GCD = std::min(MulZeros, TZ); 6310 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6311 SmallVector<const SCEV*, 4> MulOps; 6312 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6313 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6314 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6315 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6316 } 6317 } 6318 if (!ShiftedLHS) 6319 ShiftedLHS = getUDivExpr(LHS, MulCount); 6320 return getMulExpr( 6321 getZeroExtendExpr( 6322 getTruncateExpr(ShiftedLHS, 6323 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6324 BO->LHS->getType()), 6325 MulCount); 6326 } 6327 } 6328 break; 6329 6330 case Instruction::Or: 6331 // If the RHS of the Or is a constant, we may have something like: 6332 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6333 // optimizations will transparently handle this case. 6334 // 6335 // In order for this transformation to be safe, the LHS must be of the 6336 // form X*(2^n) and the Or constant must be less than 2^n. 6337 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6338 const SCEV *LHS = getSCEV(BO->LHS); 6339 const APInt &CIVal = CI->getValue(); 6340 if (GetMinTrailingZeros(LHS) >= 6341 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6342 // Build a plain add SCEV. 6343 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6344 // If the LHS of the add was an addrec and it has no-wrap flags, 6345 // transfer the no-wrap flags, since an or won't introduce a wrap. 6346 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6347 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6348 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6349 OldAR->getNoWrapFlags()); 6350 } 6351 return S; 6352 } 6353 } 6354 break; 6355 6356 case Instruction::Xor: 6357 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6358 // If the RHS of xor is -1, then this is a not operation. 6359 if (CI->isMinusOne()) 6360 return getNotSCEV(getSCEV(BO->LHS)); 6361 6362 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6363 // This is a variant of the check for xor with -1, and it handles 6364 // the case where instcombine has trimmed non-demanded bits out 6365 // of an xor with -1. 6366 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6367 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6368 if (LBO->getOpcode() == Instruction::And && 6369 LCI->getValue() == CI->getValue()) 6370 if (const SCEVZeroExtendExpr *Z = 6371 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6372 Type *UTy = BO->LHS->getType(); 6373 const SCEV *Z0 = Z->getOperand(); 6374 Type *Z0Ty = Z0->getType(); 6375 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6376 6377 // If C is a low-bits mask, the zero extend is serving to 6378 // mask off the high bits. Complement the operand and 6379 // re-apply the zext. 6380 if (CI->getValue().isMask(Z0TySize)) 6381 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6382 6383 // If C is a single bit, it may be in the sign-bit position 6384 // before the zero-extend. In this case, represent the xor 6385 // using an add, which is equivalent, and re-apply the zext. 6386 APInt Trunc = CI->getValue().trunc(Z0TySize); 6387 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6388 Trunc.isSignMask()) 6389 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6390 UTy); 6391 } 6392 } 6393 break; 6394 6395 case Instruction::Shl: 6396 // Turn shift left of a constant amount into a multiply. 6397 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6398 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6399 6400 // If the shift count is not less than the bitwidth, the result of 6401 // the shift is undefined. Don't try to analyze it, because the 6402 // resolution chosen here may differ from the resolution chosen in 6403 // other parts of the compiler. 6404 if (SA->getValue().uge(BitWidth)) 6405 break; 6406 6407 // It is currently not resolved how to interpret NSW for left 6408 // shift by BitWidth - 1, so we avoid applying flags in that 6409 // case. Remove this check (or this comment) once the situation 6410 // is resolved. See 6411 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6412 // and http://reviews.llvm.org/D8890 . 6413 auto Flags = SCEV::FlagAnyWrap; 6414 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6415 Flags = getNoWrapFlagsFromUB(BO->Op); 6416 6417 Constant *X = ConstantInt::get( 6418 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6419 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6420 } 6421 break; 6422 6423 case Instruction::AShr: { 6424 // AShr X, C, where C is a constant. 6425 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6426 if (!CI) 6427 break; 6428 6429 Type *OuterTy = BO->LHS->getType(); 6430 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6431 // If the shift count is not less than the bitwidth, the result of 6432 // the shift is undefined. Don't try to analyze it, because the 6433 // resolution chosen here may differ from the resolution chosen in 6434 // other parts of the compiler. 6435 if (CI->getValue().uge(BitWidth)) 6436 break; 6437 6438 if (CI->isZero()) 6439 return getSCEV(BO->LHS); // shift by zero --> noop 6440 6441 uint64_t AShrAmt = CI->getZExtValue(); 6442 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6443 6444 Operator *L = dyn_cast<Operator>(BO->LHS); 6445 if (L && L->getOpcode() == Instruction::Shl) { 6446 // X = Shl A, n 6447 // Y = AShr X, m 6448 // Both n and m are constant. 6449 6450 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6451 if (L->getOperand(1) == BO->RHS) 6452 // For a two-shift sext-inreg, i.e. n = m, 6453 // use sext(trunc(x)) as the SCEV expression. 6454 return getSignExtendExpr( 6455 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6456 6457 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6458 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6459 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6460 if (ShlAmt > AShrAmt) { 6461 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6462 // expression. We already checked that ShlAmt < BitWidth, so 6463 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6464 // ShlAmt - AShrAmt < Amt. 6465 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6466 ShlAmt - AShrAmt); 6467 return getSignExtendExpr( 6468 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6469 getConstant(Mul)), OuterTy); 6470 } 6471 } 6472 } 6473 break; 6474 } 6475 } 6476 } 6477 6478 switch (U->getOpcode()) { 6479 case Instruction::Trunc: 6480 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6481 6482 case Instruction::ZExt: 6483 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6484 6485 case Instruction::SExt: 6486 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6487 // The NSW flag of a subtract does not always survive the conversion to 6488 // A + (-1)*B. By pushing sign extension onto its operands we are much 6489 // more likely to preserve NSW and allow later AddRec optimisations. 6490 // 6491 // NOTE: This is effectively duplicating this logic from getSignExtend: 6492 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6493 // but by that point the NSW information has potentially been lost. 6494 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6495 Type *Ty = U->getType(); 6496 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6497 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6498 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6499 } 6500 } 6501 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6502 6503 case Instruction::BitCast: 6504 // BitCasts are no-op casts so we just eliminate the cast. 6505 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6506 return getSCEV(U->getOperand(0)); 6507 break; 6508 6509 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6510 // lead to pointer expressions which cannot safely be expanded to GEPs, 6511 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6512 // simplifying integer expressions. 6513 6514 case Instruction::GetElementPtr: 6515 return createNodeForGEP(cast<GEPOperator>(U)); 6516 6517 case Instruction::PHI: 6518 return createNodeForPHI(cast<PHINode>(U)); 6519 6520 case Instruction::Select: 6521 // U can also be a select constant expr, which let fall through. Since 6522 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6523 // constant expressions cannot have instructions as operands, we'd have 6524 // returned getUnknown for a select constant expressions anyway. 6525 if (isa<Instruction>(U)) 6526 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6527 U->getOperand(1), U->getOperand(2)); 6528 break; 6529 6530 case Instruction::Call: 6531 case Instruction::Invoke: 6532 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6533 return getSCEV(RV); 6534 break; 6535 } 6536 6537 return getUnknown(V); 6538 } 6539 6540 //===----------------------------------------------------------------------===// 6541 // Iteration Count Computation Code 6542 // 6543 6544 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6545 if (!ExitCount) 6546 return 0; 6547 6548 ConstantInt *ExitConst = ExitCount->getValue(); 6549 6550 // Guard against huge trip counts. 6551 if (ExitConst->getValue().getActiveBits() > 32) 6552 return 0; 6553 6554 // In case of integer overflow, this returns 0, which is correct. 6555 return ((unsigned)ExitConst->getZExtValue()) + 1; 6556 } 6557 6558 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6559 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6560 return getSmallConstantTripCount(L, ExitingBB); 6561 6562 // No trip count information for multiple exits. 6563 return 0; 6564 } 6565 6566 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6567 BasicBlock *ExitingBlock) { 6568 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6569 assert(L->isLoopExiting(ExitingBlock) && 6570 "Exiting block must actually branch out of the loop!"); 6571 const SCEVConstant *ExitCount = 6572 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6573 return getConstantTripCount(ExitCount); 6574 } 6575 6576 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6577 const auto *MaxExitCount = 6578 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 6579 return getConstantTripCount(MaxExitCount); 6580 } 6581 6582 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6583 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6584 return getSmallConstantTripMultiple(L, ExitingBB); 6585 6586 // No trip multiple information for multiple exits. 6587 return 0; 6588 } 6589 6590 /// Returns the largest constant divisor of the trip count of this loop as a 6591 /// normal unsigned value, if possible. This means that the actual trip count is 6592 /// always a multiple of the returned value (don't forget the trip count could 6593 /// very well be zero as well!). 6594 /// 6595 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6596 /// multiple of a constant (which is also the case if the trip count is simply 6597 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6598 /// if the trip count is very large (>= 2^32). 6599 /// 6600 /// As explained in the comments for getSmallConstantTripCount, this assumes 6601 /// that control exits the loop via ExitingBlock. 6602 unsigned 6603 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6604 BasicBlock *ExitingBlock) { 6605 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6606 assert(L->isLoopExiting(ExitingBlock) && 6607 "Exiting block must actually branch out of the loop!"); 6608 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6609 if (ExitCount == getCouldNotCompute()) 6610 return 1; 6611 6612 // Get the trip count from the BE count by adding 1. 6613 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6614 6615 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6616 if (!TC) 6617 // Attempt to factor more general cases. Returns the greatest power of 6618 // two divisor. If overflow happens, the trip count expression is still 6619 // divisible by the greatest power of 2 divisor returned. 6620 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6621 6622 ConstantInt *Result = TC->getValue(); 6623 6624 // Guard against huge trip counts (this requires checking 6625 // for zero to handle the case where the trip count == -1 and the 6626 // addition wraps). 6627 if (!Result || Result->getValue().getActiveBits() > 32 || 6628 Result->getValue().getActiveBits() == 0) 6629 return 1; 6630 6631 return (unsigned)Result->getZExtValue(); 6632 } 6633 6634 /// Get the expression for the number of loop iterations for which this loop is 6635 /// guaranteed not to exit via ExitingBlock. Otherwise return 6636 /// SCEVCouldNotCompute. 6637 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6638 BasicBlock *ExitingBlock) { 6639 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6640 } 6641 6642 const SCEV * 6643 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6644 SCEVUnionPredicate &Preds) { 6645 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6646 } 6647 6648 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6649 return getBackedgeTakenInfo(L).getExact(L, this); 6650 } 6651 6652 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6653 /// known never to be less than the actual backedge taken count. 6654 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 6655 return getBackedgeTakenInfo(L).getMax(this); 6656 } 6657 6658 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6659 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6660 } 6661 6662 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6663 static void 6664 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6665 BasicBlock *Header = L->getHeader(); 6666 6667 // Push all Loop-header PHIs onto the Worklist stack. 6668 for (PHINode &PN : Header->phis()) 6669 Worklist.push_back(&PN); 6670 } 6671 6672 const ScalarEvolution::BackedgeTakenInfo & 6673 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6674 auto &BTI = getBackedgeTakenInfo(L); 6675 if (BTI.hasFullInfo()) 6676 return BTI; 6677 6678 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6679 6680 if (!Pair.second) 6681 return Pair.first->second; 6682 6683 BackedgeTakenInfo Result = 6684 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6685 6686 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6687 } 6688 6689 const ScalarEvolution::BackedgeTakenInfo & 6690 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6691 // Initially insert an invalid entry for this loop. If the insertion 6692 // succeeds, proceed to actually compute a backedge-taken count and 6693 // update the value. The temporary CouldNotCompute value tells SCEV 6694 // code elsewhere that it shouldn't attempt to request a new 6695 // backedge-taken count, which could result in infinite recursion. 6696 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6697 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6698 if (!Pair.second) 6699 return Pair.first->second; 6700 6701 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6702 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6703 // must be cleared in this scope. 6704 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6705 6706 // In product build, there are no usage of statistic. 6707 (void)NumTripCountsComputed; 6708 (void)NumTripCountsNotComputed; 6709 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6710 const SCEV *BEExact = Result.getExact(L, this); 6711 if (BEExact != getCouldNotCompute()) { 6712 assert(isLoopInvariant(BEExact, L) && 6713 isLoopInvariant(Result.getMax(this), L) && 6714 "Computed backedge-taken count isn't loop invariant for loop!"); 6715 ++NumTripCountsComputed; 6716 } 6717 else if (Result.getMax(this) == getCouldNotCompute() && 6718 isa<PHINode>(L->getHeader()->begin())) { 6719 // Only count loops that have phi nodes as not being computable. 6720 ++NumTripCountsNotComputed; 6721 } 6722 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6723 6724 // Now that we know more about the trip count for this loop, forget any 6725 // existing SCEV values for PHI nodes in this loop since they are only 6726 // conservative estimates made without the benefit of trip count 6727 // information. This is similar to the code in forgetLoop, except that 6728 // it handles SCEVUnknown PHI nodes specially. 6729 if (Result.hasAnyInfo()) { 6730 SmallVector<Instruction *, 16> Worklist; 6731 PushLoopPHIs(L, Worklist); 6732 6733 SmallPtrSet<Instruction *, 8> Discovered; 6734 while (!Worklist.empty()) { 6735 Instruction *I = Worklist.pop_back_val(); 6736 6737 ValueExprMapType::iterator It = 6738 ValueExprMap.find_as(static_cast<Value *>(I)); 6739 if (It != ValueExprMap.end()) { 6740 const SCEV *Old = It->second; 6741 6742 // SCEVUnknown for a PHI either means that it has an unrecognized 6743 // structure, or it's a PHI that's in the progress of being computed 6744 // by createNodeForPHI. In the former case, additional loop trip 6745 // count information isn't going to change anything. In the later 6746 // case, createNodeForPHI will perform the necessary updates on its 6747 // own when it gets to that point. 6748 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6749 eraseValueFromMap(It->first); 6750 forgetMemoizedResults(Old); 6751 } 6752 if (PHINode *PN = dyn_cast<PHINode>(I)) 6753 ConstantEvolutionLoopExitValue.erase(PN); 6754 } 6755 6756 // Since we don't need to invalidate anything for correctness and we're 6757 // only invalidating to make SCEV's results more precise, we get to stop 6758 // early to avoid invalidating too much. This is especially important in 6759 // cases like: 6760 // 6761 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6762 // loop0: 6763 // %pn0 = phi 6764 // ... 6765 // loop1: 6766 // %pn1 = phi 6767 // ... 6768 // 6769 // where both loop0 and loop1's backedge taken count uses the SCEV 6770 // expression for %v. If we don't have the early stop below then in cases 6771 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6772 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6773 // count for loop1, effectively nullifying SCEV's trip count cache. 6774 for (auto *U : I->users()) 6775 if (auto *I = dyn_cast<Instruction>(U)) { 6776 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6777 if (LoopForUser && L->contains(LoopForUser) && 6778 Discovered.insert(I).second) 6779 Worklist.push_back(I); 6780 } 6781 } 6782 } 6783 6784 // Re-lookup the insert position, since the call to 6785 // computeBackedgeTakenCount above could result in a 6786 // recusive call to getBackedgeTakenInfo (on a different 6787 // loop), which would invalidate the iterator computed 6788 // earlier. 6789 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6790 } 6791 6792 void ScalarEvolution::forgetAllLoops() { 6793 // This method is intended to forget all info about loops. It should 6794 // invalidate caches as if the following happened: 6795 // - The trip counts of all loops have changed arbitrarily 6796 // - Every llvm::Value has been updated in place to produce a different 6797 // result. 6798 BackedgeTakenCounts.clear(); 6799 PredicatedBackedgeTakenCounts.clear(); 6800 LoopPropertiesCache.clear(); 6801 ConstantEvolutionLoopExitValue.clear(); 6802 ValueExprMap.clear(); 6803 ValuesAtScopes.clear(); 6804 LoopDispositions.clear(); 6805 BlockDispositions.clear(); 6806 UnsignedRanges.clear(); 6807 SignedRanges.clear(); 6808 ExprValueMap.clear(); 6809 HasRecMap.clear(); 6810 MinTrailingZerosCache.clear(); 6811 PredicatedSCEVRewrites.clear(); 6812 } 6813 6814 void ScalarEvolution::forgetLoop(const Loop *L) { 6815 // Drop any stored trip count value. 6816 auto RemoveLoopFromBackedgeMap = 6817 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6818 auto BTCPos = Map.find(L); 6819 if (BTCPos != Map.end()) { 6820 BTCPos->second.clear(); 6821 Map.erase(BTCPos); 6822 } 6823 }; 6824 6825 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6826 SmallVector<Instruction *, 32> Worklist; 6827 SmallPtrSet<Instruction *, 16> Visited; 6828 6829 // Iterate over all the loops and sub-loops to drop SCEV information. 6830 while (!LoopWorklist.empty()) { 6831 auto *CurrL = LoopWorklist.pop_back_val(); 6832 6833 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6834 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6835 6836 // Drop information about predicated SCEV rewrites for this loop. 6837 for (auto I = PredicatedSCEVRewrites.begin(); 6838 I != PredicatedSCEVRewrites.end();) { 6839 std::pair<const SCEV *, const Loop *> Entry = I->first; 6840 if (Entry.second == CurrL) 6841 PredicatedSCEVRewrites.erase(I++); 6842 else 6843 ++I; 6844 } 6845 6846 auto LoopUsersItr = LoopUsers.find(CurrL); 6847 if (LoopUsersItr != LoopUsers.end()) { 6848 for (auto *S : LoopUsersItr->second) 6849 forgetMemoizedResults(S); 6850 LoopUsers.erase(LoopUsersItr); 6851 } 6852 6853 // Drop information about expressions based on loop-header PHIs. 6854 PushLoopPHIs(CurrL, Worklist); 6855 6856 while (!Worklist.empty()) { 6857 Instruction *I = Worklist.pop_back_val(); 6858 if (!Visited.insert(I).second) 6859 continue; 6860 6861 ValueExprMapType::iterator It = 6862 ValueExprMap.find_as(static_cast<Value *>(I)); 6863 if (It != ValueExprMap.end()) { 6864 eraseValueFromMap(It->first); 6865 forgetMemoizedResults(It->second); 6866 if (PHINode *PN = dyn_cast<PHINode>(I)) 6867 ConstantEvolutionLoopExitValue.erase(PN); 6868 } 6869 6870 PushDefUseChildren(I, Worklist); 6871 } 6872 6873 LoopPropertiesCache.erase(CurrL); 6874 // Forget all contained loops too, to avoid dangling entries in the 6875 // ValuesAtScopes map. 6876 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6877 } 6878 } 6879 6880 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6881 while (Loop *Parent = L->getParentLoop()) 6882 L = Parent; 6883 forgetLoop(L); 6884 } 6885 6886 void ScalarEvolution::forgetValue(Value *V) { 6887 Instruction *I = dyn_cast<Instruction>(V); 6888 if (!I) return; 6889 6890 // Drop information about expressions based on loop-header PHIs. 6891 SmallVector<Instruction *, 16> Worklist; 6892 Worklist.push_back(I); 6893 6894 SmallPtrSet<Instruction *, 8> Visited; 6895 while (!Worklist.empty()) { 6896 I = Worklist.pop_back_val(); 6897 if (!Visited.insert(I).second) 6898 continue; 6899 6900 ValueExprMapType::iterator It = 6901 ValueExprMap.find_as(static_cast<Value *>(I)); 6902 if (It != ValueExprMap.end()) { 6903 eraseValueFromMap(It->first); 6904 forgetMemoizedResults(It->second); 6905 if (PHINode *PN = dyn_cast<PHINode>(I)) 6906 ConstantEvolutionLoopExitValue.erase(PN); 6907 } 6908 6909 PushDefUseChildren(I, Worklist); 6910 } 6911 } 6912 6913 /// Get the exact loop backedge taken count considering all loop exits. A 6914 /// computable result can only be returned for loops with all exiting blocks 6915 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6916 /// is never skipped. This is a valid assumption as long as the loop exits via 6917 /// that test. For precise results, it is the caller's responsibility to specify 6918 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6919 const SCEV * 6920 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6921 SCEVUnionPredicate *Preds) const { 6922 // If any exits were not computable, the loop is not computable. 6923 if (!isComplete() || ExitNotTaken.empty()) 6924 return SE->getCouldNotCompute(); 6925 6926 const BasicBlock *Latch = L->getLoopLatch(); 6927 // All exiting blocks we have collected must dominate the only backedge. 6928 if (!Latch) 6929 return SE->getCouldNotCompute(); 6930 6931 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6932 // count is simply a minimum out of all these calculated exit counts. 6933 SmallVector<const SCEV *, 2> Ops; 6934 for (auto &ENT : ExitNotTaken) { 6935 const SCEV *BECount = ENT.ExactNotTaken; 6936 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6937 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6938 "We should only have known counts for exiting blocks that dominate " 6939 "latch!"); 6940 6941 Ops.push_back(BECount); 6942 6943 if (Preds && !ENT.hasAlwaysTruePredicate()) 6944 Preds->add(ENT.Predicate.get()); 6945 6946 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6947 "Predicate should be always true!"); 6948 } 6949 6950 return SE->getUMinFromMismatchedTypes(Ops); 6951 } 6952 6953 /// Get the exact not taken count for this loop exit. 6954 const SCEV * 6955 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6956 ScalarEvolution *SE) const { 6957 for (auto &ENT : ExitNotTaken) 6958 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6959 return ENT.ExactNotTaken; 6960 6961 return SE->getCouldNotCompute(); 6962 } 6963 6964 /// getMax - Get the max backedge taken count for the loop. 6965 const SCEV * 6966 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6967 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6968 return !ENT.hasAlwaysTruePredicate(); 6969 }; 6970 6971 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6972 return SE->getCouldNotCompute(); 6973 6974 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6975 "No point in having a non-constant max backedge taken count!"); 6976 return getMax(); 6977 } 6978 6979 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6980 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6981 return !ENT.hasAlwaysTruePredicate(); 6982 }; 6983 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6984 } 6985 6986 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6987 ScalarEvolution *SE) const { 6988 if (getMax() && getMax() != SE->getCouldNotCompute() && 6989 SE->hasOperand(getMax(), S)) 6990 return true; 6991 6992 for (auto &ENT : ExitNotTaken) 6993 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6994 SE->hasOperand(ENT.ExactNotTaken, S)) 6995 return true; 6996 6997 return false; 6998 } 6999 7000 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7001 : ExactNotTaken(E), MaxNotTaken(E) { 7002 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7003 isa<SCEVConstant>(MaxNotTaken)) && 7004 "No point in having a non-constant max backedge taken count!"); 7005 } 7006 7007 ScalarEvolution::ExitLimit::ExitLimit( 7008 const SCEV *E, const SCEV *M, bool MaxOrZero, 7009 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7010 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7011 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7012 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7013 "Exact is not allowed to be less precise than Max"); 7014 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7015 isa<SCEVConstant>(MaxNotTaken)) && 7016 "No point in having a non-constant max backedge taken count!"); 7017 for (auto *PredSet : PredSetList) 7018 for (auto *P : *PredSet) 7019 addPredicate(P); 7020 } 7021 7022 ScalarEvolution::ExitLimit::ExitLimit( 7023 const SCEV *E, const SCEV *M, bool MaxOrZero, 7024 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7025 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7026 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7027 isa<SCEVConstant>(MaxNotTaken)) && 7028 "No point in having a non-constant max backedge taken count!"); 7029 } 7030 7031 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7032 bool MaxOrZero) 7033 : ExitLimit(E, M, MaxOrZero, None) { 7034 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7035 isa<SCEVConstant>(MaxNotTaken)) && 7036 "No point in having a non-constant max backedge taken count!"); 7037 } 7038 7039 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7040 /// computable exit into a persistent ExitNotTakenInfo array. 7041 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7042 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 7043 ExitCounts, 7044 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 7045 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 7046 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7047 7048 ExitNotTaken.reserve(ExitCounts.size()); 7049 std::transform( 7050 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7051 [&](const EdgeExitInfo &EEI) { 7052 BasicBlock *ExitBB = EEI.first; 7053 const ExitLimit &EL = EEI.second; 7054 if (EL.Predicates.empty()) 7055 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 7056 7057 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7058 for (auto *Pred : EL.Predicates) 7059 Predicate->add(Pred); 7060 7061 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 7062 }); 7063 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 7064 "No point in having a non-constant max backedge taken count!"); 7065 } 7066 7067 /// Invalidate this result and free the ExitNotTakenInfo array. 7068 void ScalarEvolution::BackedgeTakenInfo::clear() { 7069 ExitNotTaken.clear(); 7070 } 7071 7072 /// Compute the number of times the backedge of the specified loop will execute. 7073 ScalarEvolution::BackedgeTakenInfo 7074 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7075 bool AllowPredicates) { 7076 SmallVector<BasicBlock *, 8> ExitingBlocks; 7077 L->getExitingBlocks(ExitingBlocks); 7078 7079 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7080 7081 SmallVector<EdgeExitInfo, 4> ExitCounts; 7082 bool CouldComputeBECount = true; 7083 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7084 const SCEV *MustExitMaxBECount = nullptr; 7085 const SCEV *MayExitMaxBECount = nullptr; 7086 bool MustExitMaxOrZero = false; 7087 7088 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7089 // and compute maxBECount. 7090 // Do a union of all the predicates here. 7091 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7092 BasicBlock *ExitBB = ExitingBlocks[i]; 7093 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7094 7095 assert((AllowPredicates || EL.Predicates.empty()) && 7096 "Predicated exit limit when predicates are not allowed!"); 7097 7098 // 1. For each exit that can be computed, add an entry to ExitCounts. 7099 // CouldComputeBECount is true only if all exits can be computed. 7100 if (EL.ExactNotTaken == getCouldNotCompute()) 7101 // We couldn't compute an exact value for this exit, so 7102 // we won't be able to compute an exact value for the loop. 7103 CouldComputeBECount = false; 7104 else 7105 ExitCounts.emplace_back(ExitBB, EL); 7106 7107 // 2. Derive the loop's MaxBECount from each exit's max number of 7108 // non-exiting iterations. Partition the loop exits into two kinds: 7109 // LoopMustExits and LoopMayExits. 7110 // 7111 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7112 // is a LoopMayExit. If any computable LoopMustExit is found, then 7113 // MaxBECount is the minimum EL.MaxNotTaken of computable 7114 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7115 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7116 // computable EL.MaxNotTaken. 7117 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7118 DT.dominates(ExitBB, Latch)) { 7119 if (!MustExitMaxBECount) { 7120 MustExitMaxBECount = EL.MaxNotTaken; 7121 MustExitMaxOrZero = EL.MaxOrZero; 7122 } else { 7123 MustExitMaxBECount = 7124 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7125 } 7126 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7127 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7128 MayExitMaxBECount = EL.MaxNotTaken; 7129 else { 7130 MayExitMaxBECount = 7131 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7132 } 7133 } 7134 } 7135 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7136 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7137 // The loop backedge will be taken the maximum or zero times if there's 7138 // a single exit that must be taken the maximum or zero times. 7139 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7140 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7141 MaxBECount, MaxOrZero); 7142 } 7143 7144 ScalarEvolution::ExitLimit 7145 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7146 bool AllowPredicates) { 7147 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7148 // If our exiting block does not dominate the latch, then its connection with 7149 // loop's exit limit may be far from trivial. 7150 const BasicBlock *Latch = L->getLoopLatch(); 7151 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7152 return getCouldNotCompute(); 7153 7154 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7155 Instruction *Term = ExitingBlock->getTerminator(); 7156 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7157 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7158 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7159 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7160 "It should have one successor in loop and one exit block!"); 7161 // Proceed to the next level to examine the exit condition expression. 7162 return computeExitLimitFromCond( 7163 L, BI->getCondition(), ExitIfTrue, 7164 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7165 } 7166 7167 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7168 // For switch, make sure that there is a single exit from the loop. 7169 BasicBlock *Exit = nullptr; 7170 for (auto *SBB : successors(ExitingBlock)) 7171 if (!L->contains(SBB)) { 7172 if (Exit) // Multiple exit successors. 7173 return getCouldNotCompute(); 7174 Exit = SBB; 7175 } 7176 assert(Exit && "Exiting block must have at least one exit"); 7177 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7178 /*ControlsExit=*/IsOnlyExit); 7179 } 7180 7181 return getCouldNotCompute(); 7182 } 7183 7184 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7185 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7186 bool ControlsExit, bool AllowPredicates) { 7187 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7188 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7189 ControlsExit, AllowPredicates); 7190 } 7191 7192 Optional<ScalarEvolution::ExitLimit> 7193 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7194 bool ExitIfTrue, bool ControlsExit, 7195 bool AllowPredicates) { 7196 (void)this->L; 7197 (void)this->ExitIfTrue; 7198 (void)this->AllowPredicates; 7199 7200 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7201 this->AllowPredicates == AllowPredicates && 7202 "Variance in assumed invariant key components!"); 7203 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7204 if (Itr == TripCountMap.end()) 7205 return None; 7206 return Itr->second; 7207 } 7208 7209 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7210 bool ExitIfTrue, 7211 bool ControlsExit, 7212 bool AllowPredicates, 7213 const ExitLimit &EL) { 7214 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7215 this->AllowPredicates == AllowPredicates && 7216 "Variance in assumed invariant key components!"); 7217 7218 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7219 assert(InsertResult.second && "Expected successful insertion!"); 7220 (void)InsertResult; 7221 (void)ExitIfTrue; 7222 } 7223 7224 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7225 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7226 bool ControlsExit, bool AllowPredicates) { 7227 7228 if (auto MaybeEL = 7229 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7230 return *MaybeEL; 7231 7232 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7233 ControlsExit, AllowPredicates); 7234 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7235 return EL; 7236 } 7237 7238 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7239 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7240 bool ControlsExit, bool AllowPredicates) { 7241 // Check if the controlling expression for this loop is an And or Or. 7242 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7243 if (BO->getOpcode() == Instruction::And) { 7244 // Recurse on the operands of the and. 7245 bool EitherMayExit = !ExitIfTrue; 7246 ExitLimit EL0 = computeExitLimitFromCondCached( 7247 Cache, L, BO->getOperand(0), ExitIfTrue, 7248 ControlsExit && !EitherMayExit, AllowPredicates); 7249 ExitLimit EL1 = computeExitLimitFromCondCached( 7250 Cache, L, BO->getOperand(1), ExitIfTrue, 7251 ControlsExit && !EitherMayExit, AllowPredicates); 7252 const SCEV *BECount = getCouldNotCompute(); 7253 const SCEV *MaxBECount = getCouldNotCompute(); 7254 if (EitherMayExit) { 7255 // Both conditions must be true for the loop to continue executing. 7256 // Choose the less conservative count. 7257 if (EL0.ExactNotTaken == getCouldNotCompute() || 7258 EL1.ExactNotTaken == getCouldNotCompute()) 7259 BECount = getCouldNotCompute(); 7260 else 7261 BECount = 7262 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7263 if (EL0.MaxNotTaken == getCouldNotCompute()) 7264 MaxBECount = EL1.MaxNotTaken; 7265 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7266 MaxBECount = EL0.MaxNotTaken; 7267 else 7268 MaxBECount = 7269 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7270 } else { 7271 // Both conditions must be true at the same time for the loop to exit. 7272 // For now, be conservative. 7273 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7274 MaxBECount = EL0.MaxNotTaken; 7275 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7276 BECount = EL0.ExactNotTaken; 7277 } 7278 7279 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7280 // to be more aggressive when computing BECount than when computing 7281 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7282 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7283 // to not. 7284 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7285 !isa<SCEVCouldNotCompute>(BECount)) 7286 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7287 7288 return ExitLimit(BECount, MaxBECount, false, 7289 {&EL0.Predicates, &EL1.Predicates}); 7290 } 7291 if (BO->getOpcode() == Instruction::Or) { 7292 // Recurse on the operands of the or. 7293 bool EitherMayExit = ExitIfTrue; 7294 ExitLimit EL0 = computeExitLimitFromCondCached( 7295 Cache, L, BO->getOperand(0), ExitIfTrue, 7296 ControlsExit && !EitherMayExit, AllowPredicates); 7297 ExitLimit EL1 = computeExitLimitFromCondCached( 7298 Cache, L, BO->getOperand(1), ExitIfTrue, 7299 ControlsExit && !EitherMayExit, AllowPredicates); 7300 const SCEV *BECount = getCouldNotCompute(); 7301 const SCEV *MaxBECount = getCouldNotCompute(); 7302 if (EitherMayExit) { 7303 // Both conditions must be false for the loop to continue executing. 7304 // Choose the less conservative count. 7305 if (EL0.ExactNotTaken == getCouldNotCompute() || 7306 EL1.ExactNotTaken == getCouldNotCompute()) 7307 BECount = getCouldNotCompute(); 7308 else 7309 BECount = 7310 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7311 if (EL0.MaxNotTaken == getCouldNotCompute()) 7312 MaxBECount = EL1.MaxNotTaken; 7313 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7314 MaxBECount = EL0.MaxNotTaken; 7315 else 7316 MaxBECount = 7317 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7318 } else { 7319 // Both conditions must be false at the same time for the loop to exit. 7320 // For now, be conservative. 7321 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7322 MaxBECount = EL0.MaxNotTaken; 7323 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7324 BECount = EL0.ExactNotTaken; 7325 } 7326 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7327 // to be more aggressive when computing BECount than when computing 7328 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7329 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7330 // to not. 7331 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7332 !isa<SCEVCouldNotCompute>(BECount)) 7333 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7334 7335 return ExitLimit(BECount, MaxBECount, false, 7336 {&EL0.Predicates, &EL1.Predicates}); 7337 } 7338 } 7339 7340 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7341 // Proceed to the next level to examine the icmp. 7342 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7343 ExitLimit EL = 7344 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7345 if (EL.hasFullInfo() || !AllowPredicates) 7346 return EL; 7347 7348 // Try again, but use SCEV predicates this time. 7349 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7350 /*AllowPredicates=*/true); 7351 } 7352 7353 // Check for a constant condition. These are normally stripped out by 7354 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7355 // preserve the CFG and is temporarily leaving constant conditions 7356 // in place. 7357 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7358 if (ExitIfTrue == !CI->getZExtValue()) 7359 // The backedge is always taken. 7360 return getCouldNotCompute(); 7361 else 7362 // The backedge is never taken. 7363 return getZero(CI->getType()); 7364 } 7365 7366 // If it's not an integer or pointer comparison then compute it the hard way. 7367 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7368 } 7369 7370 ScalarEvolution::ExitLimit 7371 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7372 ICmpInst *ExitCond, 7373 bool ExitIfTrue, 7374 bool ControlsExit, 7375 bool AllowPredicates) { 7376 // If the condition was exit on true, convert the condition to exit on false 7377 ICmpInst::Predicate Pred; 7378 if (!ExitIfTrue) 7379 Pred = ExitCond->getPredicate(); 7380 else 7381 Pred = ExitCond->getInversePredicate(); 7382 const ICmpInst::Predicate OriginalPred = Pred; 7383 7384 // Handle common loops like: for (X = "string"; *X; ++X) 7385 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7386 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7387 ExitLimit ItCnt = 7388 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7389 if (ItCnt.hasAnyInfo()) 7390 return ItCnt; 7391 } 7392 7393 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7394 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7395 7396 // Try to evaluate any dependencies out of the loop. 7397 LHS = getSCEVAtScope(LHS, L); 7398 RHS = getSCEVAtScope(RHS, L); 7399 7400 // At this point, we would like to compute how many iterations of the 7401 // loop the predicate will return true for these inputs. 7402 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7403 // If there is a loop-invariant, force it into the RHS. 7404 std::swap(LHS, RHS); 7405 Pred = ICmpInst::getSwappedPredicate(Pred); 7406 } 7407 7408 // Simplify the operands before analyzing them. 7409 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7410 7411 // If we have a comparison of a chrec against a constant, try to use value 7412 // ranges to answer this query. 7413 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7414 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7415 if (AddRec->getLoop() == L) { 7416 // Form the constant range. 7417 ConstantRange CompRange = 7418 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7419 7420 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7421 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7422 } 7423 7424 switch (Pred) { 7425 case ICmpInst::ICMP_NE: { // while (X != Y) 7426 // Convert to: while (X-Y != 0) 7427 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7428 AllowPredicates); 7429 if (EL.hasAnyInfo()) return EL; 7430 break; 7431 } 7432 case ICmpInst::ICMP_EQ: { // while (X == Y) 7433 // Convert to: while (X-Y == 0) 7434 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7435 if (EL.hasAnyInfo()) return EL; 7436 break; 7437 } 7438 case ICmpInst::ICMP_SLT: 7439 case ICmpInst::ICMP_ULT: { // while (X < Y) 7440 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7441 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7442 AllowPredicates); 7443 if (EL.hasAnyInfo()) return EL; 7444 break; 7445 } 7446 case ICmpInst::ICMP_SGT: 7447 case ICmpInst::ICMP_UGT: { // while (X > Y) 7448 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7449 ExitLimit EL = 7450 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7451 AllowPredicates); 7452 if (EL.hasAnyInfo()) return EL; 7453 break; 7454 } 7455 default: 7456 break; 7457 } 7458 7459 auto *ExhaustiveCount = 7460 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7461 7462 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7463 return ExhaustiveCount; 7464 7465 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7466 ExitCond->getOperand(1), L, OriginalPred); 7467 } 7468 7469 ScalarEvolution::ExitLimit 7470 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7471 SwitchInst *Switch, 7472 BasicBlock *ExitingBlock, 7473 bool ControlsExit) { 7474 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7475 7476 // Give up if the exit is the default dest of a switch. 7477 if (Switch->getDefaultDest() == ExitingBlock) 7478 return getCouldNotCompute(); 7479 7480 assert(L->contains(Switch->getDefaultDest()) && 7481 "Default case must not exit the loop!"); 7482 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7483 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7484 7485 // while (X != Y) --> while (X-Y != 0) 7486 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7487 if (EL.hasAnyInfo()) 7488 return EL; 7489 7490 return getCouldNotCompute(); 7491 } 7492 7493 static ConstantInt * 7494 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7495 ScalarEvolution &SE) { 7496 const SCEV *InVal = SE.getConstant(C); 7497 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7498 assert(isa<SCEVConstant>(Val) && 7499 "Evaluation of SCEV at constant didn't fold correctly?"); 7500 return cast<SCEVConstant>(Val)->getValue(); 7501 } 7502 7503 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7504 /// compute the backedge execution count. 7505 ScalarEvolution::ExitLimit 7506 ScalarEvolution::computeLoadConstantCompareExitLimit( 7507 LoadInst *LI, 7508 Constant *RHS, 7509 const Loop *L, 7510 ICmpInst::Predicate predicate) { 7511 if (LI->isVolatile()) return getCouldNotCompute(); 7512 7513 // Check to see if the loaded pointer is a getelementptr of a global. 7514 // TODO: Use SCEV instead of manually grubbing with GEPs. 7515 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7516 if (!GEP) return getCouldNotCompute(); 7517 7518 // Make sure that it is really a constant global we are gepping, with an 7519 // initializer, and make sure the first IDX is really 0. 7520 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7521 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7522 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7523 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7524 return getCouldNotCompute(); 7525 7526 // Okay, we allow one non-constant index into the GEP instruction. 7527 Value *VarIdx = nullptr; 7528 std::vector<Constant*> Indexes; 7529 unsigned VarIdxNum = 0; 7530 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7531 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7532 Indexes.push_back(CI); 7533 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7534 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7535 VarIdx = GEP->getOperand(i); 7536 VarIdxNum = i-2; 7537 Indexes.push_back(nullptr); 7538 } 7539 7540 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7541 if (!VarIdx) 7542 return getCouldNotCompute(); 7543 7544 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7545 // Check to see if X is a loop variant variable value now. 7546 const SCEV *Idx = getSCEV(VarIdx); 7547 Idx = getSCEVAtScope(Idx, L); 7548 7549 // We can only recognize very limited forms of loop index expressions, in 7550 // particular, only affine AddRec's like {C1,+,C2}. 7551 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7552 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7553 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7554 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7555 return getCouldNotCompute(); 7556 7557 unsigned MaxSteps = MaxBruteForceIterations; 7558 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7559 ConstantInt *ItCst = ConstantInt::get( 7560 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7561 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7562 7563 // Form the GEP offset. 7564 Indexes[VarIdxNum] = Val; 7565 7566 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7567 Indexes); 7568 if (!Result) break; // Cannot compute! 7569 7570 // Evaluate the condition for this iteration. 7571 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7572 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7573 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7574 ++NumArrayLenItCounts; 7575 return getConstant(ItCst); // Found terminating iteration! 7576 } 7577 } 7578 return getCouldNotCompute(); 7579 } 7580 7581 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7582 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7583 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7584 if (!RHS) 7585 return getCouldNotCompute(); 7586 7587 const BasicBlock *Latch = L->getLoopLatch(); 7588 if (!Latch) 7589 return getCouldNotCompute(); 7590 7591 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7592 if (!Predecessor) 7593 return getCouldNotCompute(); 7594 7595 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7596 // Return LHS in OutLHS and shift_opt in OutOpCode. 7597 auto MatchPositiveShift = 7598 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7599 7600 using namespace PatternMatch; 7601 7602 ConstantInt *ShiftAmt; 7603 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7604 OutOpCode = Instruction::LShr; 7605 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7606 OutOpCode = Instruction::AShr; 7607 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7608 OutOpCode = Instruction::Shl; 7609 else 7610 return false; 7611 7612 return ShiftAmt->getValue().isStrictlyPositive(); 7613 }; 7614 7615 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7616 // 7617 // loop: 7618 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7619 // %iv.shifted = lshr i32 %iv, <positive constant> 7620 // 7621 // Return true on a successful match. Return the corresponding PHI node (%iv 7622 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7623 auto MatchShiftRecurrence = 7624 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7625 Optional<Instruction::BinaryOps> PostShiftOpCode; 7626 7627 { 7628 Instruction::BinaryOps OpC; 7629 Value *V; 7630 7631 // If we encounter a shift instruction, "peel off" the shift operation, 7632 // and remember that we did so. Later when we inspect %iv's backedge 7633 // value, we will make sure that the backedge value uses the same 7634 // operation. 7635 // 7636 // Note: the peeled shift operation does not have to be the same 7637 // instruction as the one feeding into the PHI's backedge value. We only 7638 // really care about it being the same *kind* of shift instruction -- 7639 // that's all that is required for our later inferences to hold. 7640 if (MatchPositiveShift(LHS, V, OpC)) { 7641 PostShiftOpCode = OpC; 7642 LHS = V; 7643 } 7644 } 7645 7646 PNOut = dyn_cast<PHINode>(LHS); 7647 if (!PNOut || PNOut->getParent() != L->getHeader()) 7648 return false; 7649 7650 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7651 Value *OpLHS; 7652 7653 return 7654 // The backedge value for the PHI node must be a shift by a positive 7655 // amount 7656 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7657 7658 // of the PHI node itself 7659 OpLHS == PNOut && 7660 7661 // and the kind of shift should be match the kind of shift we peeled 7662 // off, if any. 7663 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7664 }; 7665 7666 PHINode *PN; 7667 Instruction::BinaryOps OpCode; 7668 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7669 return getCouldNotCompute(); 7670 7671 const DataLayout &DL = getDataLayout(); 7672 7673 // The key rationale for this optimization is that for some kinds of shift 7674 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7675 // within a finite number of iterations. If the condition guarding the 7676 // backedge (in the sense that the backedge is taken if the condition is true) 7677 // is false for the value the shift recurrence stabilizes to, then we know 7678 // that the backedge is taken only a finite number of times. 7679 7680 ConstantInt *StableValue = nullptr; 7681 switch (OpCode) { 7682 default: 7683 llvm_unreachable("Impossible case!"); 7684 7685 case Instruction::AShr: { 7686 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7687 // bitwidth(K) iterations. 7688 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7689 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7690 Predecessor->getTerminator(), &DT); 7691 auto *Ty = cast<IntegerType>(RHS->getType()); 7692 if (Known.isNonNegative()) 7693 StableValue = ConstantInt::get(Ty, 0); 7694 else if (Known.isNegative()) 7695 StableValue = ConstantInt::get(Ty, -1, true); 7696 else 7697 return getCouldNotCompute(); 7698 7699 break; 7700 } 7701 case Instruction::LShr: 7702 case Instruction::Shl: 7703 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7704 // stabilize to 0 in at most bitwidth(K) iterations. 7705 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7706 break; 7707 } 7708 7709 auto *Result = 7710 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7711 assert(Result->getType()->isIntegerTy(1) && 7712 "Otherwise cannot be an operand to a branch instruction"); 7713 7714 if (Result->isZeroValue()) { 7715 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7716 const SCEV *UpperBound = 7717 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7718 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7719 } 7720 7721 return getCouldNotCompute(); 7722 } 7723 7724 /// Return true if we can constant fold an instruction of the specified type, 7725 /// assuming that all operands were constants. 7726 static bool CanConstantFold(const Instruction *I) { 7727 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7728 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7729 isa<LoadInst>(I)) 7730 return true; 7731 7732 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7733 if (const Function *F = CI->getCalledFunction()) 7734 return canConstantFoldCallTo(CI, F); 7735 return false; 7736 } 7737 7738 /// Determine whether this instruction can constant evolve within this loop 7739 /// assuming its operands can all constant evolve. 7740 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7741 // An instruction outside of the loop can't be derived from a loop PHI. 7742 if (!L->contains(I)) return false; 7743 7744 if (isa<PHINode>(I)) { 7745 // We don't currently keep track of the control flow needed to evaluate 7746 // PHIs, so we cannot handle PHIs inside of loops. 7747 return L->getHeader() == I->getParent(); 7748 } 7749 7750 // If we won't be able to constant fold this expression even if the operands 7751 // are constants, bail early. 7752 return CanConstantFold(I); 7753 } 7754 7755 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7756 /// recursing through each instruction operand until reaching a loop header phi. 7757 static PHINode * 7758 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7759 DenseMap<Instruction *, PHINode *> &PHIMap, 7760 unsigned Depth) { 7761 if (Depth > MaxConstantEvolvingDepth) 7762 return nullptr; 7763 7764 // Otherwise, we can evaluate this instruction if all of its operands are 7765 // constant or derived from a PHI node themselves. 7766 PHINode *PHI = nullptr; 7767 for (Value *Op : UseInst->operands()) { 7768 if (isa<Constant>(Op)) continue; 7769 7770 Instruction *OpInst = dyn_cast<Instruction>(Op); 7771 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7772 7773 PHINode *P = dyn_cast<PHINode>(OpInst); 7774 if (!P) 7775 // If this operand is already visited, reuse the prior result. 7776 // We may have P != PHI if this is the deepest point at which the 7777 // inconsistent paths meet. 7778 P = PHIMap.lookup(OpInst); 7779 if (!P) { 7780 // Recurse and memoize the results, whether a phi is found or not. 7781 // This recursive call invalidates pointers into PHIMap. 7782 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7783 PHIMap[OpInst] = P; 7784 } 7785 if (!P) 7786 return nullptr; // Not evolving from PHI 7787 if (PHI && PHI != P) 7788 return nullptr; // Evolving from multiple different PHIs. 7789 PHI = P; 7790 } 7791 // This is a expression evolving from a constant PHI! 7792 return PHI; 7793 } 7794 7795 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7796 /// in the loop that V is derived from. We allow arbitrary operations along the 7797 /// way, but the operands of an operation must either be constants or a value 7798 /// derived from a constant PHI. If this expression does not fit with these 7799 /// constraints, return null. 7800 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7801 Instruction *I = dyn_cast<Instruction>(V); 7802 if (!I || !canConstantEvolve(I, L)) return nullptr; 7803 7804 if (PHINode *PN = dyn_cast<PHINode>(I)) 7805 return PN; 7806 7807 // Record non-constant instructions contained by the loop. 7808 DenseMap<Instruction *, PHINode *> PHIMap; 7809 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7810 } 7811 7812 /// EvaluateExpression - Given an expression that passes the 7813 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7814 /// in the loop has the value PHIVal. If we can't fold this expression for some 7815 /// reason, return null. 7816 static Constant *EvaluateExpression(Value *V, const Loop *L, 7817 DenseMap<Instruction *, Constant *> &Vals, 7818 const DataLayout &DL, 7819 const TargetLibraryInfo *TLI) { 7820 // Convenient constant check, but redundant for recursive calls. 7821 if (Constant *C = dyn_cast<Constant>(V)) return C; 7822 Instruction *I = dyn_cast<Instruction>(V); 7823 if (!I) return nullptr; 7824 7825 if (Constant *C = Vals.lookup(I)) return C; 7826 7827 // An instruction inside the loop depends on a value outside the loop that we 7828 // weren't given a mapping for, or a value such as a call inside the loop. 7829 if (!canConstantEvolve(I, L)) return nullptr; 7830 7831 // An unmapped PHI can be due to a branch or another loop inside this loop, 7832 // or due to this not being the initial iteration through a loop where we 7833 // couldn't compute the evolution of this particular PHI last time. 7834 if (isa<PHINode>(I)) return nullptr; 7835 7836 std::vector<Constant*> Operands(I->getNumOperands()); 7837 7838 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7839 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7840 if (!Operand) { 7841 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7842 if (!Operands[i]) return nullptr; 7843 continue; 7844 } 7845 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7846 Vals[Operand] = C; 7847 if (!C) return nullptr; 7848 Operands[i] = C; 7849 } 7850 7851 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7852 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7853 Operands[1], DL, TLI); 7854 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7855 if (!LI->isVolatile()) 7856 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7857 } 7858 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7859 } 7860 7861 7862 // If every incoming value to PN except the one for BB is a specific Constant, 7863 // return that, else return nullptr. 7864 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7865 Constant *IncomingVal = nullptr; 7866 7867 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7868 if (PN->getIncomingBlock(i) == BB) 7869 continue; 7870 7871 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7872 if (!CurrentVal) 7873 return nullptr; 7874 7875 if (IncomingVal != CurrentVal) { 7876 if (IncomingVal) 7877 return nullptr; 7878 IncomingVal = CurrentVal; 7879 } 7880 } 7881 7882 return IncomingVal; 7883 } 7884 7885 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7886 /// in the header of its containing loop, we know the loop executes a 7887 /// constant number of times, and the PHI node is just a recurrence 7888 /// involving constants, fold it. 7889 Constant * 7890 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7891 const APInt &BEs, 7892 const Loop *L) { 7893 auto I = ConstantEvolutionLoopExitValue.find(PN); 7894 if (I != ConstantEvolutionLoopExitValue.end()) 7895 return I->second; 7896 7897 if (BEs.ugt(MaxBruteForceIterations)) 7898 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7899 7900 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7901 7902 DenseMap<Instruction *, Constant *> CurrentIterVals; 7903 BasicBlock *Header = L->getHeader(); 7904 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7905 7906 BasicBlock *Latch = L->getLoopLatch(); 7907 if (!Latch) 7908 return nullptr; 7909 7910 for (PHINode &PHI : Header->phis()) { 7911 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7912 CurrentIterVals[&PHI] = StartCST; 7913 } 7914 if (!CurrentIterVals.count(PN)) 7915 return RetVal = nullptr; 7916 7917 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7918 7919 // Execute the loop symbolically to determine the exit value. 7920 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7921 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7922 7923 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7924 unsigned IterationNum = 0; 7925 const DataLayout &DL = getDataLayout(); 7926 for (; ; ++IterationNum) { 7927 if (IterationNum == NumIterations) 7928 return RetVal = CurrentIterVals[PN]; // Got exit value! 7929 7930 // Compute the value of the PHIs for the next iteration. 7931 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7932 DenseMap<Instruction *, Constant *> NextIterVals; 7933 Constant *NextPHI = 7934 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7935 if (!NextPHI) 7936 return nullptr; // Couldn't evaluate! 7937 NextIterVals[PN] = NextPHI; 7938 7939 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7940 7941 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7942 // cease to be able to evaluate one of them or if they stop evolving, 7943 // because that doesn't necessarily prevent us from computing PN. 7944 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7945 for (const auto &I : CurrentIterVals) { 7946 PHINode *PHI = dyn_cast<PHINode>(I.first); 7947 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7948 PHIsToCompute.emplace_back(PHI, I.second); 7949 } 7950 // We use two distinct loops because EvaluateExpression may invalidate any 7951 // iterators into CurrentIterVals. 7952 for (const auto &I : PHIsToCompute) { 7953 PHINode *PHI = I.first; 7954 Constant *&NextPHI = NextIterVals[PHI]; 7955 if (!NextPHI) { // Not already computed. 7956 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7957 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7958 } 7959 if (NextPHI != I.second) 7960 StoppedEvolving = false; 7961 } 7962 7963 // If all entries in CurrentIterVals == NextIterVals then we can stop 7964 // iterating, the loop can't continue to change. 7965 if (StoppedEvolving) 7966 return RetVal = CurrentIterVals[PN]; 7967 7968 CurrentIterVals.swap(NextIterVals); 7969 } 7970 } 7971 7972 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7973 Value *Cond, 7974 bool ExitWhen) { 7975 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7976 if (!PN) return getCouldNotCompute(); 7977 7978 // If the loop is canonicalized, the PHI will have exactly two entries. 7979 // That's the only form we support here. 7980 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7981 7982 DenseMap<Instruction *, Constant *> CurrentIterVals; 7983 BasicBlock *Header = L->getHeader(); 7984 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7985 7986 BasicBlock *Latch = L->getLoopLatch(); 7987 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7988 7989 for (PHINode &PHI : Header->phis()) { 7990 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7991 CurrentIterVals[&PHI] = StartCST; 7992 } 7993 if (!CurrentIterVals.count(PN)) 7994 return getCouldNotCompute(); 7995 7996 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7997 // the loop symbolically to determine when the condition gets a value of 7998 // "ExitWhen". 7999 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8000 const DataLayout &DL = getDataLayout(); 8001 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8002 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8003 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8004 8005 // Couldn't symbolically evaluate. 8006 if (!CondVal) return getCouldNotCompute(); 8007 8008 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8009 ++NumBruteForceTripCountsComputed; 8010 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8011 } 8012 8013 // Update all the PHI nodes for the next iteration. 8014 DenseMap<Instruction *, Constant *> NextIterVals; 8015 8016 // Create a list of which PHIs we need to compute. We want to do this before 8017 // calling EvaluateExpression on them because that may invalidate iterators 8018 // into CurrentIterVals. 8019 SmallVector<PHINode *, 8> PHIsToCompute; 8020 for (const auto &I : CurrentIterVals) { 8021 PHINode *PHI = dyn_cast<PHINode>(I.first); 8022 if (!PHI || PHI->getParent() != Header) continue; 8023 PHIsToCompute.push_back(PHI); 8024 } 8025 for (PHINode *PHI : PHIsToCompute) { 8026 Constant *&NextPHI = NextIterVals[PHI]; 8027 if (NextPHI) continue; // Already computed! 8028 8029 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8030 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8031 } 8032 CurrentIterVals.swap(NextIterVals); 8033 } 8034 8035 // Too many iterations were needed to evaluate. 8036 return getCouldNotCompute(); 8037 } 8038 8039 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8040 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8041 ValuesAtScopes[V]; 8042 // Check to see if we've folded this expression at this loop before. 8043 for (auto &LS : Values) 8044 if (LS.first == L) 8045 return LS.second ? LS.second : V; 8046 8047 Values.emplace_back(L, nullptr); 8048 8049 // Otherwise compute it. 8050 const SCEV *C = computeSCEVAtScope(V, L); 8051 for (auto &LS : reverse(ValuesAtScopes[V])) 8052 if (LS.first == L) { 8053 LS.second = C; 8054 break; 8055 } 8056 return C; 8057 } 8058 8059 /// This builds up a Constant using the ConstantExpr interface. That way, we 8060 /// will return Constants for objects which aren't represented by a 8061 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8062 /// Returns NULL if the SCEV isn't representable as a Constant. 8063 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8064 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 8065 case scCouldNotCompute: 8066 case scAddRecExpr: 8067 break; 8068 case scConstant: 8069 return cast<SCEVConstant>(V)->getValue(); 8070 case scUnknown: 8071 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8072 case scSignExtend: { 8073 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8074 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8075 return ConstantExpr::getSExt(CastOp, SS->getType()); 8076 break; 8077 } 8078 case scZeroExtend: { 8079 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8080 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8081 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8082 break; 8083 } 8084 case scTruncate: { 8085 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8086 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8087 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8088 break; 8089 } 8090 case scAddExpr: { 8091 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8092 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8093 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8094 unsigned AS = PTy->getAddressSpace(); 8095 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8096 C = ConstantExpr::getBitCast(C, DestPtrTy); 8097 } 8098 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8099 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8100 if (!C2) return nullptr; 8101 8102 // First pointer! 8103 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8104 unsigned AS = C2->getType()->getPointerAddressSpace(); 8105 std::swap(C, C2); 8106 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8107 // The offsets have been converted to bytes. We can add bytes to an 8108 // i8* by GEP with the byte count in the first index. 8109 C = ConstantExpr::getBitCast(C, DestPtrTy); 8110 } 8111 8112 // Don't bother trying to sum two pointers. We probably can't 8113 // statically compute a load that results from it anyway. 8114 if (C2->getType()->isPointerTy()) 8115 return nullptr; 8116 8117 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8118 if (PTy->getElementType()->isStructTy()) 8119 C2 = ConstantExpr::getIntegerCast( 8120 C2, Type::getInt32Ty(C->getContext()), true); 8121 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8122 } else 8123 C = ConstantExpr::getAdd(C, C2); 8124 } 8125 return C; 8126 } 8127 break; 8128 } 8129 case scMulExpr: { 8130 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8131 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8132 // Don't bother with pointers at all. 8133 if (C->getType()->isPointerTy()) return nullptr; 8134 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8135 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8136 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8137 C = ConstantExpr::getMul(C, C2); 8138 } 8139 return C; 8140 } 8141 break; 8142 } 8143 case scUDivExpr: { 8144 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8145 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8146 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8147 if (LHS->getType() == RHS->getType()) 8148 return ConstantExpr::getUDiv(LHS, RHS); 8149 break; 8150 } 8151 case scSMaxExpr: 8152 case scUMaxExpr: 8153 break; // TODO: smax, umax. 8154 } 8155 return nullptr; 8156 } 8157 8158 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8159 if (isa<SCEVConstant>(V)) return V; 8160 8161 // If this instruction is evolved from a constant-evolving PHI, compute the 8162 // exit value from the loop without using SCEVs. 8163 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8164 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8165 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8166 const Loop *LI = this->LI[I->getParent()]; 8167 // Looking for loop exit value. 8168 if (LI && LI->getParentLoop() == L && 8169 PN->getParent() == LI->getHeader()) { 8170 // Okay, there is no closed form solution for the PHI node. Check 8171 // to see if the loop that contains it has a known backedge-taken 8172 // count. If so, we may be able to force computation of the exit 8173 // value. 8174 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8175 if (const SCEVConstant *BTCC = 8176 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8177 8178 // This trivial case can show up in some degenerate cases where 8179 // the incoming IR has not yet been fully simplified. 8180 if (BTCC->getValue()->isZero()) { 8181 Value *InitValue = nullptr; 8182 bool MultipleInitValues = false; 8183 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8184 if (!LI->contains(PN->getIncomingBlock(i))) { 8185 if (!InitValue) 8186 InitValue = PN->getIncomingValue(i); 8187 else if (InitValue != PN->getIncomingValue(i)) { 8188 MultipleInitValues = true; 8189 break; 8190 } 8191 } 8192 if (!MultipleInitValues && InitValue) 8193 return getSCEV(InitValue); 8194 } 8195 } 8196 // Okay, we know how many times the containing loop executes. If 8197 // this is a constant evolving PHI node, get the final value at 8198 // the specified iteration number. 8199 Constant *RV = 8200 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8201 if (RV) return getSCEV(RV); 8202 } 8203 } 8204 } 8205 8206 // Okay, this is an expression that we cannot symbolically evaluate 8207 // into a SCEV. Check to see if it's possible to symbolically evaluate 8208 // the arguments into constants, and if so, try to constant propagate the 8209 // result. This is particularly useful for computing loop exit values. 8210 if (CanConstantFold(I)) { 8211 SmallVector<Constant *, 4> Operands; 8212 bool MadeImprovement = false; 8213 for (Value *Op : I->operands()) { 8214 if (Constant *C = dyn_cast<Constant>(Op)) { 8215 Operands.push_back(C); 8216 continue; 8217 } 8218 8219 // If any of the operands is non-constant and if they are 8220 // non-integer and non-pointer, don't even try to analyze them 8221 // with scev techniques. 8222 if (!isSCEVable(Op->getType())) 8223 return V; 8224 8225 const SCEV *OrigV = getSCEV(Op); 8226 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8227 MadeImprovement |= OrigV != OpV; 8228 8229 Constant *C = BuildConstantFromSCEV(OpV); 8230 if (!C) return V; 8231 if (C->getType() != Op->getType()) 8232 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8233 Op->getType(), 8234 false), 8235 C, Op->getType()); 8236 Operands.push_back(C); 8237 } 8238 8239 // Check to see if getSCEVAtScope actually made an improvement. 8240 if (MadeImprovement) { 8241 Constant *C = nullptr; 8242 const DataLayout &DL = getDataLayout(); 8243 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8244 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8245 Operands[1], DL, &TLI); 8246 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8247 if (!LI->isVolatile()) 8248 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8249 } else 8250 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8251 if (!C) return V; 8252 return getSCEV(C); 8253 } 8254 } 8255 } 8256 8257 // This is some other type of SCEVUnknown, just return it. 8258 return V; 8259 } 8260 8261 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8262 // Avoid performing the look-up in the common case where the specified 8263 // expression has no loop-variant portions. 8264 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8265 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8266 if (OpAtScope != Comm->getOperand(i)) { 8267 // Okay, at least one of these operands is loop variant but might be 8268 // foldable. Build a new instance of the folded commutative expression. 8269 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8270 Comm->op_begin()+i); 8271 NewOps.push_back(OpAtScope); 8272 8273 for (++i; i != e; ++i) { 8274 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8275 NewOps.push_back(OpAtScope); 8276 } 8277 if (isa<SCEVAddExpr>(Comm)) 8278 return getAddExpr(NewOps); 8279 if (isa<SCEVMulExpr>(Comm)) 8280 return getMulExpr(NewOps); 8281 if (isa<SCEVSMaxExpr>(Comm)) 8282 return getSMaxExpr(NewOps); 8283 if (isa<SCEVUMaxExpr>(Comm)) 8284 return getUMaxExpr(NewOps); 8285 llvm_unreachable("Unknown commutative SCEV type!"); 8286 } 8287 } 8288 // If we got here, all operands are loop invariant. 8289 return Comm; 8290 } 8291 8292 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8293 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8294 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8295 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8296 return Div; // must be loop invariant 8297 return getUDivExpr(LHS, RHS); 8298 } 8299 8300 // If this is a loop recurrence for a loop that does not contain L, then we 8301 // are dealing with the final value computed by the loop. 8302 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8303 // First, attempt to evaluate each operand. 8304 // Avoid performing the look-up in the common case where the specified 8305 // expression has no loop-variant portions. 8306 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8307 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8308 if (OpAtScope == AddRec->getOperand(i)) 8309 continue; 8310 8311 // Okay, at least one of these operands is loop variant but might be 8312 // foldable. Build a new instance of the folded commutative expression. 8313 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8314 AddRec->op_begin()+i); 8315 NewOps.push_back(OpAtScope); 8316 for (++i; i != e; ++i) 8317 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8318 8319 const SCEV *FoldedRec = 8320 getAddRecExpr(NewOps, AddRec->getLoop(), 8321 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8322 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8323 // The addrec may be folded to a nonrecurrence, for example, if the 8324 // induction variable is multiplied by zero after constant folding. Go 8325 // ahead and return the folded value. 8326 if (!AddRec) 8327 return FoldedRec; 8328 break; 8329 } 8330 8331 // If the scope is outside the addrec's loop, evaluate it by using the 8332 // loop exit value of the addrec. 8333 if (!AddRec->getLoop()->contains(L)) { 8334 // To evaluate this recurrence, we need to know how many times the AddRec 8335 // loop iterates. Compute this now. 8336 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8337 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8338 8339 // Then, evaluate the AddRec. 8340 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8341 } 8342 8343 return AddRec; 8344 } 8345 8346 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8347 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8348 if (Op == Cast->getOperand()) 8349 return Cast; // must be loop invariant 8350 return getZeroExtendExpr(Op, Cast->getType()); 8351 } 8352 8353 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8354 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8355 if (Op == Cast->getOperand()) 8356 return Cast; // must be loop invariant 8357 return getSignExtendExpr(Op, Cast->getType()); 8358 } 8359 8360 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8361 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8362 if (Op == Cast->getOperand()) 8363 return Cast; // must be loop invariant 8364 return getTruncateExpr(Op, Cast->getType()); 8365 } 8366 8367 llvm_unreachable("Unknown SCEV type!"); 8368 } 8369 8370 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8371 return getSCEVAtScope(getSCEV(V), L); 8372 } 8373 8374 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8375 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8376 return stripInjectiveFunctions(ZExt->getOperand()); 8377 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8378 return stripInjectiveFunctions(SExt->getOperand()); 8379 return S; 8380 } 8381 8382 /// Finds the minimum unsigned root of the following equation: 8383 /// 8384 /// A * X = B (mod N) 8385 /// 8386 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8387 /// A and B isn't important. 8388 /// 8389 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8390 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8391 ScalarEvolution &SE) { 8392 uint32_t BW = A.getBitWidth(); 8393 assert(BW == SE.getTypeSizeInBits(B->getType())); 8394 assert(A != 0 && "A must be non-zero."); 8395 8396 // 1. D = gcd(A, N) 8397 // 8398 // The gcd of A and N may have only one prime factor: 2. The number of 8399 // trailing zeros in A is its multiplicity 8400 uint32_t Mult2 = A.countTrailingZeros(); 8401 // D = 2^Mult2 8402 8403 // 2. Check if B is divisible by D. 8404 // 8405 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8406 // is not less than multiplicity of this prime factor for D. 8407 if (SE.GetMinTrailingZeros(B) < Mult2) 8408 return SE.getCouldNotCompute(); 8409 8410 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8411 // modulo (N / D). 8412 // 8413 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8414 // (N / D) in general. The inverse itself always fits into BW bits, though, 8415 // so we immediately truncate it. 8416 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8417 APInt Mod(BW + 1, 0); 8418 Mod.setBit(BW - Mult2); // Mod = N / D 8419 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8420 8421 // 4. Compute the minimum unsigned root of the equation: 8422 // I * (B / D) mod (N / D) 8423 // To simplify the computation, we factor out the divide by D: 8424 // (I * B mod N) / D 8425 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8426 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8427 } 8428 8429 /// For a given quadratic addrec, generate coefficients of the corresponding 8430 /// quadratic equation, multiplied by a common value to ensure that they are 8431 /// integers. 8432 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8433 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8434 /// were multiplied by, and BitWidth is the bit width of the original addrec 8435 /// coefficients. 8436 /// This function returns None if the addrec coefficients are not compile- 8437 /// time constants. 8438 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8439 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8440 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8441 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8442 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8443 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8444 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8445 << *AddRec << '\n'); 8446 8447 // We currently can only solve this if the coefficients are constants. 8448 if (!LC || !MC || !NC) { 8449 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8450 return None; 8451 } 8452 8453 APInt L = LC->getAPInt(); 8454 APInt M = MC->getAPInt(); 8455 APInt N = NC->getAPInt(); 8456 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8457 8458 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8459 unsigned NewWidth = BitWidth + 1; 8460 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8461 << BitWidth << '\n'); 8462 // The sign-extension (as opposed to a zero-extension) here matches the 8463 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8464 N = N.sext(NewWidth); 8465 M = M.sext(NewWidth); 8466 L = L.sext(NewWidth); 8467 8468 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8469 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8470 // L+M, L+2M+N, L+3M+3N, ... 8471 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8472 // 8473 // The equation Acc = 0 is then 8474 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8475 // In a quadratic form it becomes: 8476 // N n^2 + (2M-N) n + 2L = 0. 8477 8478 APInt A = N; 8479 APInt B = 2 * M - A; 8480 APInt C = 2 * L; 8481 APInt T = APInt(NewWidth, 2); 8482 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8483 << "x + " << C << ", coeff bw: " << NewWidth 8484 << ", multiplied by " << T << '\n'); 8485 return std::make_tuple(A, B, C, T, BitWidth); 8486 } 8487 8488 /// Helper function to compare optional APInts: 8489 /// (a) if X and Y both exist, return min(X, Y), 8490 /// (b) if neither X nor Y exist, return None, 8491 /// (c) if exactly one of X and Y exists, return that value. 8492 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8493 if (X.hasValue() && Y.hasValue()) { 8494 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8495 APInt XW = X->sextOrSelf(W); 8496 APInt YW = Y->sextOrSelf(W); 8497 return XW.slt(YW) ? *X : *Y; 8498 } 8499 if (!X.hasValue() && !Y.hasValue()) 8500 return None; 8501 return X.hasValue() ? *X : *Y; 8502 } 8503 8504 /// Helper function to truncate an optional APInt to a given BitWidth. 8505 /// When solving addrec-related equations, it is preferable to return a value 8506 /// that has the same bit width as the original addrec's coefficients. If the 8507 /// solution fits in the original bit width, truncate it (except for i1). 8508 /// Returning a value of a different bit width may inhibit some optimizations. 8509 /// 8510 /// In general, a solution to a quadratic equation generated from an addrec 8511 /// may require BW+1 bits, where BW is the bit width of the addrec's 8512 /// coefficients. The reason is that the coefficients of the quadratic 8513 /// equation are BW+1 bits wide (to avoid truncation when converting from 8514 /// the addrec to the equation). 8515 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8516 if (!X.hasValue()) 8517 return None; 8518 unsigned W = X->getBitWidth(); 8519 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8520 return X->trunc(BitWidth); 8521 return X; 8522 } 8523 8524 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8525 /// iterations. The values L, M, N are assumed to be signed, and they 8526 /// should all have the same bit widths. 8527 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8528 /// where BW is the bit width of the addrec's coefficients. 8529 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8530 /// returned as such, otherwise the bit width of the returned value may 8531 /// be greater than BW. 8532 /// 8533 /// This function returns None if 8534 /// (a) the addrec coefficients are not constant, or 8535 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8536 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8537 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8538 static Optional<APInt> 8539 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8540 APInt A, B, C, M; 8541 unsigned BitWidth; 8542 auto T = GetQuadraticEquation(AddRec); 8543 if (!T.hasValue()) 8544 return None; 8545 8546 std::tie(A, B, C, M, BitWidth) = *T; 8547 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8548 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8549 if (!X.hasValue()) 8550 return None; 8551 8552 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8553 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8554 if (!V->isZero()) 8555 return None; 8556 8557 return TruncIfPossible(X, BitWidth); 8558 } 8559 8560 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8561 /// iterations. The values M, N are assumed to be signed, and they 8562 /// should all have the same bit widths. 8563 /// Find the least n such that c(n) does not belong to the given range, 8564 /// while c(n-1) does. 8565 /// 8566 /// This function returns None if 8567 /// (a) the addrec coefficients are not constant, or 8568 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8569 /// bounds of the range. 8570 static Optional<APInt> 8571 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8572 const ConstantRange &Range, ScalarEvolution &SE) { 8573 assert(AddRec->getOperand(0)->isZero() && 8574 "Starting value of addrec should be 0"); 8575 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8576 << Range << ", addrec " << *AddRec << '\n'); 8577 // This case is handled in getNumIterationsInRange. Here we can assume that 8578 // we start in the range. 8579 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8580 "Addrec's initial value should be in range"); 8581 8582 APInt A, B, C, M; 8583 unsigned BitWidth; 8584 auto T = GetQuadraticEquation(AddRec); 8585 if (!T.hasValue()) 8586 return None; 8587 8588 // Be careful about the return value: there can be two reasons for not 8589 // returning an actual number. First, if no solutions to the equations 8590 // were found, and second, if the solutions don't leave the given range. 8591 // The first case means that the actual solution is "unknown", the second 8592 // means that it's known, but not valid. If the solution is unknown, we 8593 // cannot make any conclusions. 8594 // Return a pair: the optional solution and a flag indicating if the 8595 // solution was found. 8596 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8597 // Solve for signed overflow and unsigned overflow, pick the lower 8598 // solution. 8599 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8600 << Bound << " (before multiplying by " << M << ")\n"); 8601 Bound *= M; // The quadratic equation multiplier. 8602 8603 Optional<APInt> SO = None; 8604 if (BitWidth > 1) { 8605 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8606 "signed overflow\n"); 8607 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8608 } 8609 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8610 "unsigned overflow\n"); 8611 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8612 BitWidth+1); 8613 8614 auto LeavesRange = [&] (const APInt &X) { 8615 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8616 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8617 if (Range.contains(V0->getValue())) 8618 return false; 8619 // X should be at least 1, so X-1 is non-negative. 8620 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8621 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8622 if (Range.contains(V1->getValue())) 8623 return true; 8624 return false; 8625 }; 8626 8627 // If SolveQuadraticEquationWrap returns None, it means that there can 8628 // be a solution, but the function failed to find it. We cannot treat it 8629 // as "no solution". 8630 if (!SO.hasValue() || !UO.hasValue()) 8631 return { None, false }; 8632 8633 // Check the smaller value first to see if it leaves the range. 8634 // At this point, both SO and UO must have values. 8635 Optional<APInt> Min = MinOptional(SO, UO); 8636 if (LeavesRange(*Min)) 8637 return { Min, true }; 8638 Optional<APInt> Max = Min == SO ? UO : SO; 8639 if (LeavesRange(*Max)) 8640 return { Max, true }; 8641 8642 // Solutions were found, but were eliminated, hence the "true". 8643 return { None, true }; 8644 }; 8645 8646 std::tie(A, B, C, M, BitWidth) = *T; 8647 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8648 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8649 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8650 auto SL = SolveForBoundary(Lower); 8651 auto SU = SolveForBoundary(Upper); 8652 // If any of the solutions was unknown, no meaninigful conclusions can 8653 // be made. 8654 if (!SL.second || !SU.second) 8655 return None; 8656 8657 // Claim: The correct solution is not some value between Min and Max. 8658 // 8659 // Justification: Assuming that Min and Max are different values, one of 8660 // them is when the first signed overflow happens, the other is when the 8661 // first unsigned overflow happens. Crossing the range boundary is only 8662 // possible via an overflow (treating 0 as a special case of it, modeling 8663 // an overflow as crossing k*2^W for some k). 8664 // 8665 // The interesting case here is when Min was eliminated as an invalid 8666 // solution, but Max was not. The argument is that if there was another 8667 // overflow between Min and Max, it would also have been eliminated if 8668 // it was considered. 8669 // 8670 // For a given boundary, it is possible to have two overflows of the same 8671 // type (signed/unsigned) without having the other type in between: this 8672 // can happen when the vertex of the parabola is between the iterations 8673 // corresponding to the overflows. This is only possible when the two 8674 // overflows cross k*2^W for the same k. In such case, if the second one 8675 // left the range (and was the first one to do so), the first overflow 8676 // would have to enter the range, which would mean that either we had left 8677 // the range before or that we started outside of it. Both of these cases 8678 // are contradictions. 8679 // 8680 // Claim: In the case where SolveForBoundary returns None, the correct 8681 // solution is not some value between the Max for this boundary and the 8682 // Min of the other boundary. 8683 // 8684 // Justification: Assume that we had such Max_A and Min_B corresponding 8685 // to range boundaries A and B and such that Max_A < Min_B. If there was 8686 // a solution between Max_A and Min_B, it would have to be caused by an 8687 // overflow corresponding to either A or B. It cannot correspond to B, 8688 // since Min_B is the first occurrence of such an overflow. If it 8689 // corresponded to A, it would have to be either a signed or an unsigned 8690 // overflow that is larger than both eliminated overflows for A. But 8691 // between the eliminated overflows and this overflow, the values would 8692 // cover the entire value space, thus crossing the other boundary, which 8693 // is a contradiction. 8694 8695 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8696 } 8697 8698 ScalarEvolution::ExitLimit 8699 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8700 bool AllowPredicates) { 8701 8702 // This is only used for loops with a "x != y" exit test. The exit condition 8703 // is now expressed as a single expression, V = x-y. So the exit test is 8704 // effectively V != 0. We know and take advantage of the fact that this 8705 // expression only being used in a comparison by zero context. 8706 8707 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8708 // If the value is a constant 8709 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8710 // If the value is already zero, the branch will execute zero times. 8711 if (C->getValue()->isZero()) return C; 8712 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8713 } 8714 8715 const SCEVAddRecExpr *AddRec = 8716 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8717 8718 if (!AddRec && AllowPredicates) 8719 // Try to make this an AddRec using runtime tests, in the first X 8720 // iterations of this loop, where X is the SCEV expression found by the 8721 // algorithm below. 8722 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8723 8724 if (!AddRec || AddRec->getLoop() != L) 8725 return getCouldNotCompute(); 8726 8727 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8728 // the quadratic equation to solve it. 8729 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8730 // We can only use this value if the chrec ends up with an exact zero 8731 // value at this index. When solving for "X*X != 5", for example, we 8732 // should not accept a root of 2. 8733 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8734 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8735 return ExitLimit(R, R, false, Predicates); 8736 } 8737 return getCouldNotCompute(); 8738 } 8739 8740 // Otherwise we can only handle this if it is affine. 8741 if (!AddRec->isAffine()) 8742 return getCouldNotCompute(); 8743 8744 // If this is an affine expression, the execution count of this branch is 8745 // the minimum unsigned root of the following equation: 8746 // 8747 // Start + Step*N = 0 (mod 2^BW) 8748 // 8749 // equivalent to: 8750 // 8751 // Step*N = -Start (mod 2^BW) 8752 // 8753 // where BW is the common bit width of Start and Step. 8754 8755 // Get the initial value for the loop. 8756 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8757 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8758 8759 // For now we handle only constant steps. 8760 // 8761 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8762 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8763 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8764 // We have not yet seen any such cases. 8765 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8766 if (!StepC || StepC->getValue()->isZero()) 8767 return getCouldNotCompute(); 8768 8769 // For positive steps (counting up until unsigned overflow): 8770 // N = -Start/Step (as unsigned) 8771 // For negative steps (counting down to zero): 8772 // N = Start/-Step 8773 // First compute the unsigned distance from zero in the direction of Step. 8774 bool CountDown = StepC->getAPInt().isNegative(); 8775 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8776 8777 // Handle unitary steps, which cannot wraparound. 8778 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8779 // N = Distance (as unsigned) 8780 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8781 APInt MaxBECount = getUnsignedRangeMax(Distance); 8782 8783 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8784 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8785 // case, and see if we can improve the bound. 8786 // 8787 // Explicitly handling this here is necessary because getUnsignedRange 8788 // isn't context-sensitive; it doesn't know that we only care about the 8789 // range inside the loop. 8790 const SCEV *Zero = getZero(Distance->getType()); 8791 const SCEV *One = getOne(Distance->getType()); 8792 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8793 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8794 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8795 // as "unsigned_max(Distance + 1) - 1". 8796 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8797 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8798 } 8799 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8800 } 8801 8802 // If the condition controls loop exit (the loop exits only if the expression 8803 // is true) and the addition is no-wrap we can use unsigned divide to 8804 // compute the backedge count. In this case, the step may not divide the 8805 // distance, but we don't care because if the condition is "missed" the loop 8806 // will have undefined behavior due to wrapping. 8807 if (ControlsExit && AddRec->hasNoSelfWrap() && 8808 loopHasNoAbnormalExits(AddRec->getLoop())) { 8809 const SCEV *Exact = 8810 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8811 const SCEV *Max = 8812 Exact == getCouldNotCompute() 8813 ? Exact 8814 : getConstant(getUnsignedRangeMax(Exact)); 8815 return ExitLimit(Exact, Max, false, Predicates); 8816 } 8817 8818 // Solve the general equation. 8819 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8820 getNegativeSCEV(Start), *this); 8821 const SCEV *M = E == getCouldNotCompute() 8822 ? E 8823 : getConstant(getUnsignedRangeMax(E)); 8824 return ExitLimit(E, M, false, Predicates); 8825 } 8826 8827 ScalarEvolution::ExitLimit 8828 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8829 // Loops that look like: while (X == 0) are very strange indeed. We don't 8830 // handle them yet except for the trivial case. This could be expanded in the 8831 // future as needed. 8832 8833 // If the value is a constant, check to see if it is known to be non-zero 8834 // already. If so, the backedge will execute zero times. 8835 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8836 if (!C->getValue()->isZero()) 8837 return getZero(C->getType()); 8838 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8839 } 8840 8841 // We could implement others, but I really doubt anyone writes loops like 8842 // this, and if they did, they would already be constant folded. 8843 return getCouldNotCompute(); 8844 } 8845 8846 std::pair<BasicBlock *, BasicBlock *> 8847 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8848 // If the block has a unique predecessor, then there is no path from the 8849 // predecessor to the block that does not go through the direct edge 8850 // from the predecessor to the block. 8851 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8852 return {Pred, BB}; 8853 8854 // A loop's header is defined to be a block that dominates the loop. 8855 // If the header has a unique predecessor outside the loop, it must be 8856 // a block that has exactly one successor that can reach the loop. 8857 if (Loop *L = LI.getLoopFor(BB)) 8858 return {L->getLoopPredecessor(), L->getHeader()}; 8859 8860 return {nullptr, nullptr}; 8861 } 8862 8863 /// SCEV structural equivalence is usually sufficient for testing whether two 8864 /// expressions are equal, however for the purposes of looking for a condition 8865 /// guarding a loop, it can be useful to be a little more general, since a 8866 /// front-end may have replicated the controlling expression. 8867 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8868 // Quick check to see if they are the same SCEV. 8869 if (A == B) return true; 8870 8871 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8872 // Not all instructions that are "identical" compute the same value. For 8873 // instance, two distinct alloca instructions allocating the same type are 8874 // identical and do not read memory; but compute distinct values. 8875 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8876 }; 8877 8878 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8879 // two different instructions with the same value. Check for this case. 8880 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8881 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8882 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8883 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8884 if (ComputesEqualValues(AI, BI)) 8885 return true; 8886 8887 // Otherwise assume they may have a different value. 8888 return false; 8889 } 8890 8891 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8892 const SCEV *&LHS, const SCEV *&RHS, 8893 unsigned Depth) { 8894 bool Changed = false; 8895 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8896 // '0 != 0'. 8897 auto TrivialCase = [&](bool TriviallyTrue) { 8898 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8899 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8900 return true; 8901 }; 8902 // If we hit the max recursion limit bail out. 8903 if (Depth >= 3) 8904 return false; 8905 8906 // Canonicalize a constant to the right side. 8907 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8908 // Check for both operands constant. 8909 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8910 if (ConstantExpr::getICmp(Pred, 8911 LHSC->getValue(), 8912 RHSC->getValue())->isNullValue()) 8913 return TrivialCase(false); 8914 else 8915 return TrivialCase(true); 8916 } 8917 // Otherwise swap the operands to put the constant on the right. 8918 std::swap(LHS, RHS); 8919 Pred = ICmpInst::getSwappedPredicate(Pred); 8920 Changed = true; 8921 } 8922 8923 // If we're comparing an addrec with a value which is loop-invariant in the 8924 // addrec's loop, put the addrec on the left. Also make a dominance check, 8925 // as both operands could be addrecs loop-invariant in each other's loop. 8926 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8927 const Loop *L = AR->getLoop(); 8928 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8929 std::swap(LHS, RHS); 8930 Pred = ICmpInst::getSwappedPredicate(Pred); 8931 Changed = true; 8932 } 8933 } 8934 8935 // If there's a constant operand, canonicalize comparisons with boundary 8936 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8937 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8938 const APInt &RA = RC->getAPInt(); 8939 8940 bool SimplifiedByConstantRange = false; 8941 8942 if (!ICmpInst::isEquality(Pred)) { 8943 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8944 if (ExactCR.isFullSet()) 8945 return TrivialCase(true); 8946 else if (ExactCR.isEmptySet()) 8947 return TrivialCase(false); 8948 8949 APInt NewRHS; 8950 CmpInst::Predicate NewPred; 8951 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8952 ICmpInst::isEquality(NewPred)) { 8953 // We were able to convert an inequality to an equality. 8954 Pred = NewPred; 8955 RHS = getConstant(NewRHS); 8956 Changed = SimplifiedByConstantRange = true; 8957 } 8958 } 8959 8960 if (!SimplifiedByConstantRange) { 8961 switch (Pred) { 8962 default: 8963 break; 8964 case ICmpInst::ICMP_EQ: 8965 case ICmpInst::ICMP_NE: 8966 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8967 if (!RA) 8968 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8969 if (const SCEVMulExpr *ME = 8970 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8971 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8972 ME->getOperand(0)->isAllOnesValue()) { 8973 RHS = AE->getOperand(1); 8974 LHS = ME->getOperand(1); 8975 Changed = true; 8976 } 8977 break; 8978 8979 8980 // The "Should have been caught earlier!" messages refer to the fact 8981 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8982 // should have fired on the corresponding cases, and canonicalized the 8983 // check to trivial case. 8984 8985 case ICmpInst::ICMP_UGE: 8986 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8987 Pred = ICmpInst::ICMP_UGT; 8988 RHS = getConstant(RA - 1); 8989 Changed = true; 8990 break; 8991 case ICmpInst::ICMP_ULE: 8992 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8993 Pred = ICmpInst::ICMP_ULT; 8994 RHS = getConstant(RA + 1); 8995 Changed = true; 8996 break; 8997 case ICmpInst::ICMP_SGE: 8998 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8999 Pred = ICmpInst::ICMP_SGT; 9000 RHS = getConstant(RA - 1); 9001 Changed = true; 9002 break; 9003 case ICmpInst::ICMP_SLE: 9004 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9005 Pred = ICmpInst::ICMP_SLT; 9006 RHS = getConstant(RA + 1); 9007 Changed = true; 9008 break; 9009 } 9010 } 9011 } 9012 9013 // Check for obvious equality. 9014 if (HasSameValue(LHS, RHS)) { 9015 if (ICmpInst::isTrueWhenEqual(Pred)) 9016 return TrivialCase(true); 9017 if (ICmpInst::isFalseWhenEqual(Pred)) 9018 return TrivialCase(false); 9019 } 9020 9021 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9022 // adding or subtracting 1 from one of the operands. 9023 switch (Pred) { 9024 case ICmpInst::ICMP_SLE: 9025 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9026 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9027 SCEV::FlagNSW); 9028 Pred = ICmpInst::ICMP_SLT; 9029 Changed = true; 9030 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9031 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9032 SCEV::FlagNSW); 9033 Pred = ICmpInst::ICMP_SLT; 9034 Changed = true; 9035 } 9036 break; 9037 case ICmpInst::ICMP_SGE: 9038 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9039 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9040 SCEV::FlagNSW); 9041 Pred = ICmpInst::ICMP_SGT; 9042 Changed = true; 9043 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9044 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9045 SCEV::FlagNSW); 9046 Pred = ICmpInst::ICMP_SGT; 9047 Changed = true; 9048 } 9049 break; 9050 case ICmpInst::ICMP_ULE: 9051 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9052 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9053 SCEV::FlagNUW); 9054 Pred = ICmpInst::ICMP_ULT; 9055 Changed = true; 9056 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9057 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9058 Pred = ICmpInst::ICMP_ULT; 9059 Changed = true; 9060 } 9061 break; 9062 case ICmpInst::ICMP_UGE: 9063 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9064 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9065 Pred = ICmpInst::ICMP_UGT; 9066 Changed = true; 9067 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9068 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9069 SCEV::FlagNUW); 9070 Pred = ICmpInst::ICMP_UGT; 9071 Changed = true; 9072 } 9073 break; 9074 default: 9075 break; 9076 } 9077 9078 // TODO: More simplifications are possible here. 9079 9080 // Recursively simplify until we either hit a recursion limit or nothing 9081 // changes. 9082 if (Changed) 9083 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9084 9085 return Changed; 9086 } 9087 9088 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9089 return getSignedRangeMax(S).isNegative(); 9090 } 9091 9092 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9093 return getSignedRangeMin(S).isStrictlyPositive(); 9094 } 9095 9096 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9097 return !getSignedRangeMin(S).isNegative(); 9098 } 9099 9100 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9101 return !getSignedRangeMax(S).isStrictlyPositive(); 9102 } 9103 9104 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9105 return isKnownNegative(S) || isKnownPositive(S); 9106 } 9107 9108 std::pair<const SCEV *, const SCEV *> 9109 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9110 // Compute SCEV on entry of loop L. 9111 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9112 if (Start == getCouldNotCompute()) 9113 return { Start, Start }; 9114 // Compute post increment SCEV for loop L. 9115 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9116 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9117 return { Start, PostInc }; 9118 } 9119 9120 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9121 const SCEV *LHS, const SCEV *RHS) { 9122 // First collect all loops. 9123 SmallPtrSet<const Loop *, 8> LoopsUsed; 9124 getUsedLoops(LHS, LoopsUsed); 9125 getUsedLoops(RHS, LoopsUsed); 9126 9127 if (LoopsUsed.empty()) 9128 return false; 9129 9130 // Domination relationship must be a linear order on collected loops. 9131 #ifndef NDEBUG 9132 for (auto *L1 : LoopsUsed) 9133 for (auto *L2 : LoopsUsed) 9134 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9135 DT.dominates(L2->getHeader(), L1->getHeader())) && 9136 "Domination relationship is not a linear order"); 9137 #endif 9138 9139 const Loop *MDL = 9140 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9141 [&](const Loop *L1, const Loop *L2) { 9142 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9143 }); 9144 9145 // Get init and post increment value for LHS. 9146 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9147 // if LHS contains unknown non-invariant SCEV then bail out. 9148 if (SplitLHS.first == getCouldNotCompute()) 9149 return false; 9150 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9151 // Get init and post increment value for RHS. 9152 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9153 // if RHS contains unknown non-invariant SCEV then bail out. 9154 if (SplitRHS.first == getCouldNotCompute()) 9155 return false; 9156 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9157 // It is possible that init SCEV contains an invariant load but it does 9158 // not dominate MDL and is not available at MDL loop entry, so we should 9159 // check it here. 9160 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9161 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9162 return false; 9163 9164 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 9165 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9166 SplitRHS.second); 9167 } 9168 9169 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9170 const SCEV *LHS, const SCEV *RHS) { 9171 // Canonicalize the inputs first. 9172 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9173 9174 if (isKnownViaInduction(Pred, LHS, RHS)) 9175 return true; 9176 9177 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9178 return true; 9179 9180 // Otherwise see what can be done with some simple reasoning. 9181 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9182 } 9183 9184 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9185 const SCEVAddRecExpr *LHS, 9186 const SCEV *RHS) { 9187 const Loop *L = LHS->getLoop(); 9188 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9189 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9190 } 9191 9192 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9193 ICmpInst::Predicate Pred, 9194 bool &Increasing) { 9195 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9196 9197 #ifndef NDEBUG 9198 // Verify an invariant: inverting the predicate should turn a monotonically 9199 // increasing change to a monotonically decreasing one, and vice versa. 9200 bool IncreasingSwapped; 9201 bool ResultSwapped = isMonotonicPredicateImpl( 9202 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9203 9204 assert(Result == ResultSwapped && "should be able to analyze both!"); 9205 if (ResultSwapped) 9206 assert(Increasing == !IncreasingSwapped && 9207 "monotonicity should flip as we flip the predicate"); 9208 #endif 9209 9210 return Result; 9211 } 9212 9213 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9214 ICmpInst::Predicate Pred, 9215 bool &Increasing) { 9216 9217 // A zero step value for LHS means the induction variable is essentially a 9218 // loop invariant value. We don't really depend on the predicate actually 9219 // flipping from false to true (for increasing predicates, and the other way 9220 // around for decreasing predicates), all we care about is that *if* the 9221 // predicate changes then it only changes from false to true. 9222 // 9223 // A zero step value in itself is not very useful, but there may be places 9224 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9225 // as general as possible. 9226 9227 switch (Pred) { 9228 default: 9229 return false; // Conservative answer 9230 9231 case ICmpInst::ICMP_UGT: 9232 case ICmpInst::ICMP_UGE: 9233 case ICmpInst::ICMP_ULT: 9234 case ICmpInst::ICMP_ULE: 9235 if (!LHS->hasNoUnsignedWrap()) 9236 return false; 9237 9238 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9239 return true; 9240 9241 case ICmpInst::ICMP_SGT: 9242 case ICmpInst::ICMP_SGE: 9243 case ICmpInst::ICMP_SLT: 9244 case ICmpInst::ICMP_SLE: { 9245 if (!LHS->hasNoSignedWrap()) 9246 return false; 9247 9248 const SCEV *Step = LHS->getStepRecurrence(*this); 9249 9250 if (isKnownNonNegative(Step)) { 9251 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9252 return true; 9253 } 9254 9255 if (isKnownNonPositive(Step)) { 9256 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9257 return true; 9258 } 9259 9260 return false; 9261 } 9262 9263 } 9264 9265 llvm_unreachable("switch has default clause!"); 9266 } 9267 9268 bool ScalarEvolution::isLoopInvariantPredicate( 9269 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9270 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9271 const SCEV *&InvariantRHS) { 9272 9273 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9274 if (!isLoopInvariant(RHS, L)) { 9275 if (!isLoopInvariant(LHS, L)) 9276 return false; 9277 9278 std::swap(LHS, RHS); 9279 Pred = ICmpInst::getSwappedPredicate(Pred); 9280 } 9281 9282 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9283 if (!ArLHS || ArLHS->getLoop() != L) 9284 return false; 9285 9286 bool Increasing; 9287 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9288 return false; 9289 9290 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9291 // true as the loop iterates, and the backedge is control dependent on 9292 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9293 // 9294 // * if the predicate was false in the first iteration then the predicate 9295 // is never evaluated again, since the loop exits without taking the 9296 // backedge. 9297 // * if the predicate was true in the first iteration then it will 9298 // continue to be true for all future iterations since it is 9299 // monotonically increasing. 9300 // 9301 // For both the above possibilities, we can replace the loop varying 9302 // predicate with its value on the first iteration of the loop (which is 9303 // loop invariant). 9304 // 9305 // A similar reasoning applies for a monotonically decreasing predicate, by 9306 // replacing true with false and false with true in the above two bullets. 9307 9308 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9309 9310 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9311 return false; 9312 9313 InvariantPred = Pred; 9314 InvariantLHS = ArLHS->getStart(); 9315 InvariantRHS = RHS; 9316 return true; 9317 } 9318 9319 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9320 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9321 if (HasSameValue(LHS, RHS)) 9322 return ICmpInst::isTrueWhenEqual(Pred); 9323 9324 // This code is split out from isKnownPredicate because it is called from 9325 // within isLoopEntryGuardedByCond. 9326 9327 auto CheckRanges = 9328 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9329 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9330 .contains(RangeLHS); 9331 }; 9332 9333 // The check at the top of the function catches the case where the values are 9334 // known to be equal. 9335 if (Pred == CmpInst::ICMP_EQ) 9336 return false; 9337 9338 if (Pred == CmpInst::ICMP_NE) 9339 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9340 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9341 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9342 9343 if (CmpInst::isSigned(Pred)) 9344 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9345 9346 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9347 } 9348 9349 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9350 const SCEV *LHS, 9351 const SCEV *RHS) { 9352 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9353 // Return Y via OutY. 9354 auto MatchBinaryAddToConst = 9355 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9356 SCEV::NoWrapFlags ExpectedFlags) { 9357 const SCEV *NonConstOp, *ConstOp; 9358 SCEV::NoWrapFlags FlagsPresent; 9359 9360 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9361 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9362 return false; 9363 9364 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9365 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9366 }; 9367 9368 APInt C; 9369 9370 switch (Pred) { 9371 default: 9372 break; 9373 9374 case ICmpInst::ICMP_SGE: 9375 std::swap(LHS, RHS); 9376 LLVM_FALLTHROUGH; 9377 case ICmpInst::ICMP_SLE: 9378 // X s<= (X + C)<nsw> if C >= 0 9379 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9380 return true; 9381 9382 // (X + C)<nsw> s<= X if C <= 0 9383 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9384 !C.isStrictlyPositive()) 9385 return true; 9386 break; 9387 9388 case ICmpInst::ICMP_SGT: 9389 std::swap(LHS, RHS); 9390 LLVM_FALLTHROUGH; 9391 case ICmpInst::ICMP_SLT: 9392 // X s< (X + C)<nsw> if C > 0 9393 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9394 C.isStrictlyPositive()) 9395 return true; 9396 9397 // (X + C)<nsw> s< X if C < 0 9398 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9399 return true; 9400 break; 9401 } 9402 9403 return false; 9404 } 9405 9406 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9407 const SCEV *LHS, 9408 const SCEV *RHS) { 9409 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9410 return false; 9411 9412 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9413 // the stack can result in exponential time complexity. 9414 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9415 9416 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9417 // 9418 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9419 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9420 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9421 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9422 // use isKnownPredicate later if needed. 9423 return isKnownNonNegative(RHS) && 9424 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9425 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9426 } 9427 9428 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9429 ICmpInst::Predicate Pred, 9430 const SCEV *LHS, const SCEV *RHS) { 9431 // No need to even try if we know the module has no guards. 9432 if (!HasGuards) 9433 return false; 9434 9435 return any_of(*BB, [&](Instruction &I) { 9436 using namespace llvm::PatternMatch; 9437 9438 Value *Condition; 9439 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9440 m_Value(Condition))) && 9441 isImpliedCond(Pred, LHS, RHS, Condition, false); 9442 }); 9443 } 9444 9445 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9446 /// protected by a conditional between LHS and RHS. This is used to 9447 /// to eliminate casts. 9448 bool 9449 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9450 ICmpInst::Predicate Pred, 9451 const SCEV *LHS, const SCEV *RHS) { 9452 // Interpret a null as meaning no loop, where there is obviously no guard 9453 // (interprocedural conditions notwithstanding). 9454 if (!L) return true; 9455 9456 if (VerifyIR) 9457 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9458 "This cannot be done on broken IR!"); 9459 9460 9461 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9462 return true; 9463 9464 BasicBlock *Latch = L->getLoopLatch(); 9465 if (!Latch) 9466 return false; 9467 9468 BranchInst *LoopContinuePredicate = 9469 dyn_cast<BranchInst>(Latch->getTerminator()); 9470 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9471 isImpliedCond(Pred, LHS, RHS, 9472 LoopContinuePredicate->getCondition(), 9473 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9474 return true; 9475 9476 // We don't want more than one activation of the following loops on the stack 9477 // -- that can lead to O(n!) time complexity. 9478 if (WalkingBEDominatingConds) 9479 return false; 9480 9481 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9482 9483 // See if we can exploit a trip count to prove the predicate. 9484 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9485 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9486 if (LatchBECount != getCouldNotCompute()) { 9487 // We know that Latch branches back to the loop header exactly 9488 // LatchBECount times. This means the backdege condition at Latch is 9489 // equivalent to "{0,+,1} u< LatchBECount". 9490 Type *Ty = LatchBECount->getType(); 9491 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9492 const SCEV *LoopCounter = 9493 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9494 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9495 LatchBECount)) 9496 return true; 9497 } 9498 9499 // Check conditions due to any @llvm.assume intrinsics. 9500 for (auto &AssumeVH : AC.assumptions()) { 9501 if (!AssumeVH) 9502 continue; 9503 auto *CI = cast<CallInst>(AssumeVH); 9504 if (!DT.dominates(CI, Latch->getTerminator())) 9505 continue; 9506 9507 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9508 return true; 9509 } 9510 9511 // If the loop is not reachable from the entry block, we risk running into an 9512 // infinite loop as we walk up into the dom tree. These loops do not matter 9513 // anyway, so we just return a conservative answer when we see them. 9514 if (!DT.isReachableFromEntry(L->getHeader())) 9515 return false; 9516 9517 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9518 return true; 9519 9520 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9521 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9522 assert(DTN && "should reach the loop header before reaching the root!"); 9523 9524 BasicBlock *BB = DTN->getBlock(); 9525 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9526 return true; 9527 9528 BasicBlock *PBB = BB->getSinglePredecessor(); 9529 if (!PBB) 9530 continue; 9531 9532 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9533 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9534 continue; 9535 9536 Value *Condition = ContinuePredicate->getCondition(); 9537 9538 // If we have an edge `E` within the loop body that dominates the only 9539 // latch, the condition guarding `E` also guards the backedge. This 9540 // reasoning works only for loops with a single latch. 9541 9542 BasicBlockEdge DominatingEdge(PBB, BB); 9543 if (DominatingEdge.isSingleEdge()) { 9544 // We're constructively (and conservatively) enumerating edges within the 9545 // loop body that dominate the latch. The dominator tree better agree 9546 // with us on this: 9547 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9548 9549 if (isImpliedCond(Pred, LHS, RHS, Condition, 9550 BB != ContinuePredicate->getSuccessor(0))) 9551 return true; 9552 } 9553 } 9554 9555 return false; 9556 } 9557 9558 bool 9559 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9560 ICmpInst::Predicate Pred, 9561 const SCEV *LHS, const SCEV *RHS) { 9562 // Interpret a null as meaning no loop, where there is obviously no guard 9563 // (interprocedural conditions notwithstanding). 9564 if (!L) return false; 9565 9566 if (VerifyIR) 9567 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9568 "This cannot be done on broken IR!"); 9569 9570 // Both LHS and RHS must be available at loop entry. 9571 assert(isAvailableAtLoopEntry(LHS, L) && 9572 "LHS is not available at Loop Entry"); 9573 assert(isAvailableAtLoopEntry(RHS, L) && 9574 "RHS is not available at Loop Entry"); 9575 9576 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9577 return true; 9578 9579 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9580 // the facts (a >= b && a != b) separately. A typical situation is when the 9581 // non-strict comparison is known from ranges and non-equality is known from 9582 // dominating predicates. If we are proving strict comparison, we always try 9583 // to prove non-equality and non-strict comparison separately. 9584 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9585 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9586 bool ProvedNonStrictComparison = false; 9587 bool ProvedNonEquality = false; 9588 9589 if (ProvingStrictComparison) { 9590 ProvedNonStrictComparison = 9591 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9592 ProvedNonEquality = 9593 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9594 if (ProvedNonStrictComparison && ProvedNonEquality) 9595 return true; 9596 } 9597 9598 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9599 auto ProveViaGuard = [&](BasicBlock *Block) { 9600 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9601 return true; 9602 if (ProvingStrictComparison) { 9603 if (!ProvedNonStrictComparison) 9604 ProvedNonStrictComparison = 9605 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9606 if (!ProvedNonEquality) 9607 ProvedNonEquality = 9608 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9609 if (ProvedNonStrictComparison && ProvedNonEquality) 9610 return true; 9611 } 9612 return false; 9613 }; 9614 9615 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9616 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9617 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9618 return true; 9619 if (ProvingStrictComparison) { 9620 if (!ProvedNonStrictComparison) 9621 ProvedNonStrictComparison = 9622 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9623 if (!ProvedNonEquality) 9624 ProvedNonEquality = 9625 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9626 if (ProvedNonStrictComparison && ProvedNonEquality) 9627 return true; 9628 } 9629 return false; 9630 }; 9631 9632 // Starting at the loop predecessor, climb up the predecessor chain, as long 9633 // as there are predecessors that can be found that have unique successors 9634 // leading to the original header. 9635 for (std::pair<BasicBlock *, BasicBlock *> 9636 Pair(L->getLoopPredecessor(), L->getHeader()); 9637 Pair.first; 9638 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9639 9640 if (ProveViaGuard(Pair.first)) 9641 return true; 9642 9643 BranchInst *LoopEntryPredicate = 9644 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9645 if (!LoopEntryPredicate || 9646 LoopEntryPredicate->isUnconditional()) 9647 continue; 9648 9649 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9650 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9651 return true; 9652 } 9653 9654 // Check conditions due to any @llvm.assume intrinsics. 9655 for (auto &AssumeVH : AC.assumptions()) { 9656 if (!AssumeVH) 9657 continue; 9658 auto *CI = cast<CallInst>(AssumeVH); 9659 if (!DT.dominates(CI, L->getHeader())) 9660 continue; 9661 9662 if (ProveViaCond(CI->getArgOperand(0), false)) 9663 return true; 9664 } 9665 9666 return false; 9667 } 9668 9669 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9670 const SCEV *LHS, const SCEV *RHS, 9671 Value *FoundCondValue, 9672 bool Inverse) { 9673 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9674 return false; 9675 9676 auto ClearOnExit = 9677 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9678 9679 // Recursively handle And and Or conditions. 9680 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9681 if (BO->getOpcode() == Instruction::And) { 9682 if (!Inverse) 9683 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9684 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9685 } else if (BO->getOpcode() == Instruction::Or) { 9686 if (Inverse) 9687 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9688 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9689 } 9690 } 9691 9692 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9693 if (!ICI) return false; 9694 9695 // Now that we found a conditional branch that dominates the loop or controls 9696 // the loop latch. Check to see if it is the comparison we are looking for. 9697 ICmpInst::Predicate FoundPred; 9698 if (Inverse) 9699 FoundPred = ICI->getInversePredicate(); 9700 else 9701 FoundPred = ICI->getPredicate(); 9702 9703 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9704 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9705 9706 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9707 } 9708 9709 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9710 const SCEV *RHS, 9711 ICmpInst::Predicate FoundPred, 9712 const SCEV *FoundLHS, 9713 const SCEV *FoundRHS) { 9714 // Balance the types. 9715 if (getTypeSizeInBits(LHS->getType()) < 9716 getTypeSizeInBits(FoundLHS->getType())) { 9717 if (CmpInst::isSigned(Pred)) { 9718 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9719 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9720 } else { 9721 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9722 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9723 } 9724 } else if (getTypeSizeInBits(LHS->getType()) > 9725 getTypeSizeInBits(FoundLHS->getType())) { 9726 if (CmpInst::isSigned(FoundPred)) { 9727 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9728 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9729 } else { 9730 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9731 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9732 } 9733 } 9734 9735 // Canonicalize the query to match the way instcombine will have 9736 // canonicalized the comparison. 9737 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9738 if (LHS == RHS) 9739 return CmpInst::isTrueWhenEqual(Pred); 9740 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9741 if (FoundLHS == FoundRHS) 9742 return CmpInst::isFalseWhenEqual(FoundPred); 9743 9744 // Check to see if we can make the LHS or RHS match. 9745 if (LHS == FoundRHS || RHS == FoundLHS) { 9746 if (isa<SCEVConstant>(RHS)) { 9747 std::swap(FoundLHS, FoundRHS); 9748 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9749 } else { 9750 std::swap(LHS, RHS); 9751 Pred = ICmpInst::getSwappedPredicate(Pred); 9752 } 9753 } 9754 9755 // Check whether the found predicate is the same as the desired predicate. 9756 if (FoundPred == Pred) 9757 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9758 9759 // Check whether swapping the found predicate makes it the same as the 9760 // desired predicate. 9761 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9762 if (isa<SCEVConstant>(RHS)) 9763 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9764 else 9765 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9766 RHS, LHS, FoundLHS, FoundRHS); 9767 } 9768 9769 // Unsigned comparison is the same as signed comparison when both the operands 9770 // are non-negative. 9771 if (CmpInst::isUnsigned(FoundPred) && 9772 CmpInst::getSignedPredicate(FoundPred) == Pred && 9773 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9774 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9775 9776 // Check if we can make progress by sharpening ranges. 9777 if (FoundPred == ICmpInst::ICMP_NE && 9778 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9779 9780 const SCEVConstant *C = nullptr; 9781 const SCEV *V = nullptr; 9782 9783 if (isa<SCEVConstant>(FoundLHS)) { 9784 C = cast<SCEVConstant>(FoundLHS); 9785 V = FoundRHS; 9786 } else { 9787 C = cast<SCEVConstant>(FoundRHS); 9788 V = FoundLHS; 9789 } 9790 9791 // The guarding predicate tells us that C != V. If the known range 9792 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9793 // range we consider has to correspond to same signedness as the 9794 // predicate we're interested in folding. 9795 9796 APInt Min = ICmpInst::isSigned(Pred) ? 9797 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9798 9799 if (Min == C->getAPInt()) { 9800 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9801 // This is true even if (Min + 1) wraps around -- in case of 9802 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9803 9804 APInt SharperMin = Min + 1; 9805 9806 switch (Pred) { 9807 case ICmpInst::ICMP_SGE: 9808 case ICmpInst::ICMP_UGE: 9809 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9810 // RHS, we're done. 9811 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9812 getConstant(SharperMin))) 9813 return true; 9814 LLVM_FALLTHROUGH; 9815 9816 case ICmpInst::ICMP_SGT: 9817 case ICmpInst::ICMP_UGT: 9818 // We know from the range information that (V `Pred` Min || 9819 // V == Min). We know from the guarding condition that !(V 9820 // == Min). This gives us 9821 // 9822 // V `Pred` Min || V == Min && !(V == Min) 9823 // => V `Pred` Min 9824 // 9825 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9826 9827 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9828 return true; 9829 LLVM_FALLTHROUGH; 9830 9831 default: 9832 // No change 9833 break; 9834 } 9835 } 9836 } 9837 9838 // Check whether the actual condition is beyond sufficient. 9839 if (FoundPred == ICmpInst::ICMP_EQ) 9840 if (ICmpInst::isTrueWhenEqual(Pred)) 9841 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9842 return true; 9843 if (Pred == ICmpInst::ICMP_NE) 9844 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9845 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9846 return true; 9847 9848 // Otherwise assume the worst. 9849 return false; 9850 } 9851 9852 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9853 const SCEV *&L, const SCEV *&R, 9854 SCEV::NoWrapFlags &Flags) { 9855 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9856 if (!AE || AE->getNumOperands() != 2) 9857 return false; 9858 9859 L = AE->getOperand(0); 9860 R = AE->getOperand(1); 9861 Flags = AE->getNoWrapFlags(); 9862 return true; 9863 } 9864 9865 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9866 const SCEV *Less) { 9867 // We avoid subtracting expressions here because this function is usually 9868 // fairly deep in the call stack (i.e. is called many times). 9869 9870 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9871 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9872 const auto *MAR = cast<SCEVAddRecExpr>(More); 9873 9874 if (LAR->getLoop() != MAR->getLoop()) 9875 return None; 9876 9877 // We look at affine expressions only; not for correctness but to keep 9878 // getStepRecurrence cheap. 9879 if (!LAR->isAffine() || !MAR->isAffine()) 9880 return None; 9881 9882 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9883 return None; 9884 9885 Less = LAR->getStart(); 9886 More = MAR->getStart(); 9887 9888 // fall through 9889 } 9890 9891 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9892 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9893 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9894 return M - L; 9895 } 9896 9897 SCEV::NoWrapFlags Flags; 9898 const SCEV *LLess = nullptr, *RLess = nullptr; 9899 const SCEV *LMore = nullptr, *RMore = nullptr; 9900 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9901 // Compare (X + C1) vs X. 9902 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9903 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9904 if (RLess == More) 9905 return -(C1->getAPInt()); 9906 9907 // Compare X vs (X + C2). 9908 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9909 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9910 if (RMore == Less) 9911 return C2->getAPInt(); 9912 9913 // Compare (X + C1) vs (X + C2). 9914 if (C1 && C2 && RLess == RMore) 9915 return C2->getAPInt() - C1->getAPInt(); 9916 9917 return None; 9918 } 9919 9920 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9921 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9922 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9923 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9924 return false; 9925 9926 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9927 if (!AddRecLHS) 9928 return false; 9929 9930 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9931 if (!AddRecFoundLHS) 9932 return false; 9933 9934 // We'd like to let SCEV reason about control dependencies, so we constrain 9935 // both the inequalities to be about add recurrences on the same loop. This 9936 // way we can use isLoopEntryGuardedByCond later. 9937 9938 const Loop *L = AddRecFoundLHS->getLoop(); 9939 if (L != AddRecLHS->getLoop()) 9940 return false; 9941 9942 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9943 // 9944 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9945 // ... (2) 9946 // 9947 // Informal proof for (2), assuming (1) [*]: 9948 // 9949 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9950 // 9951 // Then 9952 // 9953 // FoundLHS s< FoundRHS s< INT_MIN - C 9954 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9955 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9956 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9957 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9958 // <=> FoundLHS + C s< FoundRHS + C 9959 // 9960 // [*]: (1) can be proved by ruling out overflow. 9961 // 9962 // [**]: This can be proved by analyzing all the four possibilities: 9963 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9964 // (A s>= 0, B s>= 0). 9965 // 9966 // Note: 9967 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9968 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9969 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9970 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9971 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9972 // C)". 9973 9974 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9975 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9976 if (!LDiff || !RDiff || *LDiff != *RDiff) 9977 return false; 9978 9979 if (LDiff->isMinValue()) 9980 return true; 9981 9982 APInt FoundRHSLimit; 9983 9984 if (Pred == CmpInst::ICMP_ULT) { 9985 FoundRHSLimit = -(*RDiff); 9986 } else { 9987 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9988 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9989 } 9990 9991 // Try to prove (1) or (2), as needed. 9992 return isAvailableAtLoopEntry(FoundRHS, L) && 9993 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9994 getConstant(FoundRHSLimit)); 9995 } 9996 9997 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 9998 const SCEV *LHS, const SCEV *RHS, 9999 const SCEV *FoundLHS, 10000 const SCEV *FoundRHS, unsigned Depth) { 10001 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10002 10003 auto ClearOnExit = make_scope_exit([&]() { 10004 if (LPhi) { 10005 bool Erased = PendingMerges.erase(LPhi); 10006 assert(Erased && "Failed to erase LPhi!"); 10007 (void)Erased; 10008 } 10009 if (RPhi) { 10010 bool Erased = PendingMerges.erase(RPhi); 10011 assert(Erased && "Failed to erase RPhi!"); 10012 (void)Erased; 10013 } 10014 }); 10015 10016 // Find respective Phis and check that they are not being pending. 10017 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10018 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10019 if (!PendingMerges.insert(Phi).second) 10020 return false; 10021 LPhi = Phi; 10022 } 10023 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10024 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10025 // If we detect a loop of Phi nodes being processed by this method, for 10026 // example: 10027 // 10028 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10029 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10030 // 10031 // we don't want to deal with a case that complex, so return conservative 10032 // answer false. 10033 if (!PendingMerges.insert(Phi).second) 10034 return false; 10035 RPhi = Phi; 10036 } 10037 10038 // If none of LHS, RHS is a Phi, nothing to do here. 10039 if (!LPhi && !RPhi) 10040 return false; 10041 10042 // If there is a SCEVUnknown Phi we are interested in, make it left. 10043 if (!LPhi) { 10044 std::swap(LHS, RHS); 10045 std::swap(FoundLHS, FoundRHS); 10046 std::swap(LPhi, RPhi); 10047 Pred = ICmpInst::getSwappedPredicate(Pred); 10048 } 10049 10050 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10051 const BasicBlock *LBB = LPhi->getParent(); 10052 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10053 10054 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10055 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10056 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10057 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10058 }; 10059 10060 if (RPhi && RPhi->getParent() == LBB) { 10061 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10062 // If we compare two Phis from the same block, and for each entry block 10063 // the predicate is true for incoming values from this block, then the 10064 // predicate is also true for the Phis. 10065 for (const BasicBlock *IncBB : predecessors(LBB)) { 10066 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10067 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10068 if (!ProvedEasily(L, R)) 10069 return false; 10070 } 10071 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10072 // Case two: RHS is also a Phi from the same basic block, and it is an 10073 // AddRec. It means that there is a loop which has both AddRec and Unknown 10074 // PHIs, for it we can compare incoming values of AddRec from above the loop 10075 // and latch with their respective incoming values of LPhi. 10076 // TODO: Generalize to handle loops with many inputs in a header. 10077 if (LPhi->getNumIncomingValues() != 2) return false; 10078 10079 auto *RLoop = RAR->getLoop(); 10080 auto *Predecessor = RLoop->getLoopPredecessor(); 10081 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10082 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10083 if (!ProvedEasily(L1, RAR->getStart())) 10084 return false; 10085 auto *Latch = RLoop->getLoopLatch(); 10086 assert(Latch && "Loop with AddRec with no latch?"); 10087 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10088 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10089 return false; 10090 } else { 10091 // In all other cases go over inputs of LHS and compare each of them to RHS, 10092 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10093 // At this point RHS is either a non-Phi, or it is a Phi from some block 10094 // different from LBB. 10095 for (const BasicBlock *IncBB : predecessors(LBB)) { 10096 // Check that RHS is available in this block. 10097 if (!dominates(RHS, IncBB)) 10098 return false; 10099 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10100 if (!ProvedEasily(L, RHS)) 10101 return false; 10102 } 10103 } 10104 return true; 10105 } 10106 10107 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10108 const SCEV *LHS, const SCEV *RHS, 10109 const SCEV *FoundLHS, 10110 const SCEV *FoundRHS) { 10111 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10112 return true; 10113 10114 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10115 return true; 10116 10117 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10118 FoundLHS, FoundRHS) || 10119 // ~x < ~y --> x > y 10120 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10121 getNotSCEV(FoundRHS), 10122 getNotSCEV(FoundLHS)); 10123 } 10124 10125 /// If Expr computes ~A, return A else return nullptr 10126 static const SCEV *MatchNotExpr(const SCEV *Expr) { 10127 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 10128 if (!Add || Add->getNumOperands() != 2 || 10129 !Add->getOperand(0)->isAllOnesValue()) 10130 return nullptr; 10131 10132 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 10133 if (!AddRHS || AddRHS->getNumOperands() != 2 || 10134 !AddRHS->getOperand(0)->isAllOnesValue()) 10135 return nullptr; 10136 10137 return AddRHS->getOperand(1); 10138 } 10139 10140 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 10141 template<typename MaxExprType> 10142 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 10143 const SCEV *Candidate) { 10144 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 10145 if (!MaxExpr) return false; 10146 10147 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 10148 } 10149 10150 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 10151 template<typename MaxExprType> 10152 static bool IsMinConsistingOf(ScalarEvolution &SE, 10153 const SCEV *MaybeMinExpr, 10154 const SCEV *Candidate) { 10155 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 10156 if (!MaybeMaxExpr) 10157 return false; 10158 10159 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 10160 } 10161 10162 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10163 ICmpInst::Predicate Pred, 10164 const SCEV *LHS, const SCEV *RHS) { 10165 // If both sides are affine addrecs for the same loop, with equal 10166 // steps, and we know the recurrences don't wrap, then we only 10167 // need to check the predicate on the starting values. 10168 10169 if (!ICmpInst::isRelational(Pred)) 10170 return false; 10171 10172 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10173 if (!LAR) 10174 return false; 10175 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10176 if (!RAR) 10177 return false; 10178 if (LAR->getLoop() != RAR->getLoop()) 10179 return false; 10180 if (!LAR->isAffine() || !RAR->isAffine()) 10181 return false; 10182 10183 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10184 return false; 10185 10186 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10187 SCEV::FlagNSW : SCEV::FlagNUW; 10188 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10189 return false; 10190 10191 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10192 } 10193 10194 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10195 /// expression? 10196 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10197 ICmpInst::Predicate Pred, 10198 const SCEV *LHS, const SCEV *RHS) { 10199 switch (Pred) { 10200 default: 10201 return false; 10202 10203 case ICmpInst::ICMP_SGE: 10204 std::swap(LHS, RHS); 10205 LLVM_FALLTHROUGH; 10206 case ICmpInst::ICMP_SLE: 10207 return 10208 // min(A, ...) <= A 10209 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 10210 // A <= max(A, ...) 10211 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10212 10213 case ICmpInst::ICMP_UGE: 10214 std::swap(LHS, RHS); 10215 LLVM_FALLTHROUGH; 10216 case ICmpInst::ICMP_ULE: 10217 return 10218 // min(A, ...) <= A 10219 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 10220 // A <= max(A, ...) 10221 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10222 } 10223 10224 llvm_unreachable("covered switch fell through?!"); 10225 } 10226 10227 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10228 const SCEV *LHS, const SCEV *RHS, 10229 const SCEV *FoundLHS, 10230 const SCEV *FoundRHS, 10231 unsigned Depth) { 10232 assert(getTypeSizeInBits(LHS->getType()) == 10233 getTypeSizeInBits(RHS->getType()) && 10234 "LHS and RHS have different sizes?"); 10235 assert(getTypeSizeInBits(FoundLHS->getType()) == 10236 getTypeSizeInBits(FoundRHS->getType()) && 10237 "FoundLHS and FoundRHS have different sizes?"); 10238 // We want to avoid hurting the compile time with analysis of too big trees. 10239 if (Depth > MaxSCEVOperationsImplicationDepth) 10240 return false; 10241 // We only want to work with ICMP_SGT comparison so far. 10242 // TODO: Extend to ICMP_UGT? 10243 if (Pred == ICmpInst::ICMP_SLT) { 10244 Pred = ICmpInst::ICMP_SGT; 10245 std::swap(LHS, RHS); 10246 std::swap(FoundLHS, FoundRHS); 10247 } 10248 if (Pred != ICmpInst::ICMP_SGT) 10249 return false; 10250 10251 auto GetOpFromSExt = [&](const SCEV *S) { 10252 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10253 return Ext->getOperand(); 10254 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10255 // the constant in some cases. 10256 return S; 10257 }; 10258 10259 // Acquire values from extensions. 10260 auto *OrigLHS = LHS; 10261 auto *OrigFoundLHS = FoundLHS; 10262 LHS = GetOpFromSExt(LHS); 10263 FoundLHS = GetOpFromSExt(FoundLHS); 10264 10265 // Is the SGT predicate can be proved trivially or using the found context. 10266 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10267 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10268 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10269 FoundRHS, Depth + 1); 10270 }; 10271 10272 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10273 // We want to avoid creation of any new non-constant SCEV. Since we are 10274 // going to compare the operands to RHS, we should be certain that we don't 10275 // need any size extensions for this. So let's decline all cases when the 10276 // sizes of types of LHS and RHS do not match. 10277 // TODO: Maybe try to get RHS from sext to catch more cases? 10278 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10279 return false; 10280 10281 // Should not overflow. 10282 if (!LHSAddExpr->hasNoSignedWrap()) 10283 return false; 10284 10285 auto *LL = LHSAddExpr->getOperand(0); 10286 auto *LR = LHSAddExpr->getOperand(1); 10287 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10288 10289 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10290 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10291 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10292 }; 10293 // Try to prove the following rule: 10294 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10295 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10296 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10297 return true; 10298 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10299 Value *LL, *LR; 10300 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10301 10302 using namespace llvm::PatternMatch; 10303 10304 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10305 // Rules for division. 10306 // We are going to perform some comparisons with Denominator and its 10307 // derivative expressions. In general case, creating a SCEV for it may 10308 // lead to a complex analysis of the entire graph, and in particular it 10309 // can request trip count recalculation for the same loop. This would 10310 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10311 // this, we only want to create SCEVs that are constants in this section. 10312 // So we bail if Denominator is not a constant. 10313 if (!isa<ConstantInt>(LR)) 10314 return false; 10315 10316 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10317 10318 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10319 // then a SCEV for the numerator already exists and matches with FoundLHS. 10320 auto *Numerator = getExistingSCEV(LL); 10321 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10322 return false; 10323 10324 // Make sure that the numerator matches with FoundLHS and the denominator 10325 // is positive. 10326 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10327 return false; 10328 10329 auto *DTy = Denominator->getType(); 10330 auto *FRHSTy = FoundRHS->getType(); 10331 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10332 // One of types is a pointer and another one is not. We cannot extend 10333 // them properly to a wider type, so let us just reject this case. 10334 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10335 // to avoid this check. 10336 return false; 10337 10338 // Given that: 10339 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10340 auto *WTy = getWiderType(DTy, FRHSTy); 10341 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10342 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10343 10344 // Try to prove the following rule: 10345 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10346 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10347 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10348 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10349 if (isKnownNonPositive(RHS) && 10350 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10351 return true; 10352 10353 // Try to prove the following rule: 10354 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10355 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10356 // If we divide it by Denominator > 2, then: 10357 // 1. If FoundLHS is negative, then the result is 0. 10358 // 2. If FoundLHS is non-negative, then the result is non-negative. 10359 // Anyways, the result is non-negative. 10360 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10361 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10362 if (isKnownNegative(RHS) && 10363 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10364 return true; 10365 } 10366 } 10367 10368 // If our expression contained SCEVUnknown Phis, and we split it down and now 10369 // need to prove something for them, try to prove the predicate for every 10370 // possible incoming values of those Phis. 10371 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10372 return true; 10373 10374 return false; 10375 } 10376 10377 bool 10378 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10379 const SCEV *LHS, const SCEV *RHS) { 10380 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10381 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10382 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10383 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10384 } 10385 10386 bool 10387 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10388 const SCEV *LHS, const SCEV *RHS, 10389 const SCEV *FoundLHS, 10390 const SCEV *FoundRHS) { 10391 switch (Pred) { 10392 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10393 case ICmpInst::ICMP_EQ: 10394 case ICmpInst::ICMP_NE: 10395 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10396 return true; 10397 break; 10398 case ICmpInst::ICMP_SLT: 10399 case ICmpInst::ICMP_SLE: 10400 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10401 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10402 return true; 10403 break; 10404 case ICmpInst::ICMP_SGT: 10405 case ICmpInst::ICMP_SGE: 10406 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10407 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10408 return true; 10409 break; 10410 case ICmpInst::ICMP_ULT: 10411 case ICmpInst::ICMP_ULE: 10412 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10413 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10414 return true; 10415 break; 10416 case ICmpInst::ICMP_UGT: 10417 case ICmpInst::ICMP_UGE: 10418 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10419 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10420 return true; 10421 break; 10422 } 10423 10424 // Maybe it can be proved via operations? 10425 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10426 return true; 10427 10428 return false; 10429 } 10430 10431 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10432 const SCEV *LHS, 10433 const SCEV *RHS, 10434 const SCEV *FoundLHS, 10435 const SCEV *FoundRHS) { 10436 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10437 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10438 // reduce the compile time impact of this optimization. 10439 return false; 10440 10441 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10442 if (!Addend) 10443 return false; 10444 10445 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10446 10447 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10448 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10449 ConstantRange FoundLHSRange = 10450 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10451 10452 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10453 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10454 10455 // We can also compute the range of values for `LHS` that satisfy the 10456 // consequent, "`LHS` `Pred` `RHS`": 10457 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10458 ConstantRange SatisfyingLHSRange = 10459 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10460 10461 // The antecedent implies the consequent if every value of `LHS` that 10462 // satisfies the antecedent also satisfies the consequent. 10463 return SatisfyingLHSRange.contains(LHSRange); 10464 } 10465 10466 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10467 bool IsSigned, bool NoWrap) { 10468 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10469 10470 if (NoWrap) return false; 10471 10472 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10473 const SCEV *One = getOne(Stride->getType()); 10474 10475 if (IsSigned) { 10476 APInt MaxRHS = getSignedRangeMax(RHS); 10477 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10478 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10479 10480 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10481 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10482 } 10483 10484 APInt MaxRHS = getUnsignedRangeMax(RHS); 10485 APInt MaxValue = APInt::getMaxValue(BitWidth); 10486 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10487 10488 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10489 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10490 } 10491 10492 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10493 bool IsSigned, bool NoWrap) { 10494 if (NoWrap) return false; 10495 10496 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10497 const SCEV *One = getOne(Stride->getType()); 10498 10499 if (IsSigned) { 10500 APInt MinRHS = getSignedRangeMin(RHS); 10501 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10502 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10503 10504 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10505 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10506 } 10507 10508 APInt MinRHS = getUnsignedRangeMin(RHS); 10509 APInt MinValue = APInt::getMinValue(BitWidth); 10510 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10511 10512 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10513 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10514 } 10515 10516 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10517 bool Equality) { 10518 const SCEV *One = getOne(Step->getType()); 10519 Delta = Equality ? getAddExpr(Delta, Step) 10520 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10521 return getUDivExpr(Delta, Step); 10522 } 10523 10524 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10525 const SCEV *Stride, 10526 const SCEV *End, 10527 unsigned BitWidth, 10528 bool IsSigned) { 10529 10530 assert(!isKnownNonPositive(Stride) && 10531 "Stride is expected strictly positive!"); 10532 // Calculate the maximum backedge count based on the range of values 10533 // permitted by Start, End, and Stride. 10534 const SCEV *MaxBECount; 10535 APInt MinStart = 10536 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10537 10538 APInt StrideForMaxBECount = 10539 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10540 10541 // We already know that the stride is positive, so we paper over conservatism 10542 // in our range computation by forcing StrideForMaxBECount to be at least one. 10543 // In theory this is unnecessary, but we expect MaxBECount to be a 10544 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10545 // is nothing to constant fold it to). 10546 APInt One(BitWidth, 1, IsSigned); 10547 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10548 10549 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10550 : APInt::getMaxValue(BitWidth); 10551 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10552 10553 // Although End can be a MAX expression we estimate MaxEnd considering only 10554 // the case End = RHS of the loop termination condition. This is safe because 10555 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10556 // taken count. 10557 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10558 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10559 10560 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10561 getConstant(StrideForMaxBECount) /* Step */, 10562 false /* Equality */); 10563 10564 return MaxBECount; 10565 } 10566 10567 ScalarEvolution::ExitLimit 10568 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10569 const Loop *L, bool IsSigned, 10570 bool ControlsExit, bool AllowPredicates) { 10571 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10572 10573 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10574 bool PredicatedIV = false; 10575 10576 if (!IV && AllowPredicates) { 10577 // Try to make this an AddRec using runtime tests, in the first X 10578 // iterations of this loop, where X is the SCEV expression found by the 10579 // algorithm below. 10580 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10581 PredicatedIV = true; 10582 } 10583 10584 // Avoid weird loops 10585 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10586 return getCouldNotCompute(); 10587 10588 bool NoWrap = ControlsExit && 10589 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10590 10591 const SCEV *Stride = IV->getStepRecurrence(*this); 10592 10593 bool PositiveStride = isKnownPositive(Stride); 10594 10595 // Avoid negative or zero stride values. 10596 if (!PositiveStride) { 10597 // We can compute the correct backedge taken count for loops with unknown 10598 // strides if we can prove that the loop is not an infinite loop with side 10599 // effects. Here's the loop structure we are trying to handle - 10600 // 10601 // i = start 10602 // do { 10603 // A[i] = i; 10604 // i += s; 10605 // } while (i < end); 10606 // 10607 // The backedge taken count for such loops is evaluated as - 10608 // (max(end, start + stride) - start - 1) /u stride 10609 // 10610 // The additional preconditions that we need to check to prove correctness 10611 // of the above formula is as follows - 10612 // 10613 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10614 // NoWrap flag). 10615 // b) loop is single exit with no side effects. 10616 // 10617 // 10618 // Precondition a) implies that if the stride is negative, this is a single 10619 // trip loop. The backedge taken count formula reduces to zero in this case. 10620 // 10621 // Precondition b) implies that the unknown stride cannot be zero otherwise 10622 // we have UB. 10623 // 10624 // The positive stride case is the same as isKnownPositive(Stride) returning 10625 // true (original behavior of the function). 10626 // 10627 // We want to make sure that the stride is truly unknown as there are edge 10628 // cases where ScalarEvolution propagates no wrap flags to the 10629 // post-increment/decrement IV even though the increment/decrement operation 10630 // itself is wrapping. The computed backedge taken count may be wrong in 10631 // such cases. This is prevented by checking that the stride is not known to 10632 // be either positive or non-positive. For example, no wrap flags are 10633 // propagated to the post-increment IV of this loop with a trip count of 2 - 10634 // 10635 // unsigned char i; 10636 // for(i=127; i<128; i+=129) 10637 // A[i] = i; 10638 // 10639 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10640 !loopHasNoSideEffects(L)) 10641 return getCouldNotCompute(); 10642 } else if (!Stride->isOne() && 10643 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10644 // Avoid proven overflow cases: this will ensure that the backedge taken 10645 // count will not generate any unsigned overflow. Relaxed no-overflow 10646 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10647 // undefined behaviors like the case of C language. 10648 return getCouldNotCompute(); 10649 10650 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10651 : ICmpInst::ICMP_ULT; 10652 const SCEV *Start = IV->getStart(); 10653 const SCEV *End = RHS; 10654 // When the RHS is not invariant, we do not know the end bound of the loop and 10655 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10656 // calculate the MaxBECount, given the start, stride and max value for the end 10657 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10658 // checked above). 10659 if (!isLoopInvariant(RHS, L)) { 10660 const SCEV *MaxBECount = computeMaxBECountForLT( 10661 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10662 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10663 false /*MaxOrZero*/, Predicates); 10664 } 10665 // If the backedge is taken at least once, then it will be taken 10666 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10667 // is the LHS value of the less-than comparison the first time it is evaluated 10668 // and End is the RHS. 10669 const SCEV *BECountIfBackedgeTaken = 10670 computeBECount(getMinusSCEV(End, Start), Stride, false); 10671 // If the loop entry is guarded by the result of the backedge test of the 10672 // first loop iteration, then we know the backedge will be taken at least 10673 // once and so the backedge taken count is as above. If not then we use the 10674 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10675 // as if the backedge is taken at least once max(End,Start) is End and so the 10676 // result is as above, and if not max(End,Start) is Start so we get a backedge 10677 // count of zero. 10678 const SCEV *BECount; 10679 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10680 BECount = BECountIfBackedgeTaken; 10681 else { 10682 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10683 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10684 } 10685 10686 const SCEV *MaxBECount; 10687 bool MaxOrZero = false; 10688 if (isa<SCEVConstant>(BECount)) 10689 MaxBECount = BECount; 10690 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10691 // If we know exactly how many times the backedge will be taken if it's 10692 // taken at least once, then the backedge count will either be that or 10693 // zero. 10694 MaxBECount = BECountIfBackedgeTaken; 10695 MaxOrZero = true; 10696 } else { 10697 MaxBECount = computeMaxBECountForLT( 10698 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10699 } 10700 10701 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10702 !isa<SCEVCouldNotCompute>(BECount)) 10703 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10704 10705 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10706 } 10707 10708 ScalarEvolution::ExitLimit 10709 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10710 const Loop *L, bool IsSigned, 10711 bool ControlsExit, bool AllowPredicates) { 10712 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10713 // We handle only IV > Invariant 10714 if (!isLoopInvariant(RHS, L)) 10715 return getCouldNotCompute(); 10716 10717 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10718 if (!IV && AllowPredicates) 10719 // Try to make this an AddRec using runtime tests, in the first X 10720 // iterations of this loop, where X is the SCEV expression found by the 10721 // algorithm below. 10722 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10723 10724 // Avoid weird loops 10725 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10726 return getCouldNotCompute(); 10727 10728 bool NoWrap = ControlsExit && 10729 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10730 10731 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10732 10733 // Avoid negative or zero stride values 10734 if (!isKnownPositive(Stride)) 10735 return getCouldNotCompute(); 10736 10737 // Avoid proven overflow cases: this will ensure that the backedge taken count 10738 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10739 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10740 // behaviors like the case of C language. 10741 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10742 return getCouldNotCompute(); 10743 10744 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10745 : ICmpInst::ICMP_UGT; 10746 10747 const SCEV *Start = IV->getStart(); 10748 const SCEV *End = RHS; 10749 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10750 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10751 10752 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10753 10754 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10755 : getUnsignedRangeMax(Start); 10756 10757 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10758 : getUnsignedRangeMin(Stride); 10759 10760 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10761 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10762 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10763 10764 // Although End can be a MIN expression we estimate MinEnd considering only 10765 // the case End = RHS. This is safe because in the other case (Start - End) 10766 // is zero, leading to a zero maximum backedge taken count. 10767 APInt MinEnd = 10768 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10769 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10770 10771 10772 const SCEV *MaxBECount = getCouldNotCompute(); 10773 if (isa<SCEVConstant>(BECount)) 10774 MaxBECount = BECount; 10775 else 10776 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 10777 getConstant(MinStride), false); 10778 10779 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10780 MaxBECount = BECount; 10781 10782 return ExitLimit(BECount, MaxBECount, false, Predicates); 10783 } 10784 10785 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10786 ScalarEvolution &SE) const { 10787 if (Range.isFullSet()) // Infinite loop. 10788 return SE.getCouldNotCompute(); 10789 10790 // If the start is a non-zero constant, shift the range to simplify things. 10791 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10792 if (!SC->getValue()->isZero()) { 10793 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10794 Operands[0] = SE.getZero(SC->getType()); 10795 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10796 getNoWrapFlags(FlagNW)); 10797 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10798 return ShiftedAddRec->getNumIterationsInRange( 10799 Range.subtract(SC->getAPInt()), SE); 10800 // This is strange and shouldn't happen. 10801 return SE.getCouldNotCompute(); 10802 } 10803 10804 // The only time we can solve this is when we have all constant indices. 10805 // Otherwise, we cannot determine the overflow conditions. 10806 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10807 return SE.getCouldNotCompute(); 10808 10809 // Okay at this point we know that all elements of the chrec are constants and 10810 // that the start element is zero. 10811 10812 // First check to see if the range contains zero. If not, the first 10813 // iteration exits. 10814 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10815 if (!Range.contains(APInt(BitWidth, 0))) 10816 return SE.getZero(getType()); 10817 10818 if (isAffine()) { 10819 // If this is an affine expression then we have this situation: 10820 // Solve {0,+,A} in Range === Ax in Range 10821 10822 // We know that zero is in the range. If A is positive then we know that 10823 // the upper value of the range must be the first possible exit value. 10824 // If A is negative then the lower of the range is the last possible loop 10825 // value. Also note that we already checked for a full range. 10826 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10827 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10828 10829 // The exit value should be (End+A)/A. 10830 APInt ExitVal = (End + A).udiv(A); 10831 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10832 10833 // Evaluate at the exit value. If we really did fall out of the valid 10834 // range, then we computed our trip count, otherwise wrap around or other 10835 // things must have happened. 10836 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10837 if (Range.contains(Val->getValue())) 10838 return SE.getCouldNotCompute(); // Something strange happened 10839 10840 // Ensure that the previous value is in the range. This is a sanity check. 10841 assert(Range.contains( 10842 EvaluateConstantChrecAtConstant(this, 10843 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10844 "Linear scev computation is off in a bad way!"); 10845 return SE.getConstant(ExitValue); 10846 } 10847 10848 if (isQuadratic()) { 10849 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10850 return SE.getConstant(S.getValue()); 10851 } 10852 10853 return SE.getCouldNotCompute(); 10854 } 10855 10856 const SCEVAddRecExpr * 10857 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10858 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10859 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10860 // but in this case we cannot guarantee that the value returned will be an 10861 // AddRec because SCEV does not have a fixed point where it stops 10862 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10863 // may happen if we reach arithmetic depth limit while simplifying. So we 10864 // construct the returned value explicitly. 10865 SmallVector<const SCEV *, 3> Ops; 10866 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10867 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10868 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10869 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10870 // We know that the last operand is not a constant zero (otherwise it would 10871 // have been popped out earlier). This guarantees us that if the result has 10872 // the same last operand, then it will also not be popped out, meaning that 10873 // the returned value will be an AddRec. 10874 const SCEV *Last = getOperand(getNumOperands() - 1); 10875 assert(!Last->isZero() && "Recurrency with zero step?"); 10876 Ops.push_back(Last); 10877 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10878 SCEV::FlagAnyWrap)); 10879 } 10880 10881 // Return true when S contains at least an undef value. 10882 static inline bool containsUndefs(const SCEV *S) { 10883 return SCEVExprContains(S, [](const SCEV *S) { 10884 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10885 return isa<UndefValue>(SU->getValue()); 10886 return false; 10887 }); 10888 } 10889 10890 namespace { 10891 10892 // Collect all steps of SCEV expressions. 10893 struct SCEVCollectStrides { 10894 ScalarEvolution &SE; 10895 SmallVectorImpl<const SCEV *> &Strides; 10896 10897 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10898 : SE(SE), Strides(S) {} 10899 10900 bool follow(const SCEV *S) { 10901 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10902 Strides.push_back(AR->getStepRecurrence(SE)); 10903 return true; 10904 } 10905 10906 bool isDone() const { return false; } 10907 }; 10908 10909 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10910 struct SCEVCollectTerms { 10911 SmallVectorImpl<const SCEV *> &Terms; 10912 10913 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10914 10915 bool follow(const SCEV *S) { 10916 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10917 isa<SCEVSignExtendExpr>(S)) { 10918 if (!containsUndefs(S)) 10919 Terms.push_back(S); 10920 10921 // Stop recursion: once we collected a term, do not walk its operands. 10922 return false; 10923 } 10924 10925 // Keep looking. 10926 return true; 10927 } 10928 10929 bool isDone() const { return false; } 10930 }; 10931 10932 // Check if a SCEV contains an AddRecExpr. 10933 struct SCEVHasAddRec { 10934 bool &ContainsAddRec; 10935 10936 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10937 ContainsAddRec = false; 10938 } 10939 10940 bool follow(const SCEV *S) { 10941 if (isa<SCEVAddRecExpr>(S)) { 10942 ContainsAddRec = true; 10943 10944 // Stop recursion: once we collected a term, do not walk its operands. 10945 return false; 10946 } 10947 10948 // Keep looking. 10949 return true; 10950 } 10951 10952 bool isDone() const { return false; } 10953 }; 10954 10955 // Find factors that are multiplied with an expression that (possibly as a 10956 // subexpression) contains an AddRecExpr. In the expression: 10957 // 10958 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10959 // 10960 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10961 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10962 // parameters as they form a product with an induction variable. 10963 // 10964 // This collector expects all array size parameters to be in the same MulExpr. 10965 // It might be necessary to later add support for collecting parameters that are 10966 // spread over different nested MulExpr. 10967 struct SCEVCollectAddRecMultiplies { 10968 SmallVectorImpl<const SCEV *> &Terms; 10969 ScalarEvolution &SE; 10970 10971 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10972 : Terms(T), SE(SE) {} 10973 10974 bool follow(const SCEV *S) { 10975 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10976 bool HasAddRec = false; 10977 SmallVector<const SCEV *, 0> Operands; 10978 for (auto Op : Mul->operands()) { 10979 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10980 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10981 Operands.push_back(Op); 10982 } else if (Unknown) { 10983 HasAddRec = true; 10984 } else { 10985 bool ContainsAddRec; 10986 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10987 visitAll(Op, ContiansAddRec); 10988 HasAddRec |= ContainsAddRec; 10989 } 10990 } 10991 if (Operands.size() == 0) 10992 return true; 10993 10994 if (!HasAddRec) 10995 return false; 10996 10997 Terms.push_back(SE.getMulExpr(Operands)); 10998 // Stop recursion: once we collected a term, do not walk its operands. 10999 return false; 11000 } 11001 11002 // Keep looking. 11003 return true; 11004 } 11005 11006 bool isDone() const { return false; } 11007 }; 11008 11009 } // end anonymous namespace 11010 11011 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11012 /// two places: 11013 /// 1) The strides of AddRec expressions. 11014 /// 2) Unknowns that are multiplied with AddRec expressions. 11015 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11016 SmallVectorImpl<const SCEV *> &Terms) { 11017 SmallVector<const SCEV *, 4> Strides; 11018 SCEVCollectStrides StrideCollector(*this, Strides); 11019 visitAll(Expr, StrideCollector); 11020 11021 LLVM_DEBUG({ 11022 dbgs() << "Strides:\n"; 11023 for (const SCEV *S : Strides) 11024 dbgs() << *S << "\n"; 11025 }); 11026 11027 for (const SCEV *S : Strides) { 11028 SCEVCollectTerms TermCollector(Terms); 11029 visitAll(S, TermCollector); 11030 } 11031 11032 LLVM_DEBUG({ 11033 dbgs() << "Terms:\n"; 11034 for (const SCEV *T : Terms) 11035 dbgs() << *T << "\n"; 11036 }); 11037 11038 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11039 visitAll(Expr, MulCollector); 11040 } 11041 11042 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11043 SmallVectorImpl<const SCEV *> &Terms, 11044 SmallVectorImpl<const SCEV *> &Sizes) { 11045 int Last = Terms.size() - 1; 11046 const SCEV *Step = Terms[Last]; 11047 11048 // End of recursion. 11049 if (Last == 0) { 11050 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11051 SmallVector<const SCEV *, 2> Qs; 11052 for (const SCEV *Op : M->operands()) 11053 if (!isa<SCEVConstant>(Op)) 11054 Qs.push_back(Op); 11055 11056 Step = SE.getMulExpr(Qs); 11057 } 11058 11059 Sizes.push_back(Step); 11060 return true; 11061 } 11062 11063 for (const SCEV *&Term : Terms) { 11064 // Normalize the terms before the next call to findArrayDimensionsRec. 11065 const SCEV *Q, *R; 11066 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11067 11068 // Bail out when GCD does not evenly divide one of the terms. 11069 if (!R->isZero()) 11070 return false; 11071 11072 Term = Q; 11073 } 11074 11075 // Remove all SCEVConstants. 11076 Terms.erase( 11077 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11078 Terms.end()); 11079 11080 if (Terms.size() > 0) 11081 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11082 return false; 11083 11084 Sizes.push_back(Step); 11085 return true; 11086 } 11087 11088 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11089 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11090 for (const SCEV *T : Terms) 11091 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 11092 return true; 11093 return false; 11094 } 11095 11096 // Return the number of product terms in S. 11097 static inline int numberOfTerms(const SCEV *S) { 11098 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11099 return Expr->getNumOperands(); 11100 return 1; 11101 } 11102 11103 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11104 if (isa<SCEVConstant>(T)) 11105 return nullptr; 11106 11107 if (isa<SCEVUnknown>(T)) 11108 return T; 11109 11110 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11111 SmallVector<const SCEV *, 2> Factors; 11112 for (const SCEV *Op : M->operands()) 11113 if (!isa<SCEVConstant>(Op)) 11114 Factors.push_back(Op); 11115 11116 return SE.getMulExpr(Factors); 11117 } 11118 11119 return T; 11120 } 11121 11122 /// Return the size of an element read or written by Inst. 11123 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11124 Type *Ty; 11125 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11126 Ty = Store->getValueOperand()->getType(); 11127 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11128 Ty = Load->getType(); 11129 else 11130 return nullptr; 11131 11132 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11133 return getSizeOfExpr(ETy, Ty); 11134 } 11135 11136 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11137 SmallVectorImpl<const SCEV *> &Sizes, 11138 const SCEV *ElementSize) { 11139 if (Terms.size() < 1 || !ElementSize) 11140 return; 11141 11142 // Early return when Terms do not contain parameters: we do not delinearize 11143 // non parametric SCEVs. 11144 if (!containsParameters(Terms)) 11145 return; 11146 11147 LLVM_DEBUG({ 11148 dbgs() << "Terms:\n"; 11149 for (const SCEV *T : Terms) 11150 dbgs() << *T << "\n"; 11151 }); 11152 11153 // Remove duplicates. 11154 array_pod_sort(Terms.begin(), Terms.end()); 11155 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11156 11157 // Put larger terms first. 11158 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11159 return numberOfTerms(LHS) > numberOfTerms(RHS); 11160 }); 11161 11162 // Try to divide all terms by the element size. If term is not divisible by 11163 // element size, proceed with the original term. 11164 for (const SCEV *&Term : Terms) { 11165 const SCEV *Q, *R; 11166 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11167 if (!Q->isZero()) 11168 Term = Q; 11169 } 11170 11171 SmallVector<const SCEV *, 4> NewTerms; 11172 11173 // Remove constant factors. 11174 for (const SCEV *T : Terms) 11175 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11176 NewTerms.push_back(NewT); 11177 11178 LLVM_DEBUG({ 11179 dbgs() << "Terms after sorting:\n"; 11180 for (const SCEV *T : NewTerms) 11181 dbgs() << *T << "\n"; 11182 }); 11183 11184 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11185 Sizes.clear(); 11186 return; 11187 } 11188 11189 // The last element to be pushed into Sizes is the size of an element. 11190 Sizes.push_back(ElementSize); 11191 11192 LLVM_DEBUG({ 11193 dbgs() << "Sizes:\n"; 11194 for (const SCEV *S : Sizes) 11195 dbgs() << *S << "\n"; 11196 }); 11197 } 11198 11199 void ScalarEvolution::computeAccessFunctions( 11200 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11201 SmallVectorImpl<const SCEV *> &Sizes) { 11202 // Early exit in case this SCEV is not an affine multivariate function. 11203 if (Sizes.empty()) 11204 return; 11205 11206 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11207 if (!AR->isAffine()) 11208 return; 11209 11210 const SCEV *Res = Expr; 11211 int Last = Sizes.size() - 1; 11212 for (int i = Last; i >= 0; i--) { 11213 const SCEV *Q, *R; 11214 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11215 11216 LLVM_DEBUG({ 11217 dbgs() << "Res: " << *Res << "\n"; 11218 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11219 dbgs() << "Res divided by Sizes[i]:\n"; 11220 dbgs() << "Quotient: " << *Q << "\n"; 11221 dbgs() << "Remainder: " << *R << "\n"; 11222 }); 11223 11224 Res = Q; 11225 11226 // Do not record the last subscript corresponding to the size of elements in 11227 // the array. 11228 if (i == Last) { 11229 11230 // Bail out if the remainder is too complex. 11231 if (isa<SCEVAddRecExpr>(R)) { 11232 Subscripts.clear(); 11233 Sizes.clear(); 11234 return; 11235 } 11236 11237 continue; 11238 } 11239 11240 // Record the access function for the current subscript. 11241 Subscripts.push_back(R); 11242 } 11243 11244 // Also push in last position the remainder of the last division: it will be 11245 // the access function of the innermost dimension. 11246 Subscripts.push_back(Res); 11247 11248 std::reverse(Subscripts.begin(), Subscripts.end()); 11249 11250 LLVM_DEBUG({ 11251 dbgs() << "Subscripts:\n"; 11252 for (const SCEV *S : Subscripts) 11253 dbgs() << *S << "\n"; 11254 }); 11255 } 11256 11257 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11258 /// sizes of an array access. Returns the remainder of the delinearization that 11259 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11260 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11261 /// expressions in the stride and base of a SCEV corresponding to the 11262 /// computation of a GCD (greatest common divisor) of base and stride. When 11263 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11264 /// 11265 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11266 /// 11267 /// void foo(long n, long m, long o, double A[n][m][o]) { 11268 /// 11269 /// for (long i = 0; i < n; i++) 11270 /// for (long j = 0; j < m; j++) 11271 /// for (long k = 0; k < o; k++) 11272 /// A[i][j][k] = 1.0; 11273 /// } 11274 /// 11275 /// the delinearization input is the following AddRec SCEV: 11276 /// 11277 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11278 /// 11279 /// From this SCEV, we are able to say that the base offset of the access is %A 11280 /// because it appears as an offset that does not divide any of the strides in 11281 /// the loops: 11282 /// 11283 /// CHECK: Base offset: %A 11284 /// 11285 /// and then SCEV->delinearize determines the size of some of the dimensions of 11286 /// the array as these are the multiples by which the strides are happening: 11287 /// 11288 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11289 /// 11290 /// Note that the outermost dimension remains of UnknownSize because there are 11291 /// no strides that would help identifying the size of the last dimension: when 11292 /// the array has been statically allocated, one could compute the size of that 11293 /// dimension by dividing the overall size of the array by the size of the known 11294 /// dimensions: %m * %o * 8. 11295 /// 11296 /// Finally delinearize provides the access functions for the array reference 11297 /// that does correspond to A[i][j][k] of the above C testcase: 11298 /// 11299 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11300 /// 11301 /// The testcases are checking the output of a function pass: 11302 /// DelinearizationPass that walks through all loads and stores of a function 11303 /// asking for the SCEV of the memory access with respect to all enclosing 11304 /// loops, calling SCEV->delinearize on that and printing the results. 11305 void ScalarEvolution::delinearize(const SCEV *Expr, 11306 SmallVectorImpl<const SCEV *> &Subscripts, 11307 SmallVectorImpl<const SCEV *> &Sizes, 11308 const SCEV *ElementSize) { 11309 // First step: collect parametric terms. 11310 SmallVector<const SCEV *, 4> Terms; 11311 collectParametricTerms(Expr, Terms); 11312 11313 if (Terms.empty()) 11314 return; 11315 11316 // Second step: find subscript sizes. 11317 findArrayDimensions(Terms, Sizes, ElementSize); 11318 11319 if (Sizes.empty()) 11320 return; 11321 11322 // Third step: compute the access functions for each subscript. 11323 computeAccessFunctions(Expr, Subscripts, Sizes); 11324 11325 if (Subscripts.empty()) 11326 return; 11327 11328 LLVM_DEBUG({ 11329 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11330 dbgs() << "ArrayDecl[UnknownSize]"; 11331 for (const SCEV *S : Sizes) 11332 dbgs() << "[" << *S << "]"; 11333 11334 dbgs() << "\nArrayRef"; 11335 for (const SCEV *S : Subscripts) 11336 dbgs() << "[" << *S << "]"; 11337 dbgs() << "\n"; 11338 }); 11339 } 11340 11341 //===----------------------------------------------------------------------===// 11342 // SCEVCallbackVH Class Implementation 11343 //===----------------------------------------------------------------------===// 11344 11345 void ScalarEvolution::SCEVCallbackVH::deleted() { 11346 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11347 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11348 SE->ConstantEvolutionLoopExitValue.erase(PN); 11349 SE->eraseValueFromMap(getValPtr()); 11350 // this now dangles! 11351 } 11352 11353 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11354 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11355 11356 // Forget all the expressions associated with users of the old value, 11357 // so that future queries will recompute the expressions using the new 11358 // value. 11359 Value *Old = getValPtr(); 11360 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11361 SmallPtrSet<User *, 8> Visited; 11362 while (!Worklist.empty()) { 11363 User *U = Worklist.pop_back_val(); 11364 // Deleting the Old value will cause this to dangle. Postpone 11365 // that until everything else is done. 11366 if (U == Old) 11367 continue; 11368 if (!Visited.insert(U).second) 11369 continue; 11370 if (PHINode *PN = dyn_cast<PHINode>(U)) 11371 SE->ConstantEvolutionLoopExitValue.erase(PN); 11372 SE->eraseValueFromMap(U); 11373 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11374 } 11375 // Delete the Old value. 11376 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11377 SE->ConstantEvolutionLoopExitValue.erase(PN); 11378 SE->eraseValueFromMap(Old); 11379 // this now dangles! 11380 } 11381 11382 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11383 : CallbackVH(V), SE(se) {} 11384 11385 //===----------------------------------------------------------------------===// 11386 // ScalarEvolution Class Implementation 11387 //===----------------------------------------------------------------------===// 11388 11389 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11390 AssumptionCache &AC, DominatorTree &DT, 11391 LoopInfo &LI) 11392 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11393 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11394 LoopDispositions(64), BlockDispositions(64) { 11395 // To use guards for proving predicates, we need to scan every instruction in 11396 // relevant basic blocks, and not just terminators. Doing this is a waste of 11397 // time if the IR does not actually contain any calls to 11398 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11399 // 11400 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11401 // to _add_ guards to the module when there weren't any before, and wants 11402 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11403 // efficient in lieu of being smart in that rather obscure case. 11404 11405 auto *GuardDecl = F.getParent()->getFunction( 11406 Intrinsic::getName(Intrinsic::experimental_guard)); 11407 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11408 } 11409 11410 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11411 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11412 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11413 ValueExprMap(std::move(Arg.ValueExprMap)), 11414 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11415 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11416 PendingMerges(std::move(Arg.PendingMerges)), 11417 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11418 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11419 PredicatedBackedgeTakenCounts( 11420 std::move(Arg.PredicatedBackedgeTakenCounts)), 11421 ConstantEvolutionLoopExitValue( 11422 std::move(Arg.ConstantEvolutionLoopExitValue)), 11423 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11424 LoopDispositions(std::move(Arg.LoopDispositions)), 11425 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11426 BlockDispositions(std::move(Arg.BlockDispositions)), 11427 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11428 SignedRanges(std::move(Arg.SignedRanges)), 11429 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11430 UniquePreds(std::move(Arg.UniquePreds)), 11431 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11432 LoopUsers(std::move(Arg.LoopUsers)), 11433 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11434 FirstUnknown(Arg.FirstUnknown) { 11435 Arg.FirstUnknown = nullptr; 11436 } 11437 11438 ScalarEvolution::~ScalarEvolution() { 11439 // Iterate through all the SCEVUnknown instances and call their 11440 // destructors, so that they release their references to their values. 11441 for (SCEVUnknown *U = FirstUnknown; U;) { 11442 SCEVUnknown *Tmp = U; 11443 U = U->Next; 11444 Tmp->~SCEVUnknown(); 11445 } 11446 FirstUnknown = nullptr; 11447 11448 ExprValueMap.clear(); 11449 ValueExprMap.clear(); 11450 HasRecMap.clear(); 11451 11452 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11453 // that a loop had multiple computable exits. 11454 for (auto &BTCI : BackedgeTakenCounts) 11455 BTCI.second.clear(); 11456 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11457 BTCI.second.clear(); 11458 11459 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11460 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11461 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11462 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11463 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11464 } 11465 11466 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11467 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11468 } 11469 11470 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11471 const Loop *L) { 11472 // Print all inner loops first 11473 for (Loop *I : *L) 11474 PrintLoopInfo(OS, SE, I); 11475 11476 OS << "Loop "; 11477 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11478 OS << ": "; 11479 11480 SmallVector<BasicBlock *, 8> ExitBlocks; 11481 L->getExitBlocks(ExitBlocks); 11482 if (ExitBlocks.size() != 1) 11483 OS << "<multiple exits> "; 11484 11485 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11486 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 11487 } else { 11488 OS << "Unpredictable backedge-taken count. "; 11489 } 11490 11491 OS << "\n" 11492 "Loop "; 11493 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11494 OS << ": "; 11495 11496 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 11497 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 11498 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11499 OS << ", actual taken count either this or zero."; 11500 } else { 11501 OS << "Unpredictable max backedge-taken count. "; 11502 } 11503 11504 OS << "\n" 11505 "Loop "; 11506 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11507 OS << ": "; 11508 11509 SCEVUnionPredicate Pred; 11510 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11511 if (!isa<SCEVCouldNotCompute>(PBT)) { 11512 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11513 OS << " Predicates:\n"; 11514 Pred.print(OS, 4); 11515 } else { 11516 OS << "Unpredictable predicated backedge-taken count. "; 11517 } 11518 OS << "\n"; 11519 11520 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11521 OS << "Loop "; 11522 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11523 OS << ": "; 11524 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11525 } 11526 } 11527 11528 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11529 switch (LD) { 11530 case ScalarEvolution::LoopVariant: 11531 return "Variant"; 11532 case ScalarEvolution::LoopInvariant: 11533 return "Invariant"; 11534 case ScalarEvolution::LoopComputable: 11535 return "Computable"; 11536 } 11537 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11538 } 11539 11540 void ScalarEvolution::print(raw_ostream &OS) const { 11541 // ScalarEvolution's implementation of the print method is to print 11542 // out SCEV values of all instructions that are interesting. Doing 11543 // this potentially causes it to create new SCEV objects though, 11544 // which technically conflicts with the const qualifier. This isn't 11545 // observable from outside the class though, so casting away the 11546 // const isn't dangerous. 11547 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11548 11549 OS << "Classifying expressions for: "; 11550 F.printAsOperand(OS, /*PrintType=*/false); 11551 OS << "\n"; 11552 for (Instruction &I : instructions(F)) 11553 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11554 OS << I << '\n'; 11555 OS << " --> "; 11556 const SCEV *SV = SE.getSCEV(&I); 11557 SV->print(OS); 11558 if (!isa<SCEVCouldNotCompute>(SV)) { 11559 OS << " U: "; 11560 SE.getUnsignedRange(SV).print(OS); 11561 OS << " S: "; 11562 SE.getSignedRange(SV).print(OS); 11563 } 11564 11565 const Loop *L = LI.getLoopFor(I.getParent()); 11566 11567 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11568 if (AtUse != SV) { 11569 OS << " --> "; 11570 AtUse->print(OS); 11571 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11572 OS << " U: "; 11573 SE.getUnsignedRange(AtUse).print(OS); 11574 OS << " S: "; 11575 SE.getSignedRange(AtUse).print(OS); 11576 } 11577 } 11578 11579 if (L) { 11580 OS << "\t\t" "Exits: "; 11581 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11582 if (!SE.isLoopInvariant(ExitValue, L)) { 11583 OS << "<<Unknown>>"; 11584 } else { 11585 OS << *ExitValue; 11586 } 11587 11588 bool First = true; 11589 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11590 if (First) { 11591 OS << "\t\t" "LoopDispositions: { "; 11592 First = false; 11593 } else { 11594 OS << ", "; 11595 } 11596 11597 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11598 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11599 } 11600 11601 for (auto *InnerL : depth_first(L)) { 11602 if (InnerL == L) 11603 continue; 11604 if (First) { 11605 OS << "\t\t" "LoopDispositions: { "; 11606 First = false; 11607 } else { 11608 OS << ", "; 11609 } 11610 11611 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11612 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11613 } 11614 11615 OS << " }"; 11616 } 11617 11618 OS << "\n"; 11619 } 11620 11621 OS << "Determining loop execution counts for: "; 11622 F.printAsOperand(OS, /*PrintType=*/false); 11623 OS << "\n"; 11624 for (Loop *I : LI) 11625 PrintLoopInfo(OS, &SE, I); 11626 } 11627 11628 ScalarEvolution::LoopDisposition 11629 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11630 auto &Values = LoopDispositions[S]; 11631 for (auto &V : Values) { 11632 if (V.getPointer() == L) 11633 return V.getInt(); 11634 } 11635 Values.emplace_back(L, LoopVariant); 11636 LoopDisposition D = computeLoopDisposition(S, L); 11637 auto &Values2 = LoopDispositions[S]; 11638 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11639 if (V.getPointer() == L) { 11640 V.setInt(D); 11641 break; 11642 } 11643 } 11644 return D; 11645 } 11646 11647 ScalarEvolution::LoopDisposition 11648 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11649 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11650 case scConstant: 11651 return LoopInvariant; 11652 case scTruncate: 11653 case scZeroExtend: 11654 case scSignExtend: 11655 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11656 case scAddRecExpr: { 11657 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11658 11659 // If L is the addrec's loop, it's computable. 11660 if (AR->getLoop() == L) 11661 return LoopComputable; 11662 11663 // Add recurrences are never invariant in the function-body (null loop). 11664 if (!L) 11665 return LoopVariant; 11666 11667 // Everything that is not defined at loop entry is variant. 11668 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11669 return LoopVariant; 11670 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11671 " dominate the contained loop's header?"); 11672 11673 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11674 if (AR->getLoop()->contains(L)) 11675 return LoopInvariant; 11676 11677 // This recurrence is variant w.r.t. L if any of its operands 11678 // are variant. 11679 for (auto *Op : AR->operands()) 11680 if (!isLoopInvariant(Op, L)) 11681 return LoopVariant; 11682 11683 // Otherwise it's loop-invariant. 11684 return LoopInvariant; 11685 } 11686 case scAddExpr: 11687 case scMulExpr: 11688 case scUMaxExpr: 11689 case scSMaxExpr: { 11690 bool HasVarying = false; 11691 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11692 LoopDisposition D = getLoopDisposition(Op, L); 11693 if (D == LoopVariant) 11694 return LoopVariant; 11695 if (D == LoopComputable) 11696 HasVarying = true; 11697 } 11698 return HasVarying ? LoopComputable : LoopInvariant; 11699 } 11700 case scUDivExpr: { 11701 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11702 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11703 if (LD == LoopVariant) 11704 return LoopVariant; 11705 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11706 if (RD == LoopVariant) 11707 return LoopVariant; 11708 return (LD == LoopInvariant && RD == LoopInvariant) ? 11709 LoopInvariant : LoopComputable; 11710 } 11711 case scUnknown: 11712 // All non-instruction values are loop invariant. All instructions are loop 11713 // invariant if they are not contained in the specified loop. 11714 // Instructions are never considered invariant in the function body 11715 // (null loop) because they are defined within the "loop". 11716 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11717 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11718 return LoopInvariant; 11719 case scCouldNotCompute: 11720 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11721 } 11722 llvm_unreachable("Unknown SCEV kind!"); 11723 } 11724 11725 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11726 return getLoopDisposition(S, L) == LoopInvariant; 11727 } 11728 11729 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11730 return getLoopDisposition(S, L) == LoopComputable; 11731 } 11732 11733 ScalarEvolution::BlockDisposition 11734 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11735 auto &Values = BlockDispositions[S]; 11736 for (auto &V : Values) { 11737 if (V.getPointer() == BB) 11738 return V.getInt(); 11739 } 11740 Values.emplace_back(BB, DoesNotDominateBlock); 11741 BlockDisposition D = computeBlockDisposition(S, BB); 11742 auto &Values2 = BlockDispositions[S]; 11743 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11744 if (V.getPointer() == BB) { 11745 V.setInt(D); 11746 break; 11747 } 11748 } 11749 return D; 11750 } 11751 11752 ScalarEvolution::BlockDisposition 11753 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11754 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11755 case scConstant: 11756 return ProperlyDominatesBlock; 11757 case scTruncate: 11758 case scZeroExtend: 11759 case scSignExtend: 11760 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11761 case scAddRecExpr: { 11762 // This uses a "dominates" query instead of "properly dominates" query 11763 // to test for proper dominance too, because the instruction which 11764 // produces the addrec's value is a PHI, and a PHI effectively properly 11765 // dominates its entire containing block. 11766 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11767 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11768 return DoesNotDominateBlock; 11769 11770 // Fall through into SCEVNAryExpr handling. 11771 LLVM_FALLTHROUGH; 11772 } 11773 case scAddExpr: 11774 case scMulExpr: 11775 case scUMaxExpr: 11776 case scSMaxExpr: { 11777 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11778 bool Proper = true; 11779 for (const SCEV *NAryOp : NAry->operands()) { 11780 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11781 if (D == DoesNotDominateBlock) 11782 return DoesNotDominateBlock; 11783 if (D == DominatesBlock) 11784 Proper = false; 11785 } 11786 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11787 } 11788 case scUDivExpr: { 11789 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11790 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11791 BlockDisposition LD = getBlockDisposition(LHS, BB); 11792 if (LD == DoesNotDominateBlock) 11793 return DoesNotDominateBlock; 11794 BlockDisposition RD = getBlockDisposition(RHS, BB); 11795 if (RD == DoesNotDominateBlock) 11796 return DoesNotDominateBlock; 11797 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11798 ProperlyDominatesBlock : DominatesBlock; 11799 } 11800 case scUnknown: 11801 if (Instruction *I = 11802 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11803 if (I->getParent() == BB) 11804 return DominatesBlock; 11805 if (DT.properlyDominates(I->getParent(), BB)) 11806 return ProperlyDominatesBlock; 11807 return DoesNotDominateBlock; 11808 } 11809 return ProperlyDominatesBlock; 11810 case scCouldNotCompute: 11811 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11812 } 11813 llvm_unreachable("Unknown SCEV kind!"); 11814 } 11815 11816 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11817 return getBlockDisposition(S, BB) >= DominatesBlock; 11818 } 11819 11820 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11821 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11822 } 11823 11824 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11825 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11826 } 11827 11828 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11829 auto IsS = [&](const SCEV *X) { return S == X; }; 11830 auto ContainsS = [&](const SCEV *X) { 11831 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11832 }; 11833 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11834 } 11835 11836 void 11837 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11838 ValuesAtScopes.erase(S); 11839 LoopDispositions.erase(S); 11840 BlockDispositions.erase(S); 11841 UnsignedRanges.erase(S); 11842 SignedRanges.erase(S); 11843 ExprValueMap.erase(S); 11844 HasRecMap.erase(S); 11845 MinTrailingZerosCache.erase(S); 11846 11847 for (auto I = PredicatedSCEVRewrites.begin(); 11848 I != PredicatedSCEVRewrites.end();) { 11849 std::pair<const SCEV *, const Loop *> Entry = I->first; 11850 if (Entry.first == S) 11851 PredicatedSCEVRewrites.erase(I++); 11852 else 11853 ++I; 11854 } 11855 11856 auto RemoveSCEVFromBackedgeMap = 11857 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11858 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11859 BackedgeTakenInfo &BEInfo = I->second; 11860 if (BEInfo.hasOperand(S, this)) { 11861 BEInfo.clear(); 11862 Map.erase(I++); 11863 } else 11864 ++I; 11865 } 11866 }; 11867 11868 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11869 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11870 } 11871 11872 void 11873 ScalarEvolution::getUsedLoops(const SCEV *S, 11874 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11875 struct FindUsedLoops { 11876 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11877 : LoopsUsed(LoopsUsed) {} 11878 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11879 bool follow(const SCEV *S) { 11880 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11881 LoopsUsed.insert(AR->getLoop()); 11882 return true; 11883 } 11884 11885 bool isDone() const { return false; } 11886 }; 11887 11888 FindUsedLoops F(LoopsUsed); 11889 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11890 } 11891 11892 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11893 SmallPtrSet<const Loop *, 8> LoopsUsed; 11894 getUsedLoops(S, LoopsUsed); 11895 for (auto *L : LoopsUsed) 11896 LoopUsers[L].push_back(S); 11897 } 11898 11899 void ScalarEvolution::verify() const { 11900 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11901 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11902 11903 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11904 11905 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11906 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11907 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11908 11909 const SCEV *visitConstant(const SCEVConstant *Constant) { 11910 return SE.getConstant(Constant->getAPInt()); 11911 } 11912 11913 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11914 return SE.getUnknown(Expr->getValue()); 11915 } 11916 11917 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11918 return SE.getCouldNotCompute(); 11919 } 11920 }; 11921 11922 SCEVMapper SCM(SE2); 11923 11924 while (!LoopStack.empty()) { 11925 auto *L = LoopStack.pop_back_val(); 11926 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11927 11928 auto *CurBECount = SCM.visit( 11929 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11930 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11931 11932 if (CurBECount == SE2.getCouldNotCompute() || 11933 NewBECount == SE2.getCouldNotCompute()) { 11934 // NB! This situation is legal, but is very suspicious -- whatever pass 11935 // change the loop to make a trip count go from could not compute to 11936 // computable or vice-versa *should have* invalidated SCEV. However, we 11937 // choose not to assert here (for now) since we don't want false 11938 // positives. 11939 continue; 11940 } 11941 11942 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11943 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11944 // not propagate undef aggressively). This means we can (and do) fail 11945 // verification in cases where a transform makes the trip count of a loop 11946 // go from "undef" to "undef+1" (say). The transform is fine, since in 11947 // both cases the loop iterates "undef" times, but SCEV thinks we 11948 // increased the trip count of the loop by 1 incorrectly. 11949 continue; 11950 } 11951 11952 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11953 SE.getTypeSizeInBits(NewBECount->getType())) 11954 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11955 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11956 SE.getTypeSizeInBits(NewBECount->getType())) 11957 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11958 11959 auto *ConstantDelta = 11960 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 11961 11962 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 11963 dbgs() << "Trip Count Changed!\n"; 11964 dbgs() << "Old: " << *CurBECount << "\n"; 11965 dbgs() << "New: " << *NewBECount << "\n"; 11966 dbgs() << "Delta: " << *ConstantDelta << "\n"; 11967 std::abort(); 11968 } 11969 } 11970 } 11971 11972 bool ScalarEvolution::invalidate( 11973 Function &F, const PreservedAnalyses &PA, 11974 FunctionAnalysisManager::Invalidator &Inv) { 11975 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11976 // of its dependencies is invalidated. 11977 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11978 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11979 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11980 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11981 Inv.invalidate<LoopAnalysis>(F, PA); 11982 } 11983 11984 AnalysisKey ScalarEvolutionAnalysis::Key; 11985 11986 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11987 FunctionAnalysisManager &AM) { 11988 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11989 AM.getResult<AssumptionAnalysis>(F), 11990 AM.getResult<DominatorTreeAnalysis>(F), 11991 AM.getResult<LoopAnalysis>(F)); 11992 } 11993 11994 PreservedAnalyses 11995 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11996 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11997 return PreservedAnalyses::all(); 11998 } 11999 12000 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12001 "Scalar Evolution Analysis", false, true) 12002 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12003 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12004 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12005 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12006 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12007 "Scalar Evolution Analysis", false, true) 12008 12009 char ScalarEvolutionWrapperPass::ID = 0; 12010 12011 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12012 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12013 } 12014 12015 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12016 SE.reset(new ScalarEvolution( 12017 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 12018 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12019 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12020 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12021 return false; 12022 } 12023 12024 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12025 12026 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12027 SE->print(OS); 12028 } 12029 12030 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12031 if (!VerifySCEV) 12032 return; 12033 12034 SE->verify(); 12035 } 12036 12037 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12038 AU.setPreservesAll(); 12039 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12040 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12041 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12042 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12043 } 12044 12045 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12046 const SCEV *RHS) { 12047 FoldingSetNodeID ID; 12048 assert(LHS->getType() == RHS->getType() && 12049 "Type mismatch between LHS and RHS"); 12050 // Unique this node based on the arguments 12051 ID.AddInteger(SCEVPredicate::P_Equal); 12052 ID.AddPointer(LHS); 12053 ID.AddPointer(RHS); 12054 void *IP = nullptr; 12055 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12056 return S; 12057 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12058 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12059 UniquePreds.InsertNode(Eq, IP); 12060 return Eq; 12061 } 12062 12063 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12064 const SCEVAddRecExpr *AR, 12065 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12066 FoldingSetNodeID ID; 12067 // Unique this node based on the arguments 12068 ID.AddInteger(SCEVPredicate::P_Wrap); 12069 ID.AddPointer(AR); 12070 ID.AddInteger(AddedFlags); 12071 void *IP = nullptr; 12072 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12073 return S; 12074 auto *OF = new (SCEVAllocator) 12075 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12076 UniquePreds.InsertNode(OF, IP); 12077 return OF; 12078 } 12079 12080 namespace { 12081 12082 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12083 public: 12084 12085 /// Rewrites \p S in the context of a loop L and the SCEV predication 12086 /// infrastructure. 12087 /// 12088 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12089 /// equivalences present in \p Pred. 12090 /// 12091 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12092 /// \p NewPreds such that the result will be an AddRecExpr. 12093 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12094 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12095 SCEVUnionPredicate *Pred) { 12096 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12097 return Rewriter.visit(S); 12098 } 12099 12100 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12101 if (Pred) { 12102 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12103 for (auto *Pred : ExprPreds) 12104 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12105 if (IPred->getLHS() == Expr) 12106 return IPred->getRHS(); 12107 } 12108 return convertToAddRecWithPreds(Expr); 12109 } 12110 12111 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12112 const SCEV *Operand = visit(Expr->getOperand()); 12113 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12114 if (AR && AR->getLoop() == L && AR->isAffine()) { 12115 // This couldn't be folded because the operand didn't have the nuw 12116 // flag. Add the nusw flag as an assumption that we could make. 12117 const SCEV *Step = AR->getStepRecurrence(SE); 12118 Type *Ty = Expr->getType(); 12119 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12120 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12121 SE.getSignExtendExpr(Step, Ty), L, 12122 AR->getNoWrapFlags()); 12123 } 12124 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12125 } 12126 12127 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12128 const SCEV *Operand = visit(Expr->getOperand()); 12129 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12130 if (AR && AR->getLoop() == L && AR->isAffine()) { 12131 // This couldn't be folded because the operand didn't have the nsw 12132 // flag. Add the nssw flag as an assumption that we could make. 12133 const SCEV *Step = AR->getStepRecurrence(SE); 12134 Type *Ty = Expr->getType(); 12135 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12136 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12137 SE.getSignExtendExpr(Step, Ty), L, 12138 AR->getNoWrapFlags()); 12139 } 12140 return SE.getSignExtendExpr(Operand, Expr->getType()); 12141 } 12142 12143 private: 12144 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12145 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12146 SCEVUnionPredicate *Pred) 12147 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12148 12149 bool addOverflowAssumption(const SCEVPredicate *P) { 12150 if (!NewPreds) { 12151 // Check if we've already made this assumption. 12152 return Pred && Pred->implies(P); 12153 } 12154 NewPreds->insert(P); 12155 return true; 12156 } 12157 12158 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12159 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12160 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12161 return addOverflowAssumption(A); 12162 } 12163 12164 // If \p Expr represents a PHINode, we try to see if it can be represented 12165 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12166 // to add this predicate as a runtime overflow check, we return the AddRec. 12167 // If \p Expr does not meet these conditions (is not a PHI node, or we 12168 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12169 // return \p Expr. 12170 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12171 if (!isa<PHINode>(Expr->getValue())) 12172 return Expr; 12173 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12174 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12175 if (!PredicatedRewrite) 12176 return Expr; 12177 for (auto *P : PredicatedRewrite->second){ 12178 // Wrap predicates from outer loops are not supported. 12179 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12180 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12181 if (L != AR->getLoop()) 12182 return Expr; 12183 } 12184 if (!addOverflowAssumption(P)) 12185 return Expr; 12186 } 12187 return PredicatedRewrite->first; 12188 } 12189 12190 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12191 SCEVUnionPredicate *Pred; 12192 const Loop *L; 12193 }; 12194 12195 } // end anonymous namespace 12196 12197 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12198 SCEVUnionPredicate &Preds) { 12199 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12200 } 12201 12202 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12203 const SCEV *S, const Loop *L, 12204 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12205 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12206 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12207 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12208 12209 if (!AddRec) 12210 return nullptr; 12211 12212 // Since the transformation was successful, we can now transfer the SCEV 12213 // predicates. 12214 for (auto *P : TransformPreds) 12215 Preds.insert(P); 12216 12217 return AddRec; 12218 } 12219 12220 /// SCEV predicates 12221 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12222 SCEVPredicateKind Kind) 12223 : FastID(ID), Kind(Kind) {} 12224 12225 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12226 const SCEV *LHS, const SCEV *RHS) 12227 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12228 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12229 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12230 } 12231 12232 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12233 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12234 12235 if (!Op) 12236 return false; 12237 12238 return Op->LHS == LHS && Op->RHS == RHS; 12239 } 12240 12241 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12242 12243 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12244 12245 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12246 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12247 } 12248 12249 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12250 const SCEVAddRecExpr *AR, 12251 IncrementWrapFlags Flags) 12252 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12253 12254 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12255 12256 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12257 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12258 12259 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12260 } 12261 12262 bool SCEVWrapPredicate::isAlwaysTrue() const { 12263 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12264 IncrementWrapFlags IFlags = Flags; 12265 12266 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12267 IFlags = clearFlags(IFlags, IncrementNSSW); 12268 12269 return IFlags == IncrementAnyWrap; 12270 } 12271 12272 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12273 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12274 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12275 OS << "<nusw>"; 12276 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12277 OS << "<nssw>"; 12278 OS << "\n"; 12279 } 12280 12281 SCEVWrapPredicate::IncrementWrapFlags 12282 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12283 ScalarEvolution &SE) { 12284 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12285 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12286 12287 // We can safely transfer the NSW flag as NSSW. 12288 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12289 ImpliedFlags = IncrementNSSW; 12290 12291 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12292 // If the increment is positive, the SCEV NUW flag will also imply the 12293 // WrapPredicate NUSW flag. 12294 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12295 if (Step->getValue()->getValue().isNonNegative()) 12296 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12297 } 12298 12299 return ImpliedFlags; 12300 } 12301 12302 /// Union predicates don't get cached so create a dummy set ID for it. 12303 SCEVUnionPredicate::SCEVUnionPredicate() 12304 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12305 12306 bool SCEVUnionPredicate::isAlwaysTrue() const { 12307 return all_of(Preds, 12308 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12309 } 12310 12311 ArrayRef<const SCEVPredicate *> 12312 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12313 auto I = SCEVToPreds.find(Expr); 12314 if (I == SCEVToPreds.end()) 12315 return ArrayRef<const SCEVPredicate *>(); 12316 return I->second; 12317 } 12318 12319 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12320 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12321 return all_of(Set->Preds, 12322 [this](const SCEVPredicate *I) { return this->implies(I); }); 12323 12324 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12325 if (ScevPredsIt == SCEVToPreds.end()) 12326 return false; 12327 auto &SCEVPreds = ScevPredsIt->second; 12328 12329 return any_of(SCEVPreds, 12330 [N](const SCEVPredicate *I) { return I->implies(N); }); 12331 } 12332 12333 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12334 12335 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12336 for (auto Pred : Preds) 12337 Pred->print(OS, Depth); 12338 } 12339 12340 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12341 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12342 for (auto Pred : Set->Preds) 12343 add(Pred); 12344 return; 12345 } 12346 12347 if (implies(N)) 12348 return; 12349 12350 const SCEV *Key = N->getExpr(); 12351 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12352 " associated expression!"); 12353 12354 SCEVToPreds[Key].push_back(N); 12355 Preds.push_back(N); 12356 } 12357 12358 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12359 Loop &L) 12360 : SE(SE), L(L) {} 12361 12362 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12363 const SCEV *Expr = SE.getSCEV(V); 12364 RewriteEntry &Entry = RewriteMap[Expr]; 12365 12366 // If we already have an entry and the version matches, return it. 12367 if (Entry.second && Generation == Entry.first) 12368 return Entry.second; 12369 12370 // We found an entry but it's stale. Rewrite the stale entry 12371 // according to the current predicate. 12372 if (Entry.second) 12373 Expr = Entry.second; 12374 12375 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12376 Entry = {Generation, NewSCEV}; 12377 12378 return NewSCEV; 12379 } 12380 12381 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12382 if (!BackedgeCount) { 12383 SCEVUnionPredicate BackedgePred; 12384 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12385 addPredicate(BackedgePred); 12386 } 12387 return BackedgeCount; 12388 } 12389 12390 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12391 if (Preds.implies(&Pred)) 12392 return; 12393 Preds.add(&Pred); 12394 updateGeneration(); 12395 } 12396 12397 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12398 return Preds; 12399 } 12400 12401 void PredicatedScalarEvolution::updateGeneration() { 12402 // If the generation number wrapped recompute everything. 12403 if (++Generation == 0) { 12404 for (auto &II : RewriteMap) { 12405 const SCEV *Rewritten = II.second.second; 12406 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12407 } 12408 } 12409 } 12410 12411 void PredicatedScalarEvolution::setNoOverflow( 12412 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12413 const SCEV *Expr = getSCEV(V); 12414 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12415 12416 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12417 12418 // Clear the statically implied flags. 12419 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12420 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12421 12422 auto II = FlagsMap.insert({V, Flags}); 12423 if (!II.second) 12424 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12425 } 12426 12427 bool PredicatedScalarEvolution::hasNoOverflow( 12428 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12429 const SCEV *Expr = getSCEV(V); 12430 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12431 12432 Flags = SCEVWrapPredicate::clearFlags( 12433 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12434 12435 auto II = FlagsMap.find(V); 12436 12437 if (II != FlagsMap.end()) 12438 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12439 12440 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12441 } 12442 12443 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12444 const SCEV *Expr = this->getSCEV(V); 12445 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12446 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12447 12448 if (!New) 12449 return nullptr; 12450 12451 for (auto *P : NewPreds) 12452 Preds.add(P); 12453 12454 updateGeneration(); 12455 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12456 return New; 12457 } 12458 12459 PredicatedScalarEvolution::PredicatedScalarEvolution( 12460 const PredicatedScalarEvolution &Init) 12461 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12462 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12463 for (const auto &I : Init.FlagsMap) 12464 FlagsMap.insert(I); 12465 } 12466 12467 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12468 // For each block. 12469 for (auto *BB : L.getBlocks()) 12470 for (auto &I : *BB) { 12471 if (!SE.isSCEVable(I.getType())) 12472 continue; 12473 12474 auto *Expr = SE.getSCEV(&I); 12475 auto II = RewriteMap.find(Expr); 12476 12477 if (II == RewriteMap.end()) 12478 continue; 12479 12480 // Don't print things that are not interesting. 12481 if (II->second.second == Expr) 12482 continue; 12483 12484 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12485 OS.indent(Depth + 2) << *Expr << "\n"; 12486 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12487 } 12488 } 12489 12490 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12491 // arbitrary expressions. 12492 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12493 // 4, A / B becomes X / 8). 12494 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12495 const SCEV *&RHS) { 12496 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12497 if (Add == nullptr || Add->getNumOperands() != 2) 12498 return false; 12499 12500 const SCEV *A = Add->getOperand(1); 12501 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12502 12503 if (Mul == nullptr) 12504 return false; 12505 12506 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12507 // (SomeExpr + (-(SomeExpr / B) * B)). 12508 if (Expr == getURemExpr(A, B)) { 12509 LHS = A; 12510 RHS = B; 12511 return true; 12512 } 12513 return false; 12514 }; 12515 12516 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12517 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12518 return MatchURemWithDivisor(Mul->getOperand(1)) || 12519 MatchURemWithDivisor(Mul->getOperand(2)); 12520 12521 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12522 if (Mul->getNumOperands() == 2) 12523 return MatchURemWithDivisor(Mul->getOperand(1)) || 12524 MatchURemWithDivisor(Mul->getOperand(0)) || 12525 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12526 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12527 return false; 12528 } 12529