1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the implementation of the scalar evolution analysis 11 // engine, which is used primarily to analyze expressions involving induction 12 // variables in loops. 13 // 14 // There are several aspects to this library. First is the representation of 15 // scalar expressions, which are represented as subclasses of the SCEV class. 16 // These classes are used to represent certain types of subexpressions that we 17 // can handle. We only create one SCEV of a particular shape, so 18 // pointer-comparisons for equality are legal. 19 // 20 // One important aspect of the SCEV objects is that they are never cyclic, even 21 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 23 // recurrence) then we represent it directly as a recurrence node, otherwise we 24 // represent it as a SCEVUnknown node. 25 // 26 // In addition to being able to represent expressions of various types, we also 27 // have folders that are used to build the *canonical* representation for a 28 // particular expression. These folders are capable of using a variety of 29 // rewrite rules to simplify the expressions. 30 // 31 // Once the folders are defined, we can implement the more interesting 32 // higher-level code, such as the code that recognizes PHI nodes of various 33 // types, computes the execution count of a loop, etc. 34 // 35 // TODO: We should use these routines and value representations to implement 36 // dependence analysis! 37 // 38 //===----------------------------------------------------------------------===// 39 // 40 // There are several good references for the techniques used in this analysis. 41 // 42 // Chains of recurrences -- a method to expedite the evaluation 43 // of closed-form functions 44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 45 // 46 // On computational properties of chains of recurrences 47 // Eugene V. Zima 48 // 49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 50 // Robert A. van Engelen 51 // 52 // Efficient Symbolic Analysis for Optimizing Compilers 53 // Robert A. van Engelen 54 // 55 // Using the chains of recurrences algebra for data dependence testing and 56 // induction variable substitution 57 // MS Thesis, Johnie Birch 58 // 59 //===----------------------------------------------------------------------===// 60 61 #include "llvm/Analysis/ScalarEvolution.h" 62 #include "llvm/ADT/Optional.h" 63 #include "llvm/ADT/STLExtras.h" 64 #include "llvm/ADT/ScopeExit.h" 65 #include "llvm/ADT/Sequence.h" 66 #include "llvm/ADT/SmallPtrSet.h" 67 #include "llvm/ADT/Statistic.h" 68 #include "llvm/Analysis/AssumptionCache.h" 69 #include "llvm/Analysis/ConstantFolding.h" 70 #include "llvm/Analysis/InstructionSimplify.h" 71 #include "llvm/Analysis/LoopInfo.h" 72 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 73 #include "llvm/Analysis/TargetLibraryInfo.h" 74 #include "llvm/Analysis/ValueTracking.h" 75 #include "llvm/IR/ConstantRange.h" 76 #include "llvm/IR/Constants.h" 77 #include "llvm/IR/DataLayout.h" 78 #include "llvm/IR/DerivedTypes.h" 79 #include "llvm/IR/Dominators.h" 80 #include "llvm/IR/GetElementPtrTypeIterator.h" 81 #include "llvm/IR/GlobalAlias.h" 82 #include "llvm/IR/GlobalVariable.h" 83 #include "llvm/IR/InstIterator.h" 84 #include "llvm/IR/Instructions.h" 85 #include "llvm/IR/LLVMContext.h" 86 #include "llvm/IR/Metadata.h" 87 #include "llvm/IR/Operator.h" 88 #include "llvm/IR/PatternMatch.h" 89 #include "llvm/Support/CommandLine.h" 90 #include "llvm/Support/Debug.h" 91 #include "llvm/Support/ErrorHandling.h" 92 #include "llvm/Support/MathExtras.h" 93 #include "llvm/Support/raw_ostream.h" 94 #include "llvm/Support/SaveAndRestore.h" 95 #include <algorithm> 96 using namespace llvm; 97 98 #define DEBUG_TYPE "scalar-evolution" 99 100 STATISTIC(NumArrayLenItCounts, 101 "Number of trip counts computed with array length"); 102 STATISTIC(NumTripCountsComputed, 103 "Number of loops with predictable loop counts"); 104 STATISTIC(NumTripCountsNotComputed, 105 "Number of loops without predictable loop counts"); 106 STATISTIC(NumBruteForceTripCountsComputed, 107 "Number of loops with trip counts computed by force"); 108 109 static cl::opt<unsigned> 110 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 111 cl::desc("Maximum number of iterations SCEV will " 112 "symbolically execute a constant " 113 "derived loop"), 114 cl::init(100)); 115 116 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 117 static cl::opt<bool> 118 VerifySCEV("verify-scev", 119 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 120 static cl::opt<bool> 121 VerifySCEVMap("verify-scev-maps", 122 cl::desc("Verify no dangling value in ScalarEvolution's " 123 "ExprValueMap (slow)")); 124 125 static cl::opt<unsigned> MulOpsInlineThreshold( 126 "scev-mulops-inline-threshold", cl::Hidden, 127 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 128 cl::init(1000)); 129 130 static cl::opt<unsigned> 131 MaxCompareDepth("scalar-evolution-max-compare-depth", cl::Hidden, 132 cl::desc("Maximum depth of recursive compare complexity"), 133 cl::init(32)); 134 135 //===----------------------------------------------------------------------===// 136 // SCEV class definitions 137 //===----------------------------------------------------------------------===// 138 139 //===----------------------------------------------------------------------===// 140 // Implementation of the SCEV class. 141 // 142 143 LLVM_DUMP_METHOD 144 void SCEV::dump() const { 145 print(dbgs()); 146 dbgs() << '\n'; 147 } 148 149 void SCEV::print(raw_ostream &OS) const { 150 switch (static_cast<SCEVTypes>(getSCEVType())) { 151 case scConstant: 152 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 153 return; 154 case scTruncate: { 155 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 156 const SCEV *Op = Trunc->getOperand(); 157 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 158 << *Trunc->getType() << ")"; 159 return; 160 } 161 case scZeroExtend: { 162 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 163 const SCEV *Op = ZExt->getOperand(); 164 OS << "(zext " << *Op->getType() << " " << *Op << " to " 165 << *ZExt->getType() << ")"; 166 return; 167 } 168 case scSignExtend: { 169 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 170 const SCEV *Op = SExt->getOperand(); 171 OS << "(sext " << *Op->getType() << " " << *Op << " to " 172 << *SExt->getType() << ")"; 173 return; 174 } 175 case scAddRecExpr: { 176 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 177 OS << "{" << *AR->getOperand(0); 178 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 179 OS << ",+," << *AR->getOperand(i); 180 OS << "}<"; 181 if (AR->hasNoUnsignedWrap()) 182 OS << "nuw><"; 183 if (AR->hasNoSignedWrap()) 184 OS << "nsw><"; 185 if (AR->hasNoSelfWrap() && 186 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 187 OS << "nw><"; 188 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 189 OS << ">"; 190 return; 191 } 192 case scAddExpr: 193 case scMulExpr: 194 case scUMaxExpr: 195 case scSMaxExpr: { 196 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 197 const char *OpStr = nullptr; 198 switch (NAry->getSCEVType()) { 199 case scAddExpr: OpStr = " + "; break; 200 case scMulExpr: OpStr = " * "; break; 201 case scUMaxExpr: OpStr = " umax "; break; 202 case scSMaxExpr: OpStr = " smax "; break; 203 } 204 OS << "("; 205 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 206 I != E; ++I) { 207 OS << **I; 208 if (std::next(I) != E) 209 OS << OpStr; 210 } 211 OS << ")"; 212 switch (NAry->getSCEVType()) { 213 case scAddExpr: 214 case scMulExpr: 215 if (NAry->hasNoUnsignedWrap()) 216 OS << "<nuw>"; 217 if (NAry->hasNoSignedWrap()) 218 OS << "<nsw>"; 219 } 220 return; 221 } 222 case scUDivExpr: { 223 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 224 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 225 return; 226 } 227 case scUnknown: { 228 const SCEVUnknown *U = cast<SCEVUnknown>(this); 229 Type *AllocTy; 230 if (U->isSizeOf(AllocTy)) { 231 OS << "sizeof(" << *AllocTy << ")"; 232 return; 233 } 234 if (U->isAlignOf(AllocTy)) { 235 OS << "alignof(" << *AllocTy << ")"; 236 return; 237 } 238 239 Type *CTy; 240 Constant *FieldNo; 241 if (U->isOffsetOf(CTy, FieldNo)) { 242 OS << "offsetof(" << *CTy << ", "; 243 FieldNo->printAsOperand(OS, false); 244 OS << ")"; 245 return; 246 } 247 248 // Otherwise just print it normally. 249 U->getValue()->printAsOperand(OS, false); 250 return; 251 } 252 case scCouldNotCompute: 253 OS << "***COULDNOTCOMPUTE***"; 254 return; 255 } 256 llvm_unreachable("Unknown SCEV kind!"); 257 } 258 259 Type *SCEV::getType() const { 260 switch (static_cast<SCEVTypes>(getSCEVType())) { 261 case scConstant: 262 return cast<SCEVConstant>(this)->getType(); 263 case scTruncate: 264 case scZeroExtend: 265 case scSignExtend: 266 return cast<SCEVCastExpr>(this)->getType(); 267 case scAddRecExpr: 268 case scMulExpr: 269 case scUMaxExpr: 270 case scSMaxExpr: 271 return cast<SCEVNAryExpr>(this)->getType(); 272 case scAddExpr: 273 return cast<SCEVAddExpr>(this)->getType(); 274 case scUDivExpr: 275 return cast<SCEVUDivExpr>(this)->getType(); 276 case scUnknown: 277 return cast<SCEVUnknown>(this)->getType(); 278 case scCouldNotCompute: 279 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 280 } 281 llvm_unreachable("Unknown SCEV kind!"); 282 } 283 284 bool SCEV::isZero() const { 285 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 286 return SC->getValue()->isZero(); 287 return false; 288 } 289 290 bool SCEV::isOne() const { 291 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 292 return SC->getValue()->isOne(); 293 return false; 294 } 295 296 bool SCEV::isAllOnesValue() const { 297 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 298 return SC->getValue()->isAllOnesValue(); 299 return false; 300 } 301 302 bool SCEV::isNonConstantNegative() const { 303 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 304 if (!Mul) return false; 305 306 // If there is a constant factor, it will be first. 307 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 308 if (!SC) return false; 309 310 // Return true if the value is negative, this matches things like (-42 * V). 311 return SC->getAPInt().isNegative(); 312 } 313 314 SCEVCouldNotCompute::SCEVCouldNotCompute() : 315 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 316 317 bool SCEVCouldNotCompute::classof(const SCEV *S) { 318 return S->getSCEVType() == scCouldNotCompute; 319 } 320 321 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 322 FoldingSetNodeID ID; 323 ID.AddInteger(scConstant); 324 ID.AddPointer(V); 325 void *IP = nullptr; 326 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 327 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 328 UniqueSCEVs.InsertNode(S, IP); 329 return S; 330 } 331 332 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 333 return getConstant(ConstantInt::get(getContext(), Val)); 334 } 335 336 const SCEV * 337 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 338 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 339 return getConstant(ConstantInt::get(ITy, V, isSigned)); 340 } 341 342 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 343 unsigned SCEVTy, const SCEV *op, Type *ty) 344 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 345 346 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 347 const SCEV *op, Type *ty) 348 : SCEVCastExpr(ID, scTruncate, op, ty) { 349 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 350 (Ty->isIntegerTy() || Ty->isPointerTy()) && 351 "Cannot truncate non-integer value!"); 352 } 353 354 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 355 const SCEV *op, Type *ty) 356 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 357 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 358 (Ty->isIntegerTy() || Ty->isPointerTy()) && 359 "Cannot zero extend non-integer value!"); 360 } 361 362 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 363 const SCEV *op, Type *ty) 364 : SCEVCastExpr(ID, scSignExtend, op, ty) { 365 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 366 (Ty->isIntegerTy() || Ty->isPointerTy()) && 367 "Cannot sign extend non-integer value!"); 368 } 369 370 void SCEVUnknown::deleted() { 371 // Clear this SCEVUnknown from various maps. 372 SE->forgetMemoizedResults(this); 373 374 // Remove this SCEVUnknown from the uniquing map. 375 SE->UniqueSCEVs.RemoveNode(this); 376 377 // Release the value. 378 setValPtr(nullptr); 379 } 380 381 void SCEVUnknown::allUsesReplacedWith(Value *New) { 382 // Clear this SCEVUnknown from various maps. 383 SE->forgetMemoizedResults(this); 384 385 // Remove this SCEVUnknown from the uniquing map. 386 SE->UniqueSCEVs.RemoveNode(this); 387 388 // Update this SCEVUnknown to point to the new value. This is needed 389 // because there may still be outstanding SCEVs which still point to 390 // this SCEVUnknown. 391 setValPtr(New); 392 } 393 394 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 395 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 396 if (VCE->getOpcode() == Instruction::PtrToInt) 397 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 398 if (CE->getOpcode() == Instruction::GetElementPtr && 399 CE->getOperand(0)->isNullValue() && 400 CE->getNumOperands() == 2) 401 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 402 if (CI->isOne()) { 403 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 404 ->getElementType(); 405 return true; 406 } 407 408 return false; 409 } 410 411 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 412 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 413 if (VCE->getOpcode() == Instruction::PtrToInt) 414 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 415 if (CE->getOpcode() == Instruction::GetElementPtr && 416 CE->getOperand(0)->isNullValue()) { 417 Type *Ty = 418 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 419 if (StructType *STy = dyn_cast<StructType>(Ty)) 420 if (!STy->isPacked() && 421 CE->getNumOperands() == 3 && 422 CE->getOperand(1)->isNullValue()) { 423 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 424 if (CI->isOne() && 425 STy->getNumElements() == 2 && 426 STy->getElementType(0)->isIntegerTy(1)) { 427 AllocTy = STy->getElementType(1); 428 return true; 429 } 430 } 431 } 432 433 return false; 434 } 435 436 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 437 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 438 if (VCE->getOpcode() == Instruction::PtrToInt) 439 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 440 if (CE->getOpcode() == Instruction::GetElementPtr && 441 CE->getNumOperands() == 3 && 442 CE->getOperand(0)->isNullValue() && 443 CE->getOperand(1)->isNullValue()) { 444 Type *Ty = 445 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 446 // Ignore vector types here so that ScalarEvolutionExpander doesn't 447 // emit getelementptrs that index into vectors. 448 if (Ty->isStructTy() || Ty->isArrayTy()) { 449 CTy = Ty; 450 FieldNo = CE->getOperand(2); 451 return true; 452 } 453 } 454 455 return false; 456 } 457 458 //===----------------------------------------------------------------------===// 459 // SCEV Utilities 460 //===----------------------------------------------------------------------===// 461 462 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 463 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 464 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 465 /// have been previously deemed to be "equally complex" by this routine. It is 466 /// intended to avoid exponential time complexity in cases like: 467 /// 468 /// %a = f(%x, %y) 469 /// %b = f(%a, %a) 470 /// %c = f(%b, %b) 471 /// 472 /// %d = f(%x, %y) 473 /// %e = f(%d, %d) 474 /// %f = f(%e, %e) 475 /// 476 /// CompareValueComplexity(%f, %c) 477 /// 478 /// Since we do not continue running this routine on expression trees once we 479 /// have seen unequal values, there is no need to track them in the cache. 480 static int 481 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache, 482 const LoopInfo *const LI, Value *LV, Value *RV, 483 unsigned Depth) { 484 if (Depth > MaxCompareDepth || EqCache.count({LV, RV})) 485 return 0; 486 487 // Order pointer values after integer values. This helps SCEVExpander form 488 // GEPs. 489 bool LIsPointer = LV->getType()->isPointerTy(), 490 RIsPointer = RV->getType()->isPointerTy(); 491 if (LIsPointer != RIsPointer) 492 return (int)LIsPointer - (int)RIsPointer; 493 494 // Compare getValueID values. 495 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 496 if (LID != RID) 497 return (int)LID - (int)RID; 498 499 // Sort arguments by their position. 500 if (const auto *LA = dyn_cast<Argument>(LV)) { 501 const auto *RA = cast<Argument>(RV); 502 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 503 return (int)LArgNo - (int)RArgNo; 504 } 505 506 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 507 const auto *RGV = cast<GlobalValue>(RV); 508 509 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 510 auto LT = GV->getLinkage(); 511 return !(GlobalValue::isPrivateLinkage(LT) || 512 GlobalValue::isInternalLinkage(LT)); 513 }; 514 515 // Use the names to distinguish the two values, but only if the 516 // names are semantically important. 517 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 518 return LGV->getName().compare(RGV->getName()); 519 } 520 521 // For instructions, compare their loop depth, and their operand count. This 522 // is pretty loose. 523 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 524 const auto *RInst = cast<Instruction>(RV); 525 526 // Compare loop depths. 527 const BasicBlock *LParent = LInst->getParent(), 528 *RParent = RInst->getParent(); 529 if (LParent != RParent) { 530 unsigned LDepth = LI->getLoopDepth(LParent), 531 RDepth = LI->getLoopDepth(RParent); 532 if (LDepth != RDepth) 533 return (int)LDepth - (int)RDepth; 534 } 535 536 // Compare the number of operands. 537 unsigned LNumOps = LInst->getNumOperands(), 538 RNumOps = RInst->getNumOperands(); 539 if (LNumOps != RNumOps) 540 return (int)LNumOps - (int)RNumOps; 541 542 for (unsigned Idx : seq(0u, LNumOps)) { 543 int Result = 544 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx), 545 RInst->getOperand(Idx), Depth + 1); 546 if (Result != 0) 547 return Result; 548 } 549 } 550 551 EqCache.insert({LV, RV}); 552 return 0; 553 } 554 555 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 556 // than RHS, respectively. A three-way result allows recursive comparisons to be 557 // more efficient. 558 static int CompareSCEVComplexity( 559 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV, 560 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 561 unsigned Depth = 0) { 562 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 563 if (LHS == RHS) 564 return 0; 565 566 // Primarily, sort the SCEVs by their getSCEVType(). 567 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 568 if (LType != RType) 569 return (int)LType - (int)RType; 570 571 if (Depth > MaxCompareDepth || EqCacheSCEV.count({LHS, RHS})) 572 return 0; 573 // Aside from the getSCEVType() ordering, the particular ordering 574 // isn't very important except that it's beneficial to be consistent, 575 // so that (a + b) and (b + a) don't end up as different expressions. 576 switch (static_cast<SCEVTypes>(LType)) { 577 case scUnknown: { 578 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 579 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 580 581 SmallSet<std::pair<Value *, Value *>, 8> EqCache; 582 int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(), 583 Depth + 1); 584 if (X == 0) 585 EqCacheSCEV.insert({LHS, RHS}); 586 return X; 587 } 588 589 case scConstant: { 590 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 591 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 592 593 // Compare constant values. 594 const APInt &LA = LC->getAPInt(); 595 const APInt &RA = RC->getAPInt(); 596 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 597 if (LBitWidth != RBitWidth) 598 return (int)LBitWidth - (int)RBitWidth; 599 return LA.ult(RA) ? -1 : 1; 600 } 601 602 case scAddRecExpr: { 603 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 604 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 605 606 // Compare addrec loop depths. 607 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 608 if (LLoop != RLoop) { 609 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth(); 610 if (LDepth != RDepth) 611 return (int)LDepth - (int)RDepth; 612 } 613 614 // Addrec complexity grows with operand count. 615 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 616 if (LNumOps != RNumOps) 617 return (int)LNumOps - (int)RNumOps; 618 619 // Lexicographically compare. 620 for (unsigned i = 0; i != LNumOps; ++i) { 621 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i), 622 RA->getOperand(i), Depth + 1); 623 if (X != 0) 624 return X; 625 } 626 EqCacheSCEV.insert({LHS, RHS}); 627 return 0; 628 } 629 630 case scAddExpr: 631 case scMulExpr: 632 case scSMaxExpr: 633 case scUMaxExpr: { 634 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 635 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 636 637 // Lexicographically compare n-ary expressions. 638 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 639 if (LNumOps != RNumOps) 640 return (int)LNumOps - (int)RNumOps; 641 642 for (unsigned i = 0; i != LNumOps; ++i) { 643 if (i >= RNumOps) 644 return 1; 645 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i), 646 RC->getOperand(i), Depth + 1); 647 if (X != 0) 648 return X; 649 } 650 EqCacheSCEV.insert({LHS, RHS}); 651 return 0; 652 } 653 654 case scUDivExpr: { 655 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 656 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 657 658 // Lexicographically compare udiv expressions. 659 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(), 660 Depth + 1); 661 if (X != 0) 662 return X; 663 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(), 664 Depth + 1); 665 if (X == 0) 666 EqCacheSCEV.insert({LHS, RHS}); 667 return X; 668 } 669 670 case scTruncate: 671 case scZeroExtend: 672 case scSignExtend: { 673 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 674 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 675 676 // Compare cast expressions by operand. 677 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(), 678 RC->getOperand(), Depth + 1); 679 if (X == 0) 680 EqCacheSCEV.insert({LHS, RHS}); 681 return X; 682 } 683 684 case scCouldNotCompute: 685 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 686 } 687 llvm_unreachable("Unknown SCEV kind!"); 688 } 689 690 /// Given a list of SCEV objects, order them by their complexity, and group 691 /// objects of the same complexity together by value. When this routine is 692 /// finished, we know that any duplicates in the vector are consecutive and that 693 /// complexity is monotonically increasing. 694 /// 695 /// Note that we go take special precautions to ensure that we get deterministic 696 /// results from this routine. In other words, we don't want the results of 697 /// this to depend on where the addresses of various SCEV objects happened to 698 /// land in memory. 699 /// 700 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 701 LoopInfo *LI) { 702 if (Ops.size() < 2) return; // Noop 703 704 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache; 705 if (Ops.size() == 2) { 706 // This is the common case, which also happens to be trivially simple. 707 // Special case it. 708 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 709 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0) 710 std::swap(LHS, RHS); 711 return; 712 } 713 714 // Do the rough sort by complexity. 715 std::stable_sort(Ops.begin(), Ops.end(), 716 [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) { 717 return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0; 718 }); 719 720 // Now that we are sorted by complexity, group elements of the same 721 // complexity. Note that this is, at worst, N^2, but the vector is likely to 722 // be extremely short in practice. Note that we take this approach because we 723 // do not want to depend on the addresses of the objects we are grouping. 724 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 725 const SCEV *S = Ops[i]; 726 unsigned Complexity = S->getSCEVType(); 727 728 // If there are any objects of the same complexity and same value as this 729 // one, group them. 730 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 731 if (Ops[j] == S) { // Found a duplicate. 732 // Move it to immediately after i'th element. 733 std::swap(Ops[i+1], Ops[j]); 734 ++i; // no need to rescan it. 735 if (i == e-2) return; // Done! 736 } 737 } 738 } 739 } 740 741 // Returns the size of the SCEV S. 742 static inline int sizeOfSCEV(const SCEV *S) { 743 struct FindSCEVSize { 744 int Size; 745 FindSCEVSize() : Size(0) {} 746 747 bool follow(const SCEV *S) { 748 ++Size; 749 // Keep looking at all operands of S. 750 return true; 751 } 752 bool isDone() const { 753 return false; 754 } 755 }; 756 757 FindSCEVSize F; 758 SCEVTraversal<FindSCEVSize> ST(F); 759 ST.visitAll(S); 760 return F.Size; 761 } 762 763 namespace { 764 765 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 766 public: 767 // Computes the Quotient and Remainder of the division of Numerator by 768 // Denominator. 769 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 770 const SCEV *Denominator, const SCEV **Quotient, 771 const SCEV **Remainder) { 772 assert(Numerator && Denominator && "Uninitialized SCEV"); 773 774 SCEVDivision D(SE, Numerator, Denominator); 775 776 // Check for the trivial case here to avoid having to check for it in the 777 // rest of the code. 778 if (Numerator == Denominator) { 779 *Quotient = D.One; 780 *Remainder = D.Zero; 781 return; 782 } 783 784 if (Numerator->isZero()) { 785 *Quotient = D.Zero; 786 *Remainder = D.Zero; 787 return; 788 } 789 790 // A simple case when N/1. The quotient is N. 791 if (Denominator->isOne()) { 792 *Quotient = Numerator; 793 *Remainder = D.Zero; 794 return; 795 } 796 797 // Split the Denominator when it is a product. 798 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 799 const SCEV *Q, *R; 800 *Quotient = Numerator; 801 for (const SCEV *Op : T->operands()) { 802 divide(SE, *Quotient, Op, &Q, &R); 803 *Quotient = Q; 804 805 // Bail out when the Numerator is not divisible by one of the terms of 806 // the Denominator. 807 if (!R->isZero()) { 808 *Quotient = D.Zero; 809 *Remainder = Numerator; 810 return; 811 } 812 } 813 *Remainder = D.Zero; 814 return; 815 } 816 817 D.visit(Numerator); 818 *Quotient = D.Quotient; 819 *Remainder = D.Remainder; 820 } 821 822 // Except in the trivial case described above, we do not know how to divide 823 // Expr by Denominator for the following functions with empty implementation. 824 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 825 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 826 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 827 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 828 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 829 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 830 void visitUnknown(const SCEVUnknown *Numerator) {} 831 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 832 833 void visitConstant(const SCEVConstant *Numerator) { 834 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 835 APInt NumeratorVal = Numerator->getAPInt(); 836 APInt DenominatorVal = D->getAPInt(); 837 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 838 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 839 840 if (NumeratorBW > DenominatorBW) 841 DenominatorVal = DenominatorVal.sext(NumeratorBW); 842 else if (NumeratorBW < DenominatorBW) 843 NumeratorVal = NumeratorVal.sext(DenominatorBW); 844 845 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 846 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 847 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 848 Quotient = SE.getConstant(QuotientVal); 849 Remainder = SE.getConstant(RemainderVal); 850 return; 851 } 852 } 853 854 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 855 const SCEV *StartQ, *StartR, *StepQ, *StepR; 856 if (!Numerator->isAffine()) 857 return cannotDivide(Numerator); 858 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 859 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 860 // Bail out if the types do not match. 861 Type *Ty = Denominator->getType(); 862 if (Ty != StartQ->getType() || Ty != StartR->getType() || 863 Ty != StepQ->getType() || Ty != StepR->getType()) 864 return cannotDivide(Numerator); 865 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 866 Numerator->getNoWrapFlags()); 867 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 868 Numerator->getNoWrapFlags()); 869 } 870 871 void visitAddExpr(const SCEVAddExpr *Numerator) { 872 SmallVector<const SCEV *, 2> Qs, Rs; 873 Type *Ty = Denominator->getType(); 874 875 for (const SCEV *Op : Numerator->operands()) { 876 const SCEV *Q, *R; 877 divide(SE, Op, Denominator, &Q, &R); 878 879 // Bail out if types do not match. 880 if (Ty != Q->getType() || Ty != R->getType()) 881 return cannotDivide(Numerator); 882 883 Qs.push_back(Q); 884 Rs.push_back(R); 885 } 886 887 if (Qs.size() == 1) { 888 Quotient = Qs[0]; 889 Remainder = Rs[0]; 890 return; 891 } 892 893 Quotient = SE.getAddExpr(Qs); 894 Remainder = SE.getAddExpr(Rs); 895 } 896 897 void visitMulExpr(const SCEVMulExpr *Numerator) { 898 SmallVector<const SCEV *, 2> Qs; 899 Type *Ty = Denominator->getType(); 900 901 bool FoundDenominatorTerm = false; 902 for (const SCEV *Op : Numerator->operands()) { 903 // Bail out if types do not match. 904 if (Ty != Op->getType()) 905 return cannotDivide(Numerator); 906 907 if (FoundDenominatorTerm) { 908 Qs.push_back(Op); 909 continue; 910 } 911 912 // Check whether Denominator divides one of the product operands. 913 const SCEV *Q, *R; 914 divide(SE, Op, Denominator, &Q, &R); 915 if (!R->isZero()) { 916 Qs.push_back(Op); 917 continue; 918 } 919 920 // Bail out if types do not match. 921 if (Ty != Q->getType()) 922 return cannotDivide(Numerator); 923 924 FoundDenominatorTerm = true; 925 Qs.push_back(Q); 926 } 927 928 if (FoundDenominatorTerm) { 929 Remainder = Zero; 930 if (Qs.size() == 1) 931 Quotient = Qs[0]; 932 else 933 Quotient = SE.getMulExpr(Qs); 934 return; 935 } 936 937 if (!isa<SCEVUnknown>(Denominator)) 938 return cannotDivide(Numerator); 939 940 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 941 ValueToValueMap RewriteMap; 942 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 943 cast<SCEVConstant>(Zero)->getValue(); 944 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 945 946 if (Remainder->isZero()) { 947 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 948 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 949 cast<SCEVConstant>(One)->getValue(); 950 Quotient = 951 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 952 return; 953 } 954 955 // Quotient is (Numerator - Remainder) divided by Denominator. 956 const SCEV *Q, *R; 957 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 958 // This SCEV does not seem to simplify: fail the division here. 959 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 960 return cannotDivide(Numerator); 961 divide(SE, Diff, Denominator, &Q, &R); 962 if (R != Zero) 963 return cannotDivide(Numerator); 964 Quotient = Q; 965 } 966 967 private: 968 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 969 const SCEV *Denominator) 970 : SE(S), Denominator(Denominator) { 971 Zero = SE.getZero(Denominator->getType()); 972 One = SE.getOne(Denominator->getType()); 973 974 // We generally do not know how to divide Expr by Denominator. We 975 // initialize the division to a "cannot divide" state to simplify the rest 976 // of the code. 977 cannotDivide(Numerator); 978 } 979 980 // Convenience function for giving up on the division. We set the quotient to 981 // be equal to zero and the remainder to be equal to the numerator. 982 void cannotDivide(const SCEV *Numerator) { 983 Quotient = Zero; 984 Remainder = Numerator; 985 } 986 987 ScalarEvolution &SE; 988 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 989 }; 990 991 } 992 993 //===----------------------------------------------------------------------===// 994 // Simple SCEV method implementations 995 //===----------------------------------------------------------------------===// 996 997 /// Compute BC(It, K). The result has width W. Assume, K > 0. 998 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 999 ScalarEvolution &SE, 1000 Type *ResultTy) { 1001 // Handle the simplest case efficiently. 1002 if (K == 1) 1003 return SE.getTruncateOrZeroExtend(It, ResultTy); 1004 1005 // We are using the following formula for BC(It, K): 1006 // 1007 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1008 // 1009 // Suppose, W is the bitwidth of the return value. We must be prepared for 1010 // overflow. Hence, we must assure that the result of our computation is 1011 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1012 // safe in modular arithmetic. 1013 // 1014 // However, this code doesn't use exactly that formula; the formula it uses 1015 // is something like the following, where T is the number of factors of 2 in 1016 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1017 // exponentiation: 1018 // 1019 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1020 // 1021 // This formula is trivially equivalent to the previous formula. However, 1022 // this formula can be implemented much more efficiently. The trick is that 1023 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1024 // arithmetic. To do exact division in modular arithmetic, all we have 1025 // to do is multiply by the inverse. Therefore, this step can be done at 1026 // width W. 1027 // 1028 // The next issue is how to safely do the division by 2^T. The way this 1029 // is done is by doing the multiplication step at a width of at least W + T 1030 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1031 // when we perform the division by 2^T (which is equivalent to a right shift 1032 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1033 // truncated out after the division by 2^T. 1034 // 1035 // In comparison to just directly using the first formula, this technique 1036 // is much more efficient; using the first formula requires W * K bits, 1037 // but this formula less than W + K bits. Also, the first formula requires 1038 // a division step, whereas this formula only requires multiplies and shifts. 1039 // 1040 // It doesn't matter whether the subtraction step is done in the calculation 1041 // width or the input iteration count's width; if the subtraction overflows, 1042 // the result must be zero anyway. We prefer here to do it in the width of 1043 // the induction variable because it helps a lot for certain cases; CodeGen 1044 // isn't smart enough to ignore the overflow, which leads to much less 1045 // efficient code if the width of the subtraction is wider than the native 1046 // register width. 1047 // 1048 // (It's possible to not widen at all by pulling out factors of 2 before 1049 // the multiplication; for example, K=2 can be calculated as 1050 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1051 // extra arithmetic, so it's not an obvious win, and it gets 1052 // much more complicated for K > 3.) 1053 1054 // Protection from insane SCEVs; this bound is conservative, 1055 // but it probably doesn't matter. 1056 if (K > 1000) 1057 return SE.getCouldNotCompute(); 1058 1059 unsigned W = SE.getTypeSizeInBits(ResultTy); 1060 1061 // Calculate K! / 2^T and T; we divide out the factors of two before 1062 // multiplying for calculating K! / 2^T to avoid overflow. 1063 // Other overflow doesn't matter because we only care about the bottom 1064 // W bits of the result. 1065 APInt OddFactorial(W, 1); 1066 unsigned T = 1; 1067 for (unsigned i = 3; i <= K; ++i) { 1068 APInt Mult(W, i); 1069 unsigned TwoFactors = Mult.countTrailingZeros(); 1070 T += TwoFactors; 1071 Mult = Mult.lshr(TwoFactors); 1072 OddFactorial *= Mult; 1073 } 1074 1075 // We need at least W + T bits for the multiplication step 1076 unsigned CalculationBits = W + T; 1077 1078 // Calculate 2^T, at width T+W. 1079 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1080 1081 // Calculate the multiplicative inverse of K! / 2^T; 1082 // this multiplication factor will perform the exact division by 1083 // K! / 2^T. 1084 APInt Mod = APInt::getSignedMinValue(W+1); 1085 APInt MultiplyFactor = OddFactorial.zext(W+1); 1086 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1087 MultiplyFactor = MultiplyFactor.trunc(W); 1088 1089 // Calculate the product, at width T+W 1090 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1091 CalculationBits); 1092 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1093 for (unsigned i = 1; i != K; ++i) { 1094 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1095 Dividend = SE.getMulExpr(Dividend, 1096 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1097 } 1098 1099 // Divide by 2^T 1100 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1101 1102 // Truncate the result, and divide by K! / 2^T. 1103 1104 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1105 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1106 } 1107 1108 /// Return the value of this chain of recurrences at the specified iteration 1109 /// number. We can evaluate this recurrence by multiplying each element in the 1110 /// chain by the binomial coefficient corresponding to it. In other words, we 1111 /// can evaluate {A,+,B,+,C,+,D} as: 1112 /// 1113 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1114 /// 1115 /// where BC(It, k) stands for binomial coefficient. 1116 /// 1117 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1118 ScalarEvolution &SE) const { 1119 const SCEV *Result = getStart(); 1120 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1121 // The computation is correct in the face of overflow provided that the 1122 // multiplication is performed _after_ the evaluation of the binomial 1123 // coefficient. 1124 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1125 if (isa<SCEVCouldNotCompute>(Coeff)) 1126 return Coeff; 1127 1128 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1129 } 1130 return Result; 1131 } 1132 1133 //===----------------------------------------------------------------------===// 1134 // SCEV Expression folder implementations 1135 //===----------------------------------------------------------------------===// 1136 1137 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1138 Type *Ty) { 1139 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1140 "This is not a truncating conversion!"); 1141 assert(isSCEVable(Ty) && 1142 "This is not a conversion to a SCEVable type!"); 1143 Ty = getEffectiveSCEVType(Ty); 1144 1145 FoldingSetNodeID ID; 1146 ID.AddInteger(scTruncate); 1147 ID.AddPointer(Op); 1148 ID.AddPointer(Ty); 1149 void *IP = nullptr; 1150 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1151 1152 // Fold if the operand is constant. 1153 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1154 return getConstant( 1155 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1156 1157 // trunc(trunc(x)) --> trunc(x) 1158 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1159 return getTruncateExpr(ST->getOperand(), Ty); 1160 1161 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1162 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1163 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1164 1165 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1166 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1167 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1168 1169 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can 1170 // eliminate all the truncates, or we replace other casts with truncates. 1171 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { 1172 SmallVector<const SCEV *, 4> Operands; 1173 bool hasTrunc = false; 1174 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { 1175 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); 1176 if (!isa<SCEVCastExpr>(SA->getOperand(i))) 1177 hasTrunc = isa<SCEVTruncateExpr>(S); 1178 Operands.push_back(S); 1179 } 1180 if (!hasTrunc) 1181 return getAddExpr(Operands); 1182 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1183 } 1184 1185 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can 1186 // eliminate all the truncates, or we replace other casts with truncates. 1187 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { 1188 SmallVector<const SCEV *, 4> Operands; 1189 bool hasTrunc = false; 1190 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { 1191 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); 1192 if (!isa<SCEVCastExpr>(SM->getOperand(i))) 1193 hasTrunc = isa<SCEVTruncateExpr>(S); 1194 Operands.push_back(S); 1195 } 1196 if (!hasTrunc) 1197 return getMulExpr(Operands); 1198 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1199 } 1200 1201 // If the input value is a chrec scev, truncate the chrec's operands. 1202 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1203 SmallVector<const SCEV *, 4> Operands; 1204 for (const SCEV *Op : AddRec->operands()) 1205 Operands.push_back(getTruncateExpr(Op, Ty)); 1206 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1207 } 1208 1209 // The cast wasn't folded; create an explicit cast node. We can reuse 1210 // the existing insert position since if we get here, we won't have 1211 // made any changes which would invalidate it. 1212 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1213 Op, Ty); 1214 UniqueSCEVs.InsertNode(S, IP); 1215 return S; 1216 } 1217 1218 // Get the limit of a recurrence such that incrementing by Step cannot cause 1219 // signed overflow as long as the value of the recurrence within the 1220 // loop does not exceed this limit before incrementing. 1221 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1222 ICmpInst::Predicate *Pred, 1223 ScalarEvolution *SE) { 1224 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1225 if (SE->isKnownPositive(Step)) { 1226 *Pred = ICmpInst::ICMP_SLT; 1227 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1228 SE->getSignedRange(Step).getSignedMax()); 1229 } 1230 if (SE->isKnownNegative(Step)) { 1231 *Pred = ICmpInst::ICMP_SGT; 1232 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1233 SE->getSignedRange(Step).getSignedMin()); 1234 } 1235 return nullptr; 1236 } 1237 1238 // Get the limit of a recurrence such that incrementing by Step cannot cause 1239 // unsigned overflow as long as the value of the recurrence within the loop does 1240 // not exceed this limit before incrementing. 1241 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1242 ICmpInst::Predicate *Pred, 1243 ScalarEvolution *SE) { 1244 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1245 *Pred = ICmpInst::ICMP_ULT; 1246 1247 return SE->getConstant(APInt::getMinValue(BitWidth) - 1248 SE->getUnsignedRange(Step).getUnsignedMax()); 1249 } 1250 1251 namespace { 1252 1253 struct ExtendOpTraitsBase { 1254 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *); 1255 }; 1256 1257 // Used to make code generic over signed and unsigned overflow. 1258 template <typename ExtendOp> struct ExtendOpTraits { 1259 // Members present: 1260 // 1261 // static const SCEV::NoWrapFlags WrapType; 1262 // 1263 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1264 // 1265 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1266 // ICmpInst::Predicate *Pred, 1267 // ScalarEvolution *SE); 1268 }; 1269 1270 template <> 1271 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1272 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1273 1274 static const GetExtendExprTy GetExtendExpr; 1275 1276 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1277 ICmpInst::Predicate *Pred, 1278 ScalarEvolution *SE) { 1279 return getSignedOverflowLimitForStep(Step, Pred, SE); 1280 } 1281 }; 1282 1283 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1284 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1285 1286 template <> 1287 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1288 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1289 1290 static const GetExtendExprTy GetExtendExpr; 1291 1292 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1293 ICmpInst::Predicate *Pred, 1294 ScalarEvolution *SE) { 1295 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1296 } 1297 }; 1298 1299 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1300 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1301 } 1302 1303 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1304 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1305 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1306 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1307 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1308 // expression "Step + sext/zext(PreIncAR)" is congruent with 1309 // "sext/zext(PostIncAR)" 1310 template <typename ExtendOpTy> 1311 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1312 ScalarEvolution *SE) { 1313 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1314 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1315 1316 const Loop *L = AR->getLoop(); 1317 const SCEV *Start = AR->getStart(); 1318 const SCEV *Step = AR->getStepRecurrence(*SE); 1319 1320 // Check for a simple looking step prior to loop entry. 1321 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1322 if (!SA) 1323 return nullptr; 1324 1325 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1326 // subtraction is expensive. For this purpose, perform a quick and dirty 1327 // difference, by checking for Step in the operand list. 1328 SmallVector<const SCEV *, 4> DiffOps; 1329 for (const SCEV *Op : SA->operands()) 1330 if (Op != Step) 1331 DiffOps.push_back(Op); 1332 1333 if (DiffOps.size() == SA->getNumOperands()) 1334 return nullptr; 1335 1336 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1337 // `Step`: 1338 1339 // 1. NSW/NUW flags on the step increment. 1340 auto PreStartFlags = 1341 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1342 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1343 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1344 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1345 1346 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1347 // "S+X does not sign/unsign-overflow". 1348 // 1349 1350 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1351 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1352 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1353 return PreStart; 1354 1355 // 2. Direct overflow check on the step operation's expression. 1356 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1357 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1358 const SCEV *OperandExtendedStart = 1359 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy), 1360 (SE->*GetExtendExpr)(Step, WideTy)); 1361 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) { 1362 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1363 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1364 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1365 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1366 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1367 } 1368 return PreStart; 1369 } 1370 1371 // 3. Loop precondition. 1372 ICmpInst::Predicate Pred; 1373 const SCEV *OverflowLimit = 1374 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1375 1376 if (OverflowLimit && 1377 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1378 return PreStart; 1379 1380 return nullptr; 1381 } 1382 1383 // Get the normalized zero or sign extended expression for this AddRec's Start. 1384 template <typename ExtendOpTy> 1385 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1386 ScalarEvolution *SE) { 1387 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1388 1389 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE); 1390 if (!PreStart) 1391 return (SE->*GetExtendExpr)(AR->getStart(), Ty); 1392 1393 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty), 1394 (SE->*GetExtendExpr)(PreStart, Ty)); 1395 } 1396 1397 // Try to prove away overflow by looking at "nearby" add recurrences. A 1398 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1399 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1400 // 1401 // Formally: 1402 // 1403 // {S,+,X} == {S-T,+,X} + T 1404 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1405 // 1406 // If ({S-T,+,X} + T) does not overflow ... (1) 1407 // 1408 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1409 // 1410 // If {S-T,+,X} does not overflow ... (2) 1411 // 1412 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1413 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1414 // 1415 // If (S-T)+T does not overflow ... (3) 1416 // 1417 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1418 // == {Ext(S),+,Ext(X)} == LHS 1419 // 1420 // Thus, if (1), (2) and (3) are true for some T, then 1421 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1422 // 1423 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1424 // does not overflow" restricted to the 0th iteration. Therefore we only need 1425 // to check for (1) and (2). 1426 // 1427 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1428 // is `Delta` (defined below). 1429 // 1430 template <typename ExtendOpTy> 1431 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1432 const SCEV *Step, 1433 const Loop *L) { 1434 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1435 1436 // We restrict `Start` to a constant to prevent SCEV from spending too much 1437 // time here. It is correct (but more expensive) to continue with a 1438 // non-constant `Start` and do a general SCEV subtraction to compute 1439 // `PreStart` below. 1440 // 1441 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1442 if (!StartC) 1443 return false; 1444 1445 APInt StartAI = StartC->getAPInt(); 1446 1447 for (unsigned Delta : {-2, -1, 1, 2}) { 1448 const SCEV *PreStart = getConstant(StartAI - Delta); 1449 1450 FoldingSetNodeID ID; 1451 ID.AddInteger(scAddRecExpr); 1452 ID.AddPointer(PreStart); 1453 ID.AddPointer(Step); 1454 ID.AddPointer(L); 1455 void *IP = nullptr; 1456 const auto *PreAR = 1457 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1458 1459 // Give up if we don't already have the add recurrence we need because 1460 // actually constructing an add recurrence is relatively expensive. 1461 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1462 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1463 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1464 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1465 DeltaS, &Pred, this); 1466 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1467 return true; 1468 } 1469 } 1470 1471 return false; 1472 } 1473 1474 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, 1475 Type *Ty) { 1476 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1477 "This is not an extending conversion!"); 1478 assert(isSCEVable(Ty) && 1479 "This is not a conversion to a SCEVable type!"); 1480 Ty = getEffectiveSCEVType(Ty); 1481 1482 // Fold if the operand is constant. 1483 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1484 return getConstant( 1485 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1486 1487 // zext(zext(x)) --> zext(x) 1488 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1489 return getZeroExtendExpr(SZ->getOperand(), Ty); 1490 1491 // Before doing any expensive analysis, check to see if we've already 1492 // computed a SCEV for this Op and Ty. 1493 FoldingSetNodeID ID; 1494 ID.AddInteger(scZeroExtend); 1495 ID.AddPointer(Op); 1496 ID.AddPointer(Ty); 1497 void *IP = nullptr; 1498 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1499 1500 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1501 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1502 // It's possible the bits taken off by the truncate were all zero bits. If 1503 // so, we should be able to simplify this further. 1504 const SCEV *X = ST->getOperand(); 1505 ConstantRange CR = getUnsignedRange(X); 1506 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1507 unsigned NewBits = getTypeSizeInBits(Ty); 1508 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1509 CR.zextOrTrunc(NewBits))) 1510 return getTruncateOrZeroExtend(X, Ty); 1511 } 1512 1513 // If the input value is a chrec scev, and we can prove that the value 1514 // did not overflow the old, smaller, value, we can zero extend all of the 1515 // operands (often constants). This allows analysis of something like 1516 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1517 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1518 if (AR->isAffine()) { 1519 const SCEV *Start = AR->getStart(); 1520 const SCEV *Step = AR->getStepRecurrence(*this); 1521 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1522 const Loop *L = AR->getLoop(); 1523 1524 if (!AR->hasNoUnsignedWrap()) { 1525 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1526 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1527 } 1528 1529 // If we have special knowledge that this addrec won't overflow, 1530 // we don't need to do any further analysis. 1531 if (AR->hasNoUnsignedWrap()) 1532 return getAddRecExpr( 1533 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1534 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1535 1536 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1537 // Note that this serves two purposes: It filters out loops that are 1538 // simply not analyzable, and it covers the case where this code is 1539 // being called from within backedge-taken count analysis, such that 1540 // attempting to ask for the backedge-taken count would likely result 1541 // in infinite recursion. In the later case, the analysis code will 1542 // cope with a conservative value, and it will take care to purge 1543 // that value once it has finished. 1544 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1545 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1546 // Manually compute the final value for AR, checking for 1547 // overflow. 1548 1549 // Check whether the backedge-taken count can be losslessly casted to 1550 // the addrec's type. The count is always unsigned. 1551 const SCEV *CastedMaxBECount = 1552 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1553 const SCEV *RecastedMaxBECount = 1554 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1555 if (MaxBECount == RecastedMaxBECount) { 1556 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1557 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1558 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); 1559 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy); 1560 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy); 1561 const SCEV *WideMaxBECount = 1562 getZeroExtendExpr(CastedMaxBECount, WideTy); 1563 const SCEV *OperandExtendedAdd = 1564 getAddExpr(WideStart, 1565 getMulExpr(WideMaxBECount, 1566 getZeroExtendExpr(Step, WideTy))); 1567 if (ZAdd == OperandExtendedAdd) { 1568 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1569 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1570 // Return the expression with the addrec on the outside. 1571 return getAddRecExpr( 1572 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1573 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1574 } 1575 // Similar to above, only this time treat the step value as signed. 1576 // This covers loops that count down. 1577 OperandExtendedAdd = 1578 getAddExpr(WideStart, 1579 getMulExpr(WideMaxBECount, 1580 getSignExtendExpr(Step, WideTy))); 1581 if (ZAdd == OperandExtendedAdd) { 1582 // Cache knowledge of AR NW, which is propagated to this AddRec. 1583 // Negative step causes unsigned wrap, but it still can't self-wrap. 1584 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1585 // Return the expression with the addrec on the outside. 1586 return getAddRecExpr( 1587 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1588 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1589 } 1590 } 1591 } 1592 1593 // Normally, in the cases we can prove no-overflow via a 1594 // backedge guarding condition, we can also compute a backedge 1595 // taken count for the loop. The exceptions are assumptions and 1596 // guards present in the loop -- SCEV is not great at exploiting 1597 // these to compute max backedge taken counts, but can still use 1598 // these to prove lack of overflow. Use this fact to avoid 1599 // doing extra work that may not pay off. 1600 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1601 !AC.assumptions().empty()) { 1602 // If the backedge is guarded by a comparison with the pre-inc 1603 // value the addrec is safe. Also, if the entry is guarded by 1604 // a comparison with the start value and the backedge is 1605 // guarded by a comparison with the post-inc value, the addrec 1606 // is safe. 1607 if (isKnownPositive(Step)) { 1608 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1609 getUnsignedRange(Step).getUnsignedMax()); 1610 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1611 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && 1612 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, 1613 AR->getPostIncExpr(*this), N))) { 1614 // Cache knowledge of AR NUW, which is propagated to this 1615 // AddRec. 1616 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1617 // Return the expression with the addrec on the outside. 1618 return getAddRecExpr( 1619 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1620 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1621 } 1622 } else if (isKnownNegative(Step)) { 1623 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1624 getSignedRange(Step).getSignedMin()); 1625 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1626 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && 1627 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, 1628 AR->getPostIncExpr(*this), N))) { 1629 // Cache knowledge of AR NW, which is propagated to this 1630 // AddRec. Negative step causes unsigned wrap, but it 1631 // still can't self-wrap. 1632 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1633 // Return the expression with the addrec on the outside. 1634 return getAddRecExpr( 1635 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1636 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1637 } 1638 } 1639 } 1640 1641 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1642 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1643 return getAddRecExpr( 1644 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1645 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1646 } 1647 } 1648 1649 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1650 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1651 if (SA->hasNoUnsignedWrap()) { 1652 // If the addition does not unsign overflow then we can, by definition, 1653 // commute the zero extension with the addition operation. 1654 SmallVector<const SCEV *, 4> Ops; 1655 for (const auto *Op : SA->operands()) 1656 Ops.push_back(getZeroExtendExpr(Op, Ty)); 1657 return getAddExpr(Ops, SCEV::FlagNUW); 1658 } 1659 } 1660 1661 // The cast wasn't folded; create an explicit cast node. 1662 // Recompute the insert position, as it may have been invalidated. 1663 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1664 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1665 Op, Ty); 1666 UniqueSCEVs.InsertNode(S, IP); 1667 return S; 1668 } 1669 1670 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, 1671 Type *Ty) { 1672 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1673 "This is not an extending conversion!"); 1674 assert(isSCEVable(Ty) && 1675 "This is not a conversion to a SCEVable type!"); 1676 Ty = getEffectiveSCEVType(Ty); 1677 1678 // Fold if the operand is constant. 1679 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1680 return getConstant( 1681 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1682 1683 // sext(sext(x)) --> sext(x) 1684 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1685 return getSignExtendExpr(SS->getOperand(), Ty); 1686 1687 // sext(zext(x)) --> zext(x) 1688 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1689 return getZeroExtendExpr(SZ->getOperand(), Ty); 1690 1691 // Before doing any expensive analysis, check to see if we've already 1692 // computed a SCEV for this Op and Ty. 1693 FoldingSetNodeID ID; 1694 ID.AddInteger(scSignExtend); 1695 ID.AddPointer(Op); 1696 ID.AddPointer(Ty); 1697 void *IP = nullptr; 1698 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1699 1700 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1701 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1702 // It's possible the bits taken off by the truncate were all sign bits. If 1703 // so, we should be able to simplify this further. 1704 const SCEV *X = ST->getOperand(); 1705 ConstantRange CR = getSignedRange(X); 1706 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1707 unsigned NewBits = getTypeSizeInBits(Ty); 1708 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1709 CR.sextOrTrunc(NewBits))) 1710 return getTruncateOrSignExtend(X, Ty); 1711 } 1712 1713 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1714 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1715 if (SA->getNumOperands() == 2) { 1716 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1717 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1718 if (SMul && SC1) { 1719 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1720 const APInt &C1 = SC1->getAPInt(); 1721 const APInt &C2 = SC2->getAPInt(); 1722 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1723 C2.ugt(C1) && C2.isPowerOf2()) 1724 return getAddExpr(getSignExtendExpr(SC1, Ty), 1725 getSignExtendExpr(SMul, Ty)); 1726 } 1727 } 1728 } 1729 1730 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1731 if (SA->hasNoSignedWrap()) { 1732 // If the addition does not sign overflow then we can, by definition, 1733 // commute the sign extension with the addition operation. 1734 SmallVector<const SCEV *, 4> Ops; 1735 for (const auto *Op : SA->operands()) 1736 Ops.push_back(getSignExtendExpr(Op, Ty)); 1737 return getAddExpr(Ops, SCEV::FlagNSW); 1738 } 1739 } 1740 // If the input value is a chrec scev, and we can prove that the value 1741 // did not overflow the old, smaller, value, we can sign extend all of the 1742 // operands (often constants). This allows analysis of something like 1743 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1744 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1745 if (AR->isAffine()) { 1746 const SCEV *Start = AR->getStart(); 1747 const SCEV *Step = AR->getStepRecurrence(*this); 1748 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1749 const Loop *L = AR->getLoop(); 1750 1751 if (!AR->hasNoSignedWrap()) { 1752 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1753 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1754 } 1755 1756 // If we have special knowledge that this addrec won't overflow, 1757 // we don't need to do any further analysis. 1758 if (AR->hasNoSignedWrap()) 1759 return getAddRecExpr( 1760 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1761 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW); 1762 1763 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1764 // Note that this serves two purposes: It filters out loops that are 1765 // simply not analyzable, and it covers the case where this code is 1766 // being called from within backedge-taken count analysis, such that 1767 // attempting to ask for the backedge-taken count would likely result 1768 // in infinite recursion. In the later case, the analysis code will 1769 // cope with a conservative value, and it will take care to purge 1770 // that value once it has finished. 1771 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1772 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1773 // Manually compute the final value for AR, checking for 1774 // overflow. 1775 1776 // Check whether the backedge-taken count can be losslessly casted to 1777 // the addrec's type. The count is always unsigned. 1778 const SCEV *CastedMaxBECount = 1779 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1780 const SCEV *RecastedMaxBECount = 1781 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1782 if (MaxBECount == RecastedMaxBECount) { 1783 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1784 // Check whether Start+Step*MaxBECount has no signed overflow. 1785 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); 1786 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy); 1787 const SCEV *WideStart = getSignExtendExpr(Start, WideTy); 1788 const SCEV *WideMaxBECount = 1789 getZeroExtendExpr(CastedMaxBECount, WideTy); 1790 const SCEV *OperandExtendedAdd = 1791 getAddExpr(WideStart, 1792 getMulExpr(WideMaxBECount, 1793 getSignExtendExpr(Step, WideTy))); 1794 if (SAdd == OperandExtendedAdd) { 1795 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1796 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1797 // Return the expression with the addrec on the outside. 1798 return getAddRecExpr( 1799 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1800 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1801 } 1802 // Similar to above, only this time treat the step value as unsigned. 1803 // This covers loops that count up with an unsigned step. 1804 OperandExtendedAdd = 1805 getAddExpr(WideStart, 1806 getMulExpr(WideMaxBECount, 1807 getZeroExtendExpr(Step, WideTy))); 1808 if (SAdd == OperandExtendedAdd) { 1809 // If AR wraps around then 1810 // 1811 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1812 // => SAdd != OperandExtendedAdd 1813 // 1814 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1815 // (SAdd == OperandExtendedAdd => AR is NW) 1816 1817 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1818 1819 // Return the expression with the addrec on the outside. 1820 return getAddRecExpr( 1821 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1822 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1823 } 1824 } 1825 } 1826 1827 // Normally, in the cases we can prove no-overflow via a 1828 // backedge guarding condition, we can also compute a backedge 1829 // taken count for the loop. The exceptions are assumptions and 1830 // guards present in the loop -- SCEV is not great at exploiting 1831 // these to compute max backedge taken counts, but can still use 1832 // these to prove lack of overflow. Use this fact to avoid 1833 // doing extra work that may not pay off. 1834 1835 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1836 !AC.assumptions().empty()) { 1837 // If the backedge is guarded by a comparison with the pre-inc 1838 // value the addrec is safe. Also, if the entry is guarded by 1839 // a comparison with the start value and the backedge is 1840 // guarded by a comparison with the post-inc value, the addrec 1841 // is safe. 1842 ICmpInst::Predicate Pred; 1843 const SCEV *OverflowLimit = 1844 getSignedOverflowLimitForStep(Step, &Pred, this); 1845 if (OverflowLimit && 1846 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1847 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && 1848 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), 1849 OverflowLimit)))) { 1850 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1851 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1852 return getAddRecExpr( 1853 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1854 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1855 } 1856 } 1857 1858 // If Start and Step are constants, check if we can apply this 1859 // transformation: 1860 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 1861 auto *SC1 = dyn_cast<SCEVConstant>(Start); 1862 auto *SC2 = dyn_cast<SCEVConstant>(Step); 1863 if (SC1 && SC2) { 1864 const APInt &C1 = SC1->getAPInt(); 1865 const APInt &C2 = SC2->getAPInt(); 1866 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 1867 C2.isPowerOf2()) { 1868 Start = getSignExtendExpr(Start, Ty); 1869 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 1870 AR->getNoWrapFlags()); 1871 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty)); 1872 } 1873 } 1874 1875 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1876 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1877 return getAddRecExpr( 1878 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1879 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1880 } 1881 } 1882 1883 // If the input value is provably positive and we could not simplify 1884 // away the sext build a zext instead. 1885 if (isKnownNonNegative(Op)) 1886 return getZeroExtendExpr(Op, Ty); 1887 1888 // The cast wasn't folded; create an explicit cast node. 1889 // Recompute the insert position, as it may have been invalidated. 1890 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1891 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1892 Op, Ty); 1893 UniqueSCEVs.InsertNode(S, IP); 1894 return S; 1895 } 1896 1897 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1898 /// unspecified bits out to the given type. 1899 /// 1900 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1901 Type *Ty) { 1902 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1903 "This is not an extending conversion!"); 1904 assert(isSCEVable(Ty) && 1905 "This is not a conversion to a SCEVable type!"); 1906 Ty = getEffectiveSCEVType(Ty); 1907 1908 // Sign-extend negative constants. 1909 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1910 if (SC->getAPInt().isNegative()) 1911 return getSignExtendExpr(Op, Ty); 1912 1913 // Peel off a truncate cast. 1914 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 1915 const SCEV *NewOp = T->getOperand(); 1916 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 1917 return getAnyExtendExpr(NewOp, Ty); 1918 return getTruncateOrNoop(NewOp, Ty); 1919 } 1920 1921 // Next try a zext cast. If the cast is folded, use it. 1922 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 1923 if (!isa<SCEVZeroExtendExpr>(ZExt)) 1924 return ZExt; 1925 1926 // Next try a sext cast. If the cast is folded, use it. 1927 const SCEV *SExt = getSignExtendExpr(Op, Ty); 1928 if (!isa<SCEVSignExtendExpr>(SExt)) 1929 return SExt; 1930 1931 // Force the cast to be folded into the operands of an addrec. 1932 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 1933 SmallVector<const SCEV *, 4> Ops; 1934 for (const SCEV *Op : AR->operands()) 1935 Ops.push_back(getAnyExtendExpr(Op, Ty)); 1936 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 1937 } 1938 1939 // If the expression is obviously signed, use the sext cast value. 1940 if (isa<SCEVSMaxExpr>(Op)) 1941 return SExt; 1942 1943 // Absent any other information, use the zext cast value. 1944 return ZExt; 1945 } 1946 1947 /// Process the given Ops list, which is a list of operands to be added under 1948 /// the given scale, update the given map. This is a helper function for 1949 /// getAddRecExpr. As an example of what it does, given a sequence of operands 1950 /// that would form an add expression like this: 1951 /// 1952 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 1953 /// 1954 /// where A and B are constants, update the map with these values: 1955 /// 1956 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 1957 /// 1958 /// and add 13 + A*B*29 to AccumulatedConstant. 1959 /// This will allow getAddRecExpr to produce this: 1960 /// 1961 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 1962 /// 1963 /// This form often exposes folding opportunities that are hidden in 1964 /// the original operand list. 1965 /// 1966 /// Return true iff it appears that any interesting folding opportunities 1967 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 1968 /// the common case where no interesting opportunities are present, and 1969 /// is also used as a check to avoid infinite recursion. 1970 /// 1971 static bool 1972 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 1973 SmallVectorImpl<const SCEV *> &NewOps, 1974 APInt &AccumulatedConstant, 1975 const SCEV *const *Ops, size_t NumOperands, 1976 const APInt &Scale, 1977 ScalarEvolution &SE) { 1978 bool Interesting = false; 1979 1980 // Iterate over the add operands. They are sorted, with constants first. 1981 unsigned i = 0; 1982 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 1983 ++i; 1984 // Pull a buried constant out to the outside. 1985 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 1986 Interesting = true; 1987 AccumulatedConstant += Scale * C->getAPInt(); 1988 } 1989 1990 // Next comes everything else. We're especially interested in multiplies 1991 // here, but they're in the middle, so just visit the rest with one loop. 1992 for (; i != NumOperands; ++i) { 1993 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 1994 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 1995 APInt NewScale = 1996 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 1997 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 1998 // A multiplication of a constant with another add; recurse. 1999 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2000 Interesting |= 2001 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2002 Add->op_begin(), Add->getNumOperands(), 2003 NewScale, SE); 2004 } else { 2005 // A multiplication of a constant with some other value. Update 2006 // the map. 2007 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2008 const SCEV *Key = SE.getMulExpr(MulOps); 2009 auto Pair = M.insert({Key, NewScale}); 2010 if (Pair.second) { 2011 NewOps.push_back(Pair.first->first); 2012 } else { 2013 Pair.first->second += NewScale; 2014 // The map already had an entry for this value, which may indicate 2015 // a folding opportunity. 2016 Interesting = true; 2017 } 2018 } 2019 } else { 2020 // An ordinary operand. Update the map. 2021 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2022 M.insert({Ops[i], Scale}); 2023 if (Pair.second) { 2024 NewOps.push_back(Pair.first->first); 2025 } else { 2026 Pair.first->second += Scale; 2027 // The map already had an entry for this value, which may indicate 2028 // a folding opportunity. 2029 Interesting = true; 2030 } 2031 } 2032 } 2033 2034 return Interesting; 2035 } 2036 2037 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2038 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2039 // can't-overflow flags for the operation if possible. 2040 static SCEV::NoWrapFlags 2041 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2042 const SmallVectorImpl<const SCEV *> &Ops, 2043 SCEV::NoWrapFlags Flags) { 2044 using namespace std::placeholders; 2045 typedef OverflowingBinaryOperator OBO; 2046 2047 bool CanAnalyze = 2048 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2049 (void)CanAnalyze; 2050 assert(CanAnalyze && "don't call from other places!"); 2051 2052 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2053 SCEV::NoWrapFlags SignOrUnsignWrap = 2054 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2055 2056 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2057 auto IsKnownNonNegative = [&](const SCEV *S) { 2058 return SE->isKnownNonNegative(S); 2059 }; 2060 2061 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2062 Flags = 2063 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2064 2065 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2066 2067 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 2068 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 2069 2070 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 2071 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 2072 2073 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2074 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2075 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2076 Instruction::Add, C, OBO::NoSignedWrap); 2077 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2078 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2079 } 2080 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2081 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2082 Instruction::Add, C, OBO::NoUnsignedWrap); 2083 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2084 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2085 } 2086 } 2087 2088 return Flags; 2089 } 2090 2091 /// Get a canonical add expression, or something simpler if possible. 2092 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2093 SCEV::NoWrapFlags Flags) { 2094 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2095 "only nuw or nsw allowed"); 2096 assert(!Ops.empty() && "Cannot get empty add!"); 2097 if (Ops.size() == 1) return Ops[0]; 2098 #ifndef NDEBUG 2099 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2100 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2101 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2102 "SCEVAddExpr operand types don't match!"); 2103 #endif 2104 2105 // Sort by complexity, this groups all similar expression types together. 2106 GroupByComplexity(Ops, &LI); 2107 2108 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2109 2110 // If there are any constants, fold them together. 2111 unsigned Idx = 0; 2112 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2113 ++Idx; 2114 assert(Idx < Ops.size()); 2115 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2116 // We found two constants, fold them together! 2117 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2118 if (Ops.size() == 2) return Ops[0]; 2119 Ops.erase(Ops.begin()+1); // Erase the folded element 2120 LHSC = cast<SCEVConstant>(Ops[0]); 2121 } 2122 2123 // If we are left with a constant zero being added, strip it off. 2124 if (LHSC->getValue()->isZero()) { 2125 Ops.erase(Ops.begin()); 2126 --Idx; 2127 } 2128 2129 if (Ops.size() == 1) return Ops[0]; 2130 } 2131 2132 // Okay, check to see if the same value occurs in the operand list more than 2133 // once. If so, merge them together into an multiply expression. Since we 2134 // sorted the list, these values are required to be adjacent. 2135 Type *Ty = Ops[0]->getType(); 2136 bool FoundMatch = false; 2137 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2138 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2139 // Scan ahead to count how many equal operands there are. 2140 unsigned Count = 2; 2141 while (i+Count != e && Ops[i+Count] == Ops[i]) 2142 ++Count; 2143 // Merge the values into a multiply. 2144 const SCEV *Scale = getConstant(Ty, Count); 2145 const SCEV *Mul = getMulExpr(Scale, Ops[i]); 2146 if (Ops.size() == Count) 2147 return Mul; 2148 Ops[i] = Mul; 2149 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2150 --i; e -= Count - 1; 2151 FoundMatch = true; 2152 } 2153 if (FoundMatch) 2154 return getAddExpr(Ops, Flags); 2155 2156 // Check for truncates. If all the operands are truncated from the same 2157 // type, see if factoring out the truncate would permit the result to be 2158 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) 2159 // if the contents of the resulting outer trunc fold to something simple. 2160 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { 2161 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); 2162 Type *DstType = Trunc->getType(); 2163 Type *SrcType = Trunc->getOperand()->getType(); 2164 SmallVector<const SCEV *, 8> LargeOps; 2165 bool Ok = true; 2166 // Check all the operands to see if they can be represented in the 2167 // source type of the truncate. 2168 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2169 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2170 if (T->getOperand()->getType() != SrcType) { 2171 Ok = false; 2172 break; 2173 } 2174 LargeOps.push_back(T->getOperand()); 2175 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2176 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2177 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2178 SmallVector<const SCEV *, 8> LargeMulOps; 2179 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2180 if (const SCEVTruncateExpr *T = 2181 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2182 if (T->getOperand()->getType() != SrcType) { 2183 Ok = false; 2184 break; 2185 } 2186 LargeMulOps.push_back(T->getOperand()); 2187 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2188 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2189 } else { 2190 Ok = false; 2191 break; 2192 } 2193 } 2194 if (Ok) 2195 LargeOps.push_back(getMulExpr(LargeMulOps)); 2196 } else { 2197 Ok = false; 2198 break; 2199 } 2200 } 2201 if (Ok) { 2202 // Evaluate the expression in the larger type. 2203 const SCEV *Fold = getAddExpr(LargeOps, Flags); 2204 // If it folds to something simple, use it. Otherwise, don't. 2205 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2206 return getTruncateExpr(Fold, DstType); 2207 } 2208 } 2209 2210 // Skip past any other cast SCEVs. 2211 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2212 ++Idx; 2213 2214 // If there are add operands they would be next. 2215 if (Idx < Ops.size()) { 2216 bool DeletedAdd = false; 2217 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2218 // If we have an add, expand the add operands onto the end of the operands 2219 // list. 2220 Ops.erase(Ops.begin()+Idx); 2221 Ops.append(Add->op_begin(), Add->op_end()); 2222 DeletedAdd = true; 2223 } 2224 2225 // If we deleted at least one add, we added operands to the end of the list, 2226 // and they are not necessarily sorted. Recurse to resort and resimplify 2227 // any operands we just acquired. 2228 if (DeletedAdd) 2229 return getAddExpr(Ops); 2230 } 2231 2232 // Skip over the add expression until we get to a multiply. 2233 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2234 ++Idx; 2235 2236 // Check to see if there are any folding opportunities present with 2237 // operands multiplied by constant values. 2238 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2239 uint64_t BitWidth = getTypeSizeInBits(Ty); 2240 DenseMap<const SCEV *, APInt> M; 2241 SmallVector<const SCEV *, 8> NewOps; 2242 APInt AccumulatedConstant(BitWidth, 0); 2243 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2244 Ops.data(), Ops.size(), 2245 APInt(BitWidth, 1), *this)) { 2246 struct APIntCompare { 2247 bool operator()(const APInt &LHS, const APInt &RHS) const { 2248 return LHS.ult(RHS); 2249 } 2250 }; 2251 2252 // Some interesting folding opportunity is present, so its worthwhile to 2253 // re-generate the operands list. Group the operands by constant scale, 2254 // to avoid multiplying by the same constant scale multiple times. 2255 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2256 for (const SCEV *NewOp : NewOps) 2257 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2258 // Re-generate the operands list. 2259 Ops.clear(); 2260 if (AccumulatedConstant != 0) 2261 Ops.push_back(getConstant(AccumulatedConstant)); 2262 for (auto &MulOp : MulOpLists) 2263 if (MulOp.first != 0) 2264 Ops.push_back(getMulExpr(getConstant(MulOp.first), 2265 getAddExpr(MulOp.second))); 2266 if (Ops.empty()) 2267 return getZero(Ty); 2268 if (Ops.size() == 1) 2269 return Ops[0]; 2270 return getAddExpr(Ops); 2271 } 2272 } 2273 2274 // If we are adding something to a multiply expression, make sure the 2275 // something is not already an operand of the multiply. If so, merge it into 2276 // the multiply. 2277 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2278 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2279 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2280 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2281 if (isa<SCEVConstant>(MulOpSCEV)) 2282 continue; 2283 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2284 if (MulOpSCEV == Ops[AddOp]) { 2285 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2286 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2287 if (Mul->getNumOperands() != 2) { 2288 // If the multiply has more than two operands, we must get the 2289 // Y*Z term. 2290 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2291 Mul->op_begin()+MulOp); 2292 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2293 InnerMul = getMulExpr(MulOps); 2294 } 2295 const SCEV *One = getOne(Ty); 2296 const SCEV *AddOne = getAddExpr(One, InnerMul); 2297 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); 2298 if (Ops.size() == 2) return OuterMul; 2299 if (AddOp < Idx) { 2300 Ops.erase(Ops.begin()+AddOp); 2301 Ops.erase(Ops.begin()+Idx-1); 2302 } else { 2303 Ops.erase(Ops.begin()+Idx); 2304 Ops.erase(Ops.begin()+AddOp-1); 2305 } 2306 Ops.push_back(OuterMul); 2307 return getAddExpr(Ops); 2308 } 2309 2310 // Check this multiply against other multiplies being added together. 2311 for (unsigned OtherMulIdx = Idx+1; 2312 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2313 ++OtherMulIdx) { 2314 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2315 // If MulOp occurs in OtherMul, we can fold the two multiplies 2316 // together. 2317 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2318 OMulOp != e; ++OMulOp) 2319 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2320 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2321 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2322 if (Mul->getNumOperands() != 2) { 2323 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2324 Mul->op_begin()+MulOp); 2325 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2326 InnerMul1 = getMulExpr(MulOps); 2327 } 2328 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2329 if (OtherMul->getNumOperands() != 2) { 2330 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2331 OtherMul->op_begin()+OMulOp); 2332 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2333 InnerMul2 = getMulExpr(MulOps); 2334 } 2335 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2); 2336 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); 2337 if (Ops.size() == 2) return OuterMul; 2338 Ops.erase(Ops.begin()+Idx); 2339 Ops.erase(Ops.begin()+OtherMulIdx-1); 2340 Ops.push_back(OuterMul); 2341 return getAddExpr(Ops); 2342 } 2343 } 2344 } 2345 } 2346 2347 // If there are any add recurrences in the operands list, see if any other 2348 // added values are loop invariant. If so, we can fold them into the 2349 // recurrence. 2350 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2351 ++Idx; 2352 2353 // Scan over all recurrences, trying to fold loop invariants into them. 2354 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2355 // Scan all of the other operands to this add and add them to the vector if 2356 // they are loop invariant w.r.t. the recurrence. 2357 SmallVector<const SCEV *, 8> LIOps; 2358 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2359 const Loop *AddRecLoop = AddRec->getLoop(); 2360 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2361 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2362 LIOps.push_back(Ops[i]); 2363 Ops.erase(Ops.begin()+i); 2364 --i; --e; 2365 } 2366 2367 // If we found some loop invariants, fold them into the recurrence. 2368 if (!LIOps.empty()) { 2369 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2370 LIOps.push_back(AddRec->getStart()); 2371 2372 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2373 AddRec->op_end()); 2374 // This follows from the fact that the no-wrap flags on the outer add 2375 // expression are applicable on the 0th iteration, when the add recurrence 2376 // will be equal to its start value. 2377 AddRecOps[0] = getAddExpr(LIOps, Flags); 2378 2379 // Build the new addrec. Propagate the NUW and NSW flags if both the 2380 // outer add and the inner addrec are guaranteed to have no overflow. 2381 // Always propagate NW. 2382 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2383 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2384 2385 // If all of the other operands were loop invariant, we are done. 2386 if (Ops.size() == 1) return NewRec; 2387 2388 // Otherwise, add the folded AddRec by the non-invariant parts. 2389 for (unsigned i = 0;; ++i) 2390 if (Ops[i] == AddRec) { 2391 Ops[i] = NewRec; 2392 break; 2393 } 2394 return getAddExpr(Ops); 2395 } 2396 2397 // Okay, if there weren't any loop invariants to be folded, check to see if 2398 // there are multiple AddRec's with the same loop induction variable being 2399 // added together. If so, we can fold them. 2400 for (unsigned OtherIdx = Idx+1; 2401 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2402 ++OtherIdx) 2403 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2404 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2405 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2406 AddRec->op_end()); 2407 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2408 ++OtherIdx) 2409 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) 2410 if (OtherAddRec->getLoop() == AddRecLoop) { 2411 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2412 i != e; ++i) { 2413 if (i >= AddRecOps.size()) { 2414 AddRecOps.append(OtherAddRec->op_begin()+i, 2415 OtherAddRec->op_end()); 2416 break; 2417 } 2418 AddRecOps[i] = getAddExpr(AddRecOps[i], 2419 OtherAddRec->getOperand(i)); 2420 } 2421 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2422 } 2423 // Step size has changed, so we cannot guarantee no self-wraparound. 2424 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2425 return getAddExpr(Ops); 2426 } 2427 2428 // Otherwise couldn't fold anything into this recurrence. Move onto the 2429 // next one. 2430 } 2431 2432 // Okay, it looks like we really DO need an add expr. Check to see if we 2433 // already have one, otherwise create a new one. 2434 FoldingSetNodeID ID; 2435 ID.AddInteger(scAddExpr); 2436 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2437 ID.AddPointer(Ops[i]); 2438 void *IP = nullptr; 2439 SCEVAddExpr *S = 2440 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2441 if (!S) { 2442 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2443 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2444 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator), 2445 O, Ops.size()); 2446 UniqueSCEVs.InsertNode(S, IP); 2447 } 2448 S->setNoWrapFlags(Flags); 2449 return S; 2450 } 2451 2452 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2453 uint64_t k = i*j; 2454 if (j > 1 && k / j != i) Overflow = true; 2455 return k; 2456 } 2457 2458 /// Compute the result of "n choose k", the binomial coefficient. If an 2459 /// intermediate computation overflows, Overflow will be set and the return will 2460 /// be garbage. Overflow is not cleared on absence of overflow. 2461 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2462 // We use the multiplicative formula: 2463 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2464 // At each iteration, we take the n-th term of the numeral and divide by the 2465 // (k-n)th term of the denominator. This division will always produce an 2466 // integral result, and helps reduce the chance of overflow in the 2467 // intermediate computations. However, we can still overflow even when the 2468 // final result would fit. 2469 2470 if (n == 0 || n == k) return 1; 2471 if (k > n) return 0; 2472 2473 if (k > n/2) 2474 k = n-k; 2475 2476 uint64_t r = 1; 2477 for (uint64_t i = 1; i <= k; ++i) { 2478 r = umul_ov(r, n-(i-1), Overflow); 2479 r /= i; 2480 } 2481 return r; 2482 } 2483 2484 /// Determine if any of the operands in this SCEV are a constant or if 2485 /// any of the add or multiply expressions in this SCEV contain a constant. 2486 static bool containsConstantSomewhere(const SCEV *StartExpr) { 2487 SmallVector<const SCEV *, 4> Ops; 2488 Ops.push_back(StartExpr); 2489 while (!Ops.empty()) { 2490 const SCEV *CurrentExpr = Ops.pop_back_val(); 2491 if (isa<SCEVConstant>(*CurrentExpr)) 2492 return true; 2493 2494 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { 2495 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); 2496 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); 2497 } 2498 } 2499 return false; 2500 } 2501 2502 /// Get a canonical multiply expression, or something simpler if possible. 2503 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2504 SCEV::NoWrapFlags Flags) { 2505 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2506 "only nuw or nsw allowed"); 2507 assert(!Ops.empty() && "Cannot get empty mul!"); 2508 if (Ops.size() == 1) return Ops[0]; 2509 #ifndef NDEBUG 2510 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2511 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2512 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2513 "SCEVMulExpr operand types don't match!"); 2514 #endif 2515 2516 // Sort by complexity, this groups all similar expression types together. 2517 GroupByComplexity(Ops, &LI); 2518 2519 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2520 2521 // If there are any constants, fold them together. 2522 unsigned Idx = 0; 2523 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2524 2525 // C1*(C2+V) -> C1*C2 + C1*V 2526 if (Ops.size() == 2) 2527 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2528 // If any of Add's ops are Adds or Muls with a constant, 2529 // apply this transformation as well. 2530 if (Add->getNumOperands() == 2) 2531 if (containsConstantSomewhere(Add)) 2532 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), 2533 getMulExpr(LHSC, Add->getOperand(1))); 2534 2535 ++Idx; 2536 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2537 // We found two constants, fold them together! 2538 ConstantInt *Fold = 2539 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2540 Ops[0] = getConstant(Fold); 2541 Ops.erase(Ops.begin()+1); // Erase the folded element 2542 if (Ops.size() == 1) return Ops[0]; 2543 LHSC = cast<SCEVConstant>(Ops[0]); 2544 } 2545 2546 // If we are left with a constant one being multiplied, strip it off. 2547 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 2548 Ops.erase(Ops.begin()); 2549 --Idx; 2550 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2551 // If we have a multiply of zero, it will always be zero. 2552 return Ops[0]; 2553 } else if (Ops[0]->isAllOnesValue()) { 2554 // If we have a mul by -1 of an add, try distributing the -1 among the 2555 // add operands. 2556 if (Ops.size() == 2) { 2557 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2558 SmallVector<const SCEV *, 4> NewOps; 2559 bool AnyFolded = false; 2560 for (const SCEV *AddOp : Add->operands()) { 2561 const SCEV *Mul = getMulExpr(Ops[0], AddOp); 2562 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2563 NewOps.push_back(Mul); 2564 } 2565 if (AnyFolded) 2566 return getAddExpr(NewOps); 2567 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2568 // Negation preserves a recurrence's no self-wrap property. 2569 SmallVector<const SCEV *, 4> Operands; 2570 for (const SCEV *AddRecOp : AddRec->operands()) 2571 Operands.push_back(getMulExpr(Ops[0], AddRecOp)); 2572 2573 return getAddRecExpr(Operands, AddRec->getLoop(), 2574 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2575 } 2576 } 2577 } 2578 2579 if (Ops.size() == 1) 2580 return Ops[0]; 2581 } 2582 2583 // Skip over the add expression until we get to a multiply. 2584 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2585 ++Idx; 2586 2587 // If there are mul operands inline them all into this expression. 2588 if (Idx < Ops.size()) { 2589 bool DeletedMul = false; 2590 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2591 if (Ops.size() > MulOpsInlineThreshold) 2592 break; 2593 // If we have an mul, expand the mul operands onto the end of the operands 2594 // list. 2595 Ops.erase(Ops.begin()+Idx); 2596 Ops.append(Mul->op_begin(), Mul->op_end()); 2597 DeletedMul = true; 2598 } 2599 2600 // If we deleted at least one mul, we added operands to the end of the list, 2601 // and they are not necessarily sorted. Recurse to resort and resimplify 2602 // any operands we just acquired. 2603 if (DeletedMul) 2604 return getMulExpr(Ops); 2605 } 2606 2607 // If there are any add recurrences in the operands list, see if any other 2608 // added values are loop invariant. If so, we can fold them into the 2609 // recurrence. 2610 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2611 ++Idx; 2612 2613 // Scan over all recurrences, trying to fold loop invariants into them. 2614 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2615 // Scan all of the other operands to this mul and add them to the vector if 2616 // they are loop invariant w.r.t. the recurrence. 2617 SmallVector<const SCEV *, 8> LIOps; 2618 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2619 const Loop *AddRecLoop = AddRec->getLoop(); 2620 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2621 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2622 LIOps.push_back(Ops[i]); 2623 Ops.erase(Ops.begin()+i); 2624 --i; --e; 2625 } 2626 2627 // If we found some loop invariants, fold them into the recurrence. 2628 if (!LIOps.empty()) { 2629 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2630 SmallVector<const SCEV *, 4> NewOps; 2631 NewOps.reserve(AddRec->getNumOperands()); 2632 const SCEV *Scale = getMulExpr(LIOps); 2633 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2634 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); 2635 2636 // Build the new addrec. Propagate the NUW and NSW flags if both the 2637 // outer mul and the inner addrec are guaranteed to have no overflow. 2638 // 2639 // No self-wrap cannot be guaranteed after changing the step size, but 2640 // will be inferred if either NUW or NSW is true. 2641 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2642 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2643 2644 // If all of the other operands were loop invariant, we are done. 2645 if (Ops.size() == 1) return NewRec; 2646 2647 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2648 for (unsigned i = 0;; ++i) 2649 if (Ops[i] == AddRec) { 2650 Ops[i] = NewRec; 2651 break; 2652 } 2653 return getMulExpr(Ops); 2654 } 2655 2656 // Okay, if there weren't any loop invariants to be folded, check to see if 2657 // there are multiple AddRec's with the same loop induction variable being 2658 // multiplied together. If so, we can fold them. 2659 2660 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2661 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2662 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2663 // ]]],+,...up to x=2n}. 2664 // Note that the arguments to choose() are always integers with values 2665 // known at compile time, never SCEV objects. 2666 // 2667 // The implementation avoids pointless extra computations when the two 2668 // addrec's are of different length (mathematically, it's equivalent to 2669 // an infinite stream of zeros on the right). 2670 bool OpsModified = false; 2671 for (unsigned OtherIdx = Idx+1; 2672 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2673 ++OtherIdx) { 2674 const SCEVAddRecExpr *OtherAddRec = 2675 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2676 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2677 continue; 2678 2679 bool Overflow = false; 2680 Type *Ty = AddRec->getType(); 2681 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2682 SmallVector<const SCEV*, 7> AddRecOps; 2683 for (int x = 0, xe = AddRec->getNumOperands() + 2684 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2685 const SCEV *Term = getZero(Ty); 2686 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2687 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2688 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2689 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2690 z < ze && !Overflow; ++z) { 2691 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2692 uint64_t Coeff; 2693 if (LargerThan64Bits) 2694 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2695 else 2696 Coeff = Coeff1*Coeff2; 2697 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2698 const SCEV *Term1 = AddRec->getOperand(y-z); 2699 const SCEV *Term2 = OtherAddRec->getOperand(z); 2700 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); 2701 } 2702 } 2703 AddRecOps.push_back(Term); 2704 } 2705 if (!Overflow) { 2706 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2707 SCEV::FlagAnyWrap); 2708 if (Ops.size() == 2) return NewAddRec; 2709 Ops[Idx] = NewAddRec; 2710 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2711 OpsModified = true; 2712 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2713 if (!AddRec) 2714 break; 2715 } 2716 } 2717 if (OpsModified) 2718 return getMulExpr(Ops); 2719 2720 // Otherwise couldn't fold anything into this recurrence. Move onto the 2721 // next one. 2722 } 2723 2724 // Okay, it looks like we really DO need an mul expr. Check to see if we 2725 // already have one, otherwise create a new one. 2726 FoldingSetNodeID ID; 2727 ID.AddInteger(scMulExpr); 2728 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2729 ID.AddPointer(Ops[i]); 2730 void *IP = nullptr; 2731 SCEVMulExpr *S = 2732 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2733 if (!S) { 2734 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2735 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2736 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2737 O, Ops.size()); 2738 UniqueSCEVs.InsertNode(S, IP); 2739 } 2740 S->setNoWrapFlags(Flags); 2741 return S; 2742 } 2743 2744 /// Get a canonical unsigned division expression, or something simpler if 2745 /// possible. 2746 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2747 const SCEV *RHS) { 2748 assert(getEffectiveSCEVType(LHS->getType()) == 2749 getEffectiveSCEVType(RHS->getType()) && 2750 "SCEVUDivExpr operand types don't match!"); 2751 2752 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2753 if (RHSC->getValue()->equalsInt(1)) 2754 return LHS; // X udiv 1 --> x 2755 // If the denominator is zero, the result of the udiv is undefined. Don't 2756 // try to analyze it, because the resolution chosen here may differ from 2757 // the resolution chosen in other parts of the compiler. 2758 if (!RHSC->getValue()->isZero()) { 2759 // Determine if the division can be folded into the operands of 2760 // its operands. 2761 // TODO: Generalize this to non-constants by using known-bits information. 2762 Type *Ty = LHS->getType(); 2763 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 2764 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2765 // For non-power-of-two values, effectively round the value up to the 2766 // nearest power of two. 2767 if (!RHSC->getAPInt().isPowerOf2()) 2768 ++MaxShiftAmt; 2769 IntegerType *ExtTy = 2770 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2771 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2772 if (const SCEVConstant *Step = 2773 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2774 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2775 const APInt &StepInt = Step->getAPInt(); 2776 const APInt &DivInt = RHSC->getAPInt(); 2777 if (!StepInt.urem(DivInt) && 2778 getZeroExtendExpr(AR, ExtTy) == 2779 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2780 getZeroExtendExpr(Step, ExtTy), 2781 AR->getLoop(), SCEV::FlagAnyWrap)) { 2782 SmallVector<const SCEV *, 4> Operands; 2783 for (const SCEV *Op : AR->operands()) 2784 Operands.push_back(getUDivExpr(Op, RHS)); 2785 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 2786 } 2787 /// Get a canonical UDivExpr for a recurrence. 2788 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 2789 // We can currently only fold X%N if X is constant. 2790 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 2791 if (StartC && !DivInt.urem(StepInt) && 2792 getZeroExtendExpr(AR, ExtTy) == 2793 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2794 getZeroExtendExpr(Step, ExtTy), 2795 AR->getLoop(), SCEV::FlagAnyWrap)) { 2796 const APInt &StartInt = StartC->getAPInt(); 2797 const APInt &StartRem = StartInt.urem(StepInt); 2798 if (StartRem != 0) 2799 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 2800 AR->getLoop(), SCEV::FlagNW); 2801 } 2802 } 2803 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 2804 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 2805 SmallVector<const SCEV *, 4> Operands; 2806 for (const SCEV *Op : M->operands()) 2807 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2808 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 2809 // Find an operand that's safely divisible. 2810 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 2811 const SCEV *Op = M->getOperand(i); 2812 const SCEV *Div = getUDivExpr(Op, RHSC); 2813 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 2814 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 2815 M->op_end()); 2816 Operands[i] = Div; 2817 return getMulExpr(Operands); 2818 } 2819 } 2820 } 2821 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 2822 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 2823 SmallVector<const SCEV *, 4> Operands; 2824 for (const SCEV *Op : A->operands()) 2825 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2826 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 2827 Operands.clear(); 2828 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 2829 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 2830 if (isa<SCEVUDivExpr>(Op) || 2831 getMulExpr(Op, RHS) != A->getOperand(i)) 2832 break; 2833 Operands.push_back(Op); 2834 } 2835 if (Operands.size() == A->getNumOperands()) 2836 return getAddExpr(Operands); 2837 } 2838 } 2839 2840 // Fold if both operands are constant. 2841 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 2842 Constant *LHSCV = LHSC->getValue(); 2843 Constant *RHSCV = RHSC->getValue(); 2844 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 2845 RHSCV))); 2846 } 2847 } 2848 } 2849 2850 FoldingSetNodeID ID; 2851 ID.AddInteger(scUDivExpr); 2852 ID.AddPointer(LHS); 2853 ID.AddPointer(RHS); 2854 void *IP = nullptr; 2855 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2856 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 2857 LHS, RHS); 2858 UniqueSCEVs.InsertNode(S, IP); 2859 return S; 2860 } 2861 2862 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 2863 APInt A = C1->getAPInt().abs(); 2864 APInt B = C2->getAPInt().abs(); 2865 uint32_t ABW = A.getBitWidth(); 2866 uint32_t BBW = B.getBitWidth(); 2867 2868 if (ABW > BBW) 2869 B = B.zext(ABW); 2870 else if (ABW < BBW) 2871 A = A.zext(BBW); 2872 2873 return APIntOps::GreatestCommonDivisor(A, B); 2874 } 2875 2876 /// Get a canonical unsigned division expression, or something simpler if 2877 /// possible. There is no representation for an exact udiv in SCEV IR, but we 2878 /// can attempt to remove factors from the LHS and RHS. We can't do this when 2879 /// it's not exact because the udiv may be clearing bits. 2880 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 2881 const SCEV *RHS) { 2882 // TODO: we could try to find factors in all sorts of things, but for now we 2883 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 2884 // end of this file for inspiration. 2885 2886 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 2887 if (!Mul) 2888 return getUDivExpr(LHS, RHS); 2889 2890 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 2891 // If the mulexpr multiplies by a constant, then that constant must be the 2892 // first element of the mulexpr. 2893 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 2894 if (LHSCst == RHSCst) { 2895 SmallVector<const SCEV *, 2> Operands; 2896 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2897 return getMulExpr(Operands); 2898 } 2899 2900 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 2901 // that there's a factor provided by one of the other terms. We need to 2902 // check. 2903 APInt Factor = gcd(LHSCst, RHSCst); 2904 if (!Factor.isIntN(1)) { 2905 LHSCst = 2906 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 2907 RHSCst = 2908 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 2909 SmallVector<const SCEV *, 2> Operands; 2910 Operands.push_back(LHSCst); 2911 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2912 LHS = getMulExpr(Operands); 2913 RHS = RHSCst; 2914 Mul = dyn_cast<SCEVMulExpr>(LHS); 2915 if (!Mul) 2916 return getUDivExactExpr(LHS, RHS); 2917 } 2918 } 2919 } 2920 2921 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 2922 if (Mul->getOperand(i) == RHS) { 2923 SmallVector<const SCEV *, 2> Operands; 2924 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 2925 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 2926 return getMulExpr(Operands); 2927 } 2928 } 2929 2930 return getUDivExpr(LHS, RHS); 2931 } 2932 2933 /// Get an add recurrence expression for the specified loop. Simplify the 2934 /// expression as much as possible. 2935 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 2936 const Loop *L, 2937 SCEV::NoWrapFlags Flags) { 2938 SmallVector<const SCEV *, 4> Operands; 2939 Operands.push_back(Start); 2940 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 2941 if (StepChrec->getLoop() == L) { 2942 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 2943 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 2944 } 2945 2946 Operands.push_back(Step); 2947 return getAddRecExpr(Operands, L, Flags); 2948 } 2949 2950 /// Get an add recurrence expression for the specified loop. Simplify the 2951 /// expression as much as possible. 2952 const SCEV * 2953 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 2954 const Loop *L, SCEV::NoWrapFlags Flags) { 2955 if (Operands.size() == 1) return Operands[0]; 2956 #ifndef NDEBUG 2957 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 2958 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 2959 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 2960 "SCEVAddRecExpr operand types don't match!"); 2961 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2962 assert(isLoopInvariant(Operands[i], L) && 2963 "SCEVAddRecExpr operand is not loop-invariant!"); 2964 #endif 2965 2966 if (Operands.back()->isZero()) { 2967 Operands.pop_back(); 2968 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 2969 } 2970 2971 // It's tempting to want to call getMaxBackedgeTakenCount count here and 2972 // use that information to infer NUW and NSW flags. However, computing a 2973 // BE count requires calling getAddRecExpr, so we may not yet have a 2974 // meaningful BE count at this point (and if we don't, we'd be stuck 2975 // with a SCEVCouldNotCompute as the cached BE count). 2976 2977 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 2978 2979 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 2980 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 2981 const Loop *NestedLoop = NestedAR->getLoop(); 2982 if (L->contains(NestedLoop) 2983 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 2984 : (!NestedLoop->contains(L) && 2985 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 2986 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 2987 NestedAR->op_end()); 2988 Operands[0] = NestedAR->getStart(); 2989 // AddRecs require their operands be loop-invariant with respect to their 2990 // loops. Don't perform this transformation if it would break this 2991 // requirement. 2992 bool AllInvariant = all_of( 2993 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 2994 2995 if (AllInvariant) { 2996 // Create a recurrence for the outer loop with the same step size. 2997 // 2998 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 2999 // inner recurrence has the same property. 3000 SCEV::NoWrapFlags OuterFlags = 3001 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3002 3003 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3004 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3005 return isLoopInvariant(Op, NestedLoop); 3006 }); 3007 3008 if (AllInvariant) { 3009 // Ok, both add recurrences are valid after the transformation. 3010 // 3011 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3012 // the outer recurrence has the same property. 3013 SCEV::NoWrapFlags InnerFlags = 3014 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3015 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3016 } 3017 } 3018 // Reset Operands to its original state. 3019 Operands[0] = NestedAR; 3020 } 3021 } 3022 3023 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3024 // already have one, otherwise create a new one. 3025 FoldingSetNodeID ID; 3026 ID.AddInteger(scAddRecExpr); 3027 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3028 ID.AddPointer(Operands[i]); 3029 ID.AddPointer(L); 3030 void *IP = nullptr; 3031 SCEVAddRecExpr *S = 3032 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 3033 if (!S) { 3034 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 3035 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 3036 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 3037 O, Operands.size(), L); 3038 UniqueSCEVs.InsertNode(S, IP); 3039 } 3040 S->setNoWrapFlags(Flags); 3041 return S; 3042 } 3043 3044 const SCEV * 3045 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3046 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3047 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3048 // getSCEV(Base)->getType() has the same address space as Base->getType() 3049 // because SCEV::getType() preserves the address space. 3050 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3051 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3052 // instruction to its SCEV, because the Instruction may be guarded by control 3053 // flow and the no-overflow bits may not be valid for the expression in any 3054 // context. This can be fixed similarly to how these flags are handled for 3055 // adds. 3056 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3057 : SCEV::FlagAnyWrap; 3058 3059 const SCEV *TotalOffset = getZero(IntPtrTy); 3060 // The array size is unimportant. The first thing we do on CurTy is getting 3061 // its element type. 3062 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3063 for (const SCEV *IndexExpr : IndexExprs) { 3064 // Compute the (potentially symbolic) offset in bytes for this index. 3065 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3066 // For a struct, add the member offset. 3067 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3068 unsigned FieldNo = Index->getZExtValue(); 3069 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3070 3071 // Add the field offset to the running total offset. 3072 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3073 3074 // Update CurTy to the type of the field at Index. 3075 CurTy = STy->getTypeAtIndex(Index); 3076 } else { 3077 // Update CurTy to its element type. 3078 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3079 // For an array, add the element offset, explicitly scaled. 3080 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3081 // Getelementptr indices are signed. 3082 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3083 3084 // Multiply the index by the element size to compute the element offset. 3085 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3086 3087 // Add the element offset to the running total offset. 3088 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3089 } 3090 } 3091 3092 // Add the total offset from all the GEP indices to the base. 3093 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3094 } 3095 3096 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3097 const SCEV *RHS) { 3098 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3099 return getSMaxExpr(Ops); 3100 } 3101 3102 const SCEV * 3103 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3104 assert(!Ops.empty() && "Cannot get empty smax!"); 3105 if (Ops.size() == 1) return Ops[0]; 3106 #ifndef NDEBUG 3107 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3108 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3109 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3110 "SCEVSMaxExpr operand types don't match!"); 3111 #endif 3112 3113 // Sort by complexity, this groups all similar expression types together. 3114 GroupByComplexity(Ops, &LI); 3115 3116 // If there are any constants, fold them together. 3117 unsigned Idx = 0; 3118 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3119 ++Idx; 3120 assert(Idx < Ops.size()); 3121 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3122 // We found two constants, fold them together! 3123 ConstantInt *Fold = ConstantInt::get( 3124 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3125 Ops[0] = getConstant(Fold); 3126 Ops.erase(Ops.begin()+1); // Erase the folded element 3127 if (Ops.size() == 1) return Ops[0]; 3128 LHSC = cast<SCEVConstant>(Ops[0]); 3129 } 3130 3131 // If we are left with a constant minimum-int, strip it off. 3132 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3133 Ops.erase(Ops.begin()); 3134 --Idx; 3135 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3136 // If we have an smax with a constant maximum-int, it will always be 3137 // maximum-int. 3138 return Ops[0]; 3139 } 3140 3141 if (Ops.size() == 1) return Ops[0]; 3142 } 3143 3144 // Find the first SMax 3145 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3146 ++Idx; 3147 3148 // Check to see if one of the operands is an SMax. If so, expand its operands 3149 // onto our operand list, and recurse to simplify. 3150 if (Idx < Ops.size()) { 3151 bool DeletedSMax = false; 3152 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3153 Ops.erase(Ops.begin()+Idx); 3154 Ops.append(SMax->op_begin(), SMax->op_end()); 3155 DeletedSMax = true; 3156 } 3157 3158 if (DeletedSMax) 3159 return getSMaxExpr(Ops); 3160 } 3161 3162 // Okay, check to see if the same value occurs in the operand list twice. If 3163 // so, delete one. Since we sorted the list, these values are required to 3164 // be adjacent. 3165 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3166 // X smax Y smax Y --> X smax Y 3167 // X smax Y --> X, if X is always greater than Y 3168 if (Ops[i] == Ops[i+1] || 3169 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3170 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3171 --i; --e; 3172 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3173 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3174 --i; --e; 3175 } 3176 3177 if (Ops.size() == 1) return Ops[0]; 3178 3179 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3180 3181 // Okay, it looks like we really DO need an smax expr. Check to see if we 3182 // already have one, otherwise create a new one. 3183 FoldingSetNodeID ID; 3184 ID.AddInteger(scSMaxExpr); 3185 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3186 ID.AddPointer(Ops[i]); 3187 void *IP = nullptr; 3188 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3189 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3190 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3191 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3192 O, Ops.size()); 3193 UniqueSCEVs.InsertNode(S, IP); 3194 return S; 3195 } 3196 3197 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3198 const SCEV *RHS) { 3199 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3200 return getUMaxExpr(Ops); 3201 } 3202 3203 const SCEV * 3204 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3205 assert(!Ops.empty() && "Cannot get empty umax!"); 3206 if (Ops.size() == 1) return Ops[0]; 3207 #ifndef NDEBUG 3208 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3209 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3210 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3211 "SCEVUMaxExpr operand types don't match!"); 3212 #endif 3213 3214 // Sort by complexity, this groups all similar expression types together. 3215 GroupByComplexity(Ops, &LI); 3216 3217 // If there are any constants, fold them together. 3218 unsigned Idx = 0; 3219 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3220 ++Idx; 3221 assert(Idx < Ops.size()); 3222 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3223 // We found two constants, fold them together! 3224 ConstantInt *Fold = ConstantInt::get( 3225 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3226 Ops[0] = getConstant(Fold); 3227 Ops.erase(Ops.begin()+1); // Erase the folded element 3228 if (Ops.size() == 1) return Ops[0]; 3229 LHSC = cast<SCEVConstant>(Ops[0]); 3230 } 3231 3232 // If we are left with a constant minimum-int, strip it off. 3233 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3234 Ops.erase(Ops.begin()); 3235 --Idx; 3236 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3237 // If we have an umax with a constant maximum-int, it will always be 3238 // maximum-int. 3239 return Ops[0]; 3240 } 3241 3242 if (Ops.size() == 1) return Ops[0]; 3243 } 3244 3245 // Find the first UMax 3246 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3247 ++Idx; 3248 3249 // Check to see if one of the operands is a UMax. If so, expand its operands 3250 // onto our operand list, and recurse to simplify. 3251 if (Idx < Ops.size()) { 3252 bool DeletedUMax = false; 3253 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3254 Ops.erase(Ops.begin()+Idx); 3255 Ops.append(UMax->op_begin(), UMax->op_end()); 3256 DeletedUMax = true; 3257 } 3258 3259 if (DeletedUMax) 3260 return getUMaxExpr(Ops); 3261 } 3262 3263 // Okay, check to see if the same value occurs in the operand list twice. If 3264 // so, delete one. Since we sorted the list, these values are required to 3265 // be adjacent. 3266 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3267 // X umax Y umax Y --> X umax Y 3268 // X umax Y --> X, if X is always greater than Y 3269 if (Ops[i] == Ops[i+1] || 3270 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3271 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3272 --i; --e; 3273 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3274 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3275 --i; --e; 3276 } 3277 3278 if (Ops.size() == 1) return Ops[0]; 3279 3280 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3281 3282 // Okay, it looks like we really DO need a umax expr. Check to see if we 3283 // already have one, otherwise create a new one. 3284 FoldingSetNodeID ID; 3285 ID.AddInteger(scUMaxExpr); 3286 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3287 ID.AddPointer(Ops[i]); 3288 void *IP = nullptr; 3289 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3290 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3291 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3292 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3293 O, Ops.size()); 3294 UniqueSCEVs.InsertNode(S, IP); 3295 return S; 3296 } 3297 3298 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3299 const SCEV *RHS) { 3300 // ~smax(~x, ~y) == smin(x, y). 3301 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3302 } 3303 3304 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3305 const SCEV *RHS) { 3306 // ~umax(~x, ~y) == umin(x, y) 3307 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3308 } 3309 3310 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3311 // We can bypass creating a target-independent 3312 // constant expression and then folding it back into a ConstantInt. 3313 // This is just a compile-time optimization. 3314 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3315 } 3316 3317 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3318 StructType *STy, 3319 unsigned FieldNo) { 3320 // We can bypass creating a target-independent 3321 // constant expression and then folding it back into a ConstantInt. 3322 // This is just a compile-time optimization. 3323 return getConstant( 3324 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3325 } 3326 3327 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3328 // Don't attempt to do anything other than create a SCEVUnknown object 3329 // here. createSCEV only calls getUnknown after checking for all other 3330 // interesting possibilities, and any other code that calls getUnknown 3331 // is doing so in order to hide a value from SCEV canonicalization. 3332 3333 FoldingSetNodeID ID; 3334 ID.AddInteger(scUnknown); 3335 ID.AddPointer(V); 3336 void *IP = nullptr; 3337 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3338 assert(cast<SCEVUnknown>(S)->getValue() == V && 3339 "Stale SCEVUnknown in uniquing map!"); 3340 return S; 3341 } 3342 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3343 FirstUnknown); 3344 FirstUnknown = cast<SCEVUnknown>(S); 3345 UniqueSCEVs.InsertNode(S, IP); 3346 return S; 3347 } 3348 3349 //===----------------------------------------------------------------------===// 3350 // Basic SCEV Analysis and PHI Idiom Recognition Code 3351 // 3352 3353 /// Test if values of the given type are analyzable within the SCEV 3354 /// framework. This primarily includes integer types, and it can optionally 3355 /// include pointer types if the ScalarEvolution class has access to 3356 /// target-specific information. 3357 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3358 // Integers and pointers are always SCEVable. 3359 return Ty->isIntegerTy() || Ty->isPointerTy(); 3360 } 3361 3362 /// Return the size in bits of the specified type, for which isSCEVable must 3363 /// return true. 3364 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3365 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3366 return getDataLayout().getTypeSizeInBits(Ty); 3367 } 3368 3369 /// Return a type with the same bitwidth as the given type and which represents 3370 /// how SCEV will treat the given type, for which isSCEVable must return 3371 /// true. For pointer types, this is the pointer-sized integer type. 3372 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3373 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3374 3375 if (Ty->isIntegerTy()) 3376 return Ty; 3377 3378 // The only other support type is pointer. 3379 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3380 return getDataLayout().getIntPtrType(Ty); 3381 } 3382 3383 const SCEV *ScalarEvolution::getCouldNotCompute() { 3384 return CouldNotCompute.get(); 3385 } 3386 3387 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3388 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3389 auto *SU = dyn_cast<SCEVUnknown>(S); 3390 return SU && SU->getValue() == nullptr; 3391 }); 3392 3393 return !ContainsNulls; 3394 } 3395 3396 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3397 HasRecMapType::iterator I = HasRecMap.find(S); 3398 if (I != HasRecMap.end()) 3399 return I->second; 3400 3401 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3402 HasRecMap.insert({S, FoundAddRec}); 3403 return FoundAddRec; 3404 } 3405 3406 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3407 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3408 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3409 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3410 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3411 if (!Add) 3412 return {S, nullptr}; 3413 3414 if (Add->getNumOperands() != 2) 3415 return {S, nullptr}; 3416 3417 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3418 if (!ConstOp) 3419 return {S, nullptr}; 3420 3421 return {Add->getOperand(1), ConstOp->getValue()}; 3422 } 3423 3424 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3425 /// by the value and offset from any ValueOffsetPair in the set. 3426 SetVector<ScalarEvolution::ValueOffsetPair> * 3427 ScalarEvolution::getSCEVValues(const SCEV *S) { 3428 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3429 if (SI == ExprValueMap.end()) 3430 return nullptr; 3431 #ifndef NDEBUG 3432 if (VerifySCEVMap) { 3433 // Check there is no dangling Value in the set returned. 3434 for (const auto &VE : SI->second) 3435 assert(ValueExprMap.count(VE.first)); 3436 } 3437 #endif 3438 return &SI->second; 3439 } 3440 3441 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3442 /// cannot be used separately. eraseValueFromMap should be used to remove 3443 /// V from ValueExprMap and ExprValueMap at the same time. 3444 void ScalarEvolution::eraseValueFromMap(Value *V) { 3445 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3446 if (I != ValueExprMap.end()) { 3447 const SCEV *S = I->second; 3448 // Remove {V, 0} from the set of ExprValueMap[S] 3449 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3450 SV->remove({V, nullptr}); 3451 3452 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3453 const SCEV *Stripped; 3454 ConstantInt *Offset; 3455 std::tie(Stripped, Offset) = splitAddExpr(S); 3456 if (Offset != nullptr) { 3457 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3458 SV->remove({V, Offset}); 3459 } 3460 ValueExprMap.erase(V); 3461 } 3462 } 3463 3464 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3465 /// create a new one. 3466 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3467 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3468 3469 const SCEV *S = getExistingSCEV(V); 3470 if (S == nullptr) { 3471 S = createSCEV(V); 3472 // During PHI resolution, it is possible to create two SCEVs for the same 3473 // V, so it is needed to double check whether V->S is inserted into 3474 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3475 std::pair<ValueExprMapType::iterator, bool> Pair = 3476 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3477 if (Pair.second) { 3478 ExprValueMap[S].insert({V, nullptr}); 3479 3480 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3481 // ExprValueMap. 3482 const SCEV *Stripped = S; 3483 ConstantInt *Offset = nullptr; 3484 std::tie(Stripped, Offset) = splitAddExpr(S); 3485 // If stripped is SCEVUnknown, don't bother to save 3486 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3487 // increase the complexity of the expansion code. 3488 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3489 // because it may generate add/sub instead of GEP in SCEV expansion. 3490 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3491 !isa<GetElementPtrInst>(V)) 3492 ExprValueMap[Stripped].insert({V, Offset}); 3493 } 3494 } 3495 return S; 3496 } 3497 3498 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3499 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3500 3501 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3502 if (I != ValueExprMap.end()) { 3503 const SCEV *S = I->second; 3504 if (checkValidity(S)) 3505 return S; 3506 eraseValueFromMap(V); 3507 forgetMemoizedResults(S); 3508 } 3509 return nullptr; 3510 } 3511 3512 /// Return a SCEV corresponding to -V = -1*V 3513 /// 3514 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3515 SCEV::NoWrapFlags Flags) { 3516 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3517 return getConstant( 3518 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3519 3520 Type *Ty = V->getType(); 3521 Ty = getEffectiveSCEVType(Ty); 3522 return getMulExpr( 3523 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3524 } 3525 3526 /// Return a SCEV corresponding to ~V = -1-V 3527 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3528 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3529 return getConstant( 3530 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3531 3532 Type *Ty = V->getType(); 3533 Ty = getEffectiveSCEVType(Ty); 3534 const SCEV *AllOnes = 3535 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3536 return getMinusSCEV(AllOnes, V); 3537 } 3538 3539 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3540 SCEV::NoWrapFlags Flags) { 3541 // Fast path: X - X --> 0. 3542 if (LHS == RHS) 3543 return getZero(LHS->getType()); 3544 3545 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3546 // makes it so that we cannot make much use of NUW. 3547 auto AddFlags = SCEV::FlagAnyWrap; 3548 const bool RHSIsNotMinSigned = 3549 !getSignedRange(RHS).getSignedMin().isMinSignedValue(); 3550 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3551 // Let M be the minimum representable signed value. Then (-1)*RHS 3552 // signed-wraps if and only if RHS is M. That can happen even for 3553 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3554 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3555 // (-1)*RHS, we need to prove that RHS != M. 3556 // 3557 // If LHS is non-negative and we know that LHS - RHS does not 3558 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3559 // either by proving that RHS > M or that LHS >= 0. 3560 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3561 AddFlags = SCEV::FlagNSW; 3562 } 3563 } 3564 3565 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3566 // RHS is NSW and LHS >= 0. 3567 // 3568 // The difficulty here is that the NSW flag may have been proven 3569 // relative to a loop that is to be found in a recurrence in LHS and 3570 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3571 // larger scope than intended. 3572 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3573 3574 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); 3575 } 3576 3577 const SCEV * 3578 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3579 Type *SrcTy = V->getType(); 3580 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3581 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3582 "Cannot truncate or zero extend with non-integer arguments!"); 3583 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3584 return V; // No conversion 3585 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3586 return getTruncateExpr(V, Ty); 3587 return getZeroExtendExpr(V, Ty); 3588 } 3589 3590 const SCEV * 3591 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3592 Type *Ty) { 3593 Type *SrcTy = V->getType(); 3594 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3595 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3596 "Cannot truncate or zero extend with non-integer arguments!"); 3597 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3598 return V; // No conversion 3599 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3600 return getTruncateExpr(V, Ty); 3601 return getSignExtendExpr(V, Ty); 3602 } 3603 3604 const SCEV * 3605 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3606 Type *SrcTy = V->getType(); 3607 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3608 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3609 "Cannot noop or zero extend with non-integer arguments!"); 3610 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3611 "getNoopOrZeroExtend cannot truncate!"); 3612 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3613 return V; // No conversion 3614 return getZeroExtendExpr(V, Ty); 3615 } 3616 3617 const SCEV * 3618 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3619 Type *SrcTy = V->getType(); 3620 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3621 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3622 "Cannot noop or sign extend with non-integer arguments!"); 3623 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3624 "getNoopOrSignExtend cannot truncate!"); 3625 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3626 return V; // No conversion 3627 return getSignExtendExpr(V, Ty); 3628 } 3629 3630 const SCEV * 3631 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3632 Type *SrcTy = V->getType(); 3633 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3634 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3635 "Cannot noop or any extend with non-integer arguments!"); 3636 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3637 "getNoopOrAnyExtend cannot truncate!"); 3638 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3639 return V; // No conversion 3640 return getAnyExtendExpr(V, Ty); 3641 } 3642 3643 const SCEV * 3644 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3645 Type *SrcTy = V->getType(); 3646 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3647 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3648 "Cannot truncate or noop with non-integer arguments!"); 3649 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3650 "getTruncateOrNoop cannot extend!"); 3651 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3652 return V; // No conversion 3653 return getTruncateExpr(V, Ty); 3654 } 3655 3656 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3657 const SCEV *RHS) { 3658 const SCEV *PromotedLHS = LHS; 3659 const SCEV *PromotedRHS = RHS; 3660 3661 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3662 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3663 else 3664 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3665 3666 return getUMaxExpr(PromotedLHS, PromotedRHS); 3667 } 3668 3669 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3670 const SCEV *RHS) { 3671 const SCEV *PromotedLHS = LHS; 3672 const SCEV *PromotedRHS = RHS; 3673 3674 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3675 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3676 else 3677 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3678 3679 return getUMinExpr(PromotedLHS, PromotedRHS); 3680 } 3681 3682 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3683 // A pointer operand may evaluate to a nonpointer expression, such as null. 3684 if (!V->getType()->isPointerTy()) 3685 return V; 3686 3687 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3688 return getPointerBase(Cast->getOperand()); 3689 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3690 const SCEV *PtrOp = nullptr; 3691 for (const SCEV *NAryOp : NAry->operands()) { 3692 if (NAryOp->getType()->isPointerTy()) { 3693 // Cannot find the base of an expression with multiple pointer operands. 3694 if (PtrOp) 3695 return V; 3696 PtrOp = NAryOp; 3697 } 3698 } 3699 if (!PtrOp) 3700 return V; 3701 return getPointerBase(PtrOp); 3702 } 3703 return V; 3704 } 3705 3706 /// Push users of the given Instruction onto the given Worklist. 3707 static void 3708 PushDefUseChildren(Instruction *I, 3709 SmallVectorImpl<Instruction *> &Worklist) { 3710 // Push the def-use children onto the Worklist stack. 3711 for (User *U : I->users()) 3712 Worklist.push_back(cast<Instruction>(U)); 3713 } 3714 3715 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3716 SmallVector<Instruction *, 16> Worklist; 3717 PushDefUseChildren(PN, Worklist); 3718 3719 SmallPtrSet<Instruction *, 8> Visited; 3720 Visited.insert(PN); 3721 while (!Worklist.empty()) { 3722 Instruction *I = Worklist.pop_back_val(); 3723 if (!Visited.insert(I).second) 3724 continue; 3725 3726 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 3727 if (It != ValueExprMap.end()) { 3728 const SCEV *Old = It->second; 3729 3730 // Short-circuit the def-use traversal if the symbolic name 3731 // ceases to appear in expressions. 3732 if (Old != SymName && !hasOperand(Old, SymName)) 3733 continue; 3734 3735 // SCEVUnknown for a PHI either means that it has an unrecognized 3736 // structure, it's a PHI that's in the progress of being computed 3737 // by createNodeForPHI, or it's a single-value PHI. In the first case, 3738 // additional loop trip count information isn't going to change anything. 3739 // In the second case, createNodeForPHI will perform the necessary 3740 // updates on its own when it gets to that point. In the third, we do 3741 // want to forget the SCEVUnknown. 3742 if (!isa<PHINode>(I) || 3743 !isa<SCEVUnknown>(Old) || 3744 (I != PN && Old == SymName)) { 3745 eraseValueFromMap(It->first); 3746 forgetMemoizedResults(Old); 3747 } 3748 } 3749 3750 PushDefUseChildren(I, Worklist); 3751 } 3752 } 3753 3754 namespace { 3755 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 3756 public: 3757 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3758 ScalarEvolution &SE) { 3759 SCEVInitRewriter Rewriter(L, SE); 3760 const SCEV *Result = Rewriter.visit(S); 3761 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3762 } 3763 3764 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 3765 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3766 3767 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3768 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3769 Valid = false; 3770 return Expr; 3771 } 3772 3773 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3774 // Only allow AddRecExprs for this loop. 3775 if (Expr->getLoop() == L) 3776 return Expr->getStart(); 3777 Valid = false; 3778 return Expr; 3779 } 3780 3781 bool isValid() { return Valid; } 3782 3783 private: 3784 const Loop *L; 3785 bool Valid; 3786 }; 3787 3788 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 3789 public: 3790 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3791 ScalarEvolution &SE) { 3792 SCEVShiftRewriter Rewriter(L, SE); 3793 const SCEV *Result = Rewriter.visit(S); 3794 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3795 } 3796 3797 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 3798 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3799 3800 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3801 // Only allow AddRecExprs for this loop. 3802 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3803 Valid = false; 3804 return Expr; 3805 } 3806 3807 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3808 if (Expr->getLoop() == L && Expr->isAffine()) 3809 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 3810 Valid = false; 3811 return Expr; 3812 } 3813 bool isValid() { return Valid; } 3814 3815 private: 3816 const Loop *L; 3817 bool Valid; 3818 }; 3819 } // end anonymous namespace 3820 3821 SCEV::NoWrapFlags 3822 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 3823 if (!AR->isAffine()) 3824 return SCEV::FlagAnyWrap; 3825 3826 typedef OverflowingBinaryOperator OBO; 3827 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 3828 3829 if (!AR->hasNoSignedWrap()) { 3830 ConstantRange AddRecRange = getSignedRange(AR); 3831 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 3832 3833 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3834 Instruction::Add, IncRange, OBO::NoSignedWrap); 3835 if (NSWRegion.contains(AddRecRange)) 3836 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 3837 } 3838 3839 if (!AR->hasNoUnsignedWrap()) { 3840 ConstantRange AddRecRange = getUnsignedRange(AR); 3841 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 3842 3843 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3844 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 3845 if (NUWRegion.contains(AddRecRange)) 3846 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 3847 } 3848 3849 return Result; 3850 } 3851 3852 namespace { 3853 /// Represents an abstract binary operation. This may exist as a 3854 /// normal instruction or constant expression, or may have been 3855 /// derived from an expression tree. 3856 struct BinaryOp { 3857 unsigned Opcode; 3858 Value *LHS; 3859 Value *RHS; 3860 bool IsNSW; 3861 bool IsNUW; 3862 3863 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 3864 /// constant expression. 3865 Operator *Op; 3866 3867 explicit BinaryOp(Operator *Op) 3868 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 3869 IsNSW(false), IsNUW(false), Op(Op) { 3870 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 3871 IsNSW = OBO->hasNoSignedWrap(); 3872 IsNUW = OBO->hasNoUnsignedWrap(); 3873 } 3874 } 3875 3876 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 3877 bool IsNUW = false) 3878 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 3879 Op(nullptr) {} 3880 }; 3881 } 3882 3883 3884 /// Try to map \p V into a BinaryOp, and return \c None on failure. 3885 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 3886 auto *Op = dyn_cast<Operator>(V); 3887 if (!Op) 3888 return None; 3889 3890 // Implementation detail: all the cleverness here should happen without 3891 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 3892 // SCEV expressions when possible, and we should not break that. 3893 3894 switch (Op->getOpcode()) { 3895 case Instruction::Add: 3896 case Instruction::Sub: 3897 case Instruction::Mul: 3898 case Instruction::UDiv: 3899 case Instruction::And: 3900 case Instruction::Or: 3901 case Instruction::AShr: 3902 case Instruction::Shl: 3903 return BinaryOp(Op); 3904 3905 case Instruction::Xor: 3906 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 3907 // If the RHS of the xor is a signbit, then this is just an add. 3908 // Instcombine turns add of signbit into xor as a strength reduction step. 3909 if (RHSC->getValue().isSignBit()) 3910 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 3911 return BinaryOp(Op); 3912 3913 case Instruction::LShr: 3914 // Turn logical shift right of a constant into a unsigned divide. 3915 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 3916 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 3917 3918 // If the shift count is not less than the bitwidth, the result of 3919 // the shift is undefined. Don't try to analyze it, because the 3920 // resolution chosen here may differ from the resolution chosen in 3921 // other parts of the compiler. 3922 if (SA->getValue().ult(BitWidth)) { 3923 Constant *X = 3924 ConstantInt::get(SA->getContext(), 3925 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 3926 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 3927 } 3928 } 3929 return BinaryOp(Op); 3930 3931 case Instruction::ExtractValue: { 3932 auto *EVI = cast<ExtractValueInst>(Op); 3933 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 3934 break; 3935 3936 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 3937 if (!CI) 3938 break; 3939 3940 if (auto *F = CI->getCalledFunction()) 3941 switch (F->getIntrinsicID()) { 3942 case Intrinsic::sadd_with_overflow: 3943 case Intrinsic::uadd_with_overflow: { 3944 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 3945 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3946 CI->getArgOperand(1)); 3947 3948 // Now that we know that all uses of the arithmetic-result component of 3949 // CI are guarded by the overflow check, we can go ahead and pretend 3950 // that the arithmetic is non-overflowing. 3951 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 3952 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3953 CI->getArgOperand(1), /* IsNSW = */ true, 3954 /* IsNUW = */ false); 3955 else 3956 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3957 CI->getArgOperand(1), /* IsNSW = */ false, 3958 /* IsNUW*/ true); 3959 } 3960 3961 case Intrinsic::ssub_with_overflow: 3962 case Intrinsic::usub_with_overflow: 3963 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 3964 CI->getArgOperand(1)); 3965 3966 case Intrinsic::smul_with_overflow: 3967 case Intrinsic::umul_with_overflow: 3968 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 3969 CI->getArgOperand(1)); 3970 default: 3971 break; 3972 } 3973 } 3974 3975 default: 3976 break; 3977 } 3978 3979 return None; 3980 } 3981 3982 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 3983 const Loop *L = LI.getLoopFor(PN->getParent()); 3984 if (!L || L->getHeader() != PN->getParent()) 3985 return nullptr; 3986 3987 // The loop may have multiple entrances or multiple exits; we can analyze 3988 // this phi as an addrec if it has a unique entry value and a unique 3989 // backedge value. 3990 Value *BEValueV = nullptr, *StartValueV = nullptr; 3991 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 3992 Value *V = PN->getIncomingValue(i); 3993 if (L->contains(PN->getIncomingBlock(i))) { 3994 if (!BEValueV) { 3995 BEValueV = V; 3996 } else if (BEValueV != V) { 3997 BEValueV = nullptr; 3998 break; 3999 } 4000 } else if (!StartValueV) { 4001 StartValueV = V; 4002 } else if (StartValueV != V) { 4003 StartValueV = nullptr; 4004 break; 4005 } 4006 } 4007 if (BEValueV && StartValueV) { 4008 // While we are analyzing this PHI node, handle its value symbolically. 4009 const SCEV *SymbolicName = getUnknown(PN); 4010 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4011 "PHI node already processed?"); 4012 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4013 4014 // Using this symbolic name for the PHI, analyze the value coming around 4015 // the back-edge. 4016 const SCEV *BEValue = getSCEV(BEValueV); 4017 4018 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4019 // has a special value for the first iteration of the loop. 4020 4021 // If the value coming around the backedge is an add with the symbolic 4022 // value we just inserted, then we found a simple induction variable! 4023 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4024 // If there is a single occurrence of the symbolic value, replace it 4025 // with a recurrence. 4026 unsigned FoundIndex = Add->getNumOperands(); 4027 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4028 if (Add->getOperand(i) == SymbolicName) 4029 if (FoundIndex == e) { 4030 FoundIndex = i; 4031 break; 4032 } 4033 4034 if (FoundIndex != Add->getNumOperands()) { 4035 // Create an add with everything but the specified operand. 4036 SmallVector<const SCEV *, 8> Ops; 4037 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4038 if (i != FoundIndex) 4039 Ops.push_back(Add->getOperand(i)); 4040 const SCEV *Accum = getAddExpr(Ops); 4041 4042 // This is not a valid addrec if the step amount is varying each 4043 // loop iteration, but is not itself an addrec in this loop. 4044 if (isLoopInvariant(Accum, L) || 4045 (isa<SCEVAddRecExpr>(Accum) && 4046 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4047 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4048 4049 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4050 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4051 if (BO->IsNUW) 4052 Flags = setFlags(Flags, SCEV::FlagNUW); 4053 if (BO->IsNSW) 4054 Flags = setFlags(Flags, SCEV::FlagNSW); 4055 } 4056 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4057 // If the increment is an inbounds GEP, then we know the address 4058 // space cannot be wrapped around. We cannot make any guarantee 4059 // about signed or unsigned overflow because pointers are 4060 // unsigned but we may have a negative index from the base 4061 // pointer. We can guarantee that no unsigned wrap occurs if the 4062 // indices form a positive value. 4063 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4064 Flags = setFlags(Flags, SCEV::FlagNW); 4065 4066 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4067 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4068 Flags = setFlags(Flags, SCEV::FlagNUW); 4069 } 4070 4071 // We cannot transfer nuw and nsw flags from subtraction 4072 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4073 // for instance. 4074 } 4075 4076 const SCEV *StartVal = getSCEV(StartValueV); 4077 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4078 4079 // Okay, for the entire analysis of this edge we assumed the PHI 4080 // to be symbolic. We now need to go back and purge all of the 4081 // entries for the scalars that use the symbolic expression. 4082 forgetSymbolicName(PN, SymbolicName); 4083 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4084 4085 // We can add Flags to the post-inc expression only if we 4086 // know that it us *undefined behavior* for BEValueV to 4087 // overflow. 4088 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4089 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4090 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4091 4092 return PHISCEV; 4093 } 4094 } 4095 } else { 4096 // Otherwise, this could be a loop like this: 4097 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4098 // In this case, j = {1,+,1} and BEValue is j. 4099 // Because the other in-value of i (0) fits the evolution of BEValue 4100 // i really is an addrec evolution. 4101 // 4102 // We can generalize this saying that i is the shifted value of BEValue 4103 // by one iteration: 4104 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4105 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4106 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); 4107 if (Shifted != getCouldNotCompute() && 4108 Start != getCouldNotCompute()) { 4109 const SCEV *StartVal = getSCEV(StartValueV); 4110 if (Start == StartVal) { 4111 // Okay, for the entire analysis of this edge we assumed the PHI 4112 // to be symbolic. We now need to go back and purge all of the 4113 // entries for the scalars that use the symbolic expression. 4114 forgetSymbolicName(PN, SymbolicName); 4115 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4116 return Shifted; 4117 } 4118 } 4119 } 4120 4121 // Remove the temporary PHI node SCEV that has been inserted while intending 4122 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4123 // as it will prevent later (possibly simpler) SCEV expressions to be added 4124 // to the ValueExprMap. 4125 eraseValueFromMap(PN); 4126 } 4127 4128 return nullptr; 4129 } 4130 4131 // Checks if the SCEV S is available at BB. S is considered available at BB 4132 // if S can be materialized at BB without introducing a fault. 4133 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4134 BasicBlock *BB) { 4135 struct CheckAvailable { 4136 bool TraversalDone = false; 4137 bool Available = true; 4138 4139 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4140 BasicBlock *BB = nullptr; 4141 DominatorTree &DT; 4142 4143 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4144 : L(L), BB(BB), DT(DT) {} 4145 4146 bool setUnavailable() { 4147 TraversalDone = true; 4148 Available = false; 4149 return false; 4150 } 4151 4152 bool follow(const SCEV *S) { 4153 switch (S->getSCEVType()) { 4154 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 4155 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 4156 // These expressions are available if their operand(s) is/are. 4157 return true; 4158 4159 case scAddRecExpr: { 4160 // We allow add recurrences that are on the loop BB is in, or some 4161 // outer loop. This guarantees availability because the value of the 4162 // add recurrence at BB is simply the "current" value of the induction 4163 // variable. We can relax this in the future; for instance an add 4164 // recurrence on a sibling dominating loop is also available at BB. 4165 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 4166 if (L && (ARLoop == L || ARLoop->contains(L))) 4167 return true; 4168 4169 return setUnavailable(); 4170 } 4171 4172 case scUnknown: { 4173 // For SCEVUnknown, we check for simple dominance. 4174 const auto *SU = cast<SCEVUnknown>(S); 4175 Value *V = SU->getValue(); 4176 4177 if (isa<Argument>(V)) 4178 return false; 4179 4180 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 4181 return false; 4182 4183 return setUnavailable(); 4184 } 4185 4186 case scUDivExpr: 4187 case scCouldNotCompute: 4188 // We do not try to smart about these at all. 4189 return setUnavailable(); 4190 } 4191 llvm_unreachable("switch should be fully covered!"); 4192 } 4193 4194 bool isDone() { return TraversalDone; } 4195 }; 4196 4197 CheckAvailable CA(L, BB, DT); 4198 SCEVTraversal<CheckAvailable> ST(CA); 4199 4200 ST.visitAll(S); 4201 return CA.Available; 4202 } 4203 4204 // Try to match a control flow sequence that branches out at BI and merges back 4205 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 4206 // match. 4207 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 4208 Value *&C, Value *&LHS, Value *&RHS) { 4209 C = BI->getCondition(); 4210 4211 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 4212 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 4213 4214 if (!LeftEdge.isSingleEdge()) 4215 return false; 4216 4217 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 4218 4219 Use &LeftUse = Merge->getOperandUse(0); 4220 Use &RightUse = Merge->getOperandUse(1); 4221 4222 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 4223 LHS = LeftUse; 4224 RHS = RightUse; 4225 return true; 4226 } 4227 4228 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 4229 LHS = RightUse; 4230 RHS = LeftUse; 4231 return true; 4232 } 4233 4234 return false; 4235 } 4236 4237 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 4238 auto IsReachable = 4239 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 4240 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 4241 const Loop *L = LI.getLoopFor(PN->getParent()); 4242 4243 // We don't want to break LCSSA, even in a SCEV expression tree. 4244 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 4245 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 4246 return nullptr; 4247 4248 // Try to match 4249 // 4250 // br %cond, label %left, label %right 4251 // left: 4252 // br label %merge 4253 // right: 4254 // br label %merge 4255 // merge: 4256 // V = phi [ %x, %left ], [ %y, %right ] 4257 // 4258 // as "select %cond, %x, %y" 4259 4260 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 4261 assert(IDom && "At least the entry block should dominate PN"); 4262 4263 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 4264 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 4265 4266 if (BI && BI->isConditional() && 4267 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 4268 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 4269 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 4270 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 4271 } 4272 4273 return nullptr; 4274 } 4275 4276 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 4277 if (const SCEV *S = createAddRecFromPHI(PN)) 4278 return S; 4279 4280 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 4281 return S; 4282 4283 // If the PHI has a single incoming value, follow that value, unless the 4284 // PHI's incoming blocks are in a different loop, in which case doing so 4285 // risks breaking LCSSA form. Instcombine would normally zap these, but 4286 // it doesn't have DominatorTree information, so it may miss cases. 4287 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC)) 4288 if (LI.replacementPreservesLCSSAForm(PN, V)) 4289 return getSCEV(V); 4290 4291 // If it's not a loop phi, we can't handle it yet. 4292 return getUnknown(PN); 4293 } 4294 4295 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 4296 Value *Cond, 4297 Value *TrueVal, 4298 Value *FalseVal) { 4299 // Handle "constant" branch or select. This can occur for instance when a 4300 // loop pass transforms an inner loop and moves on to process the outer loop. 4301 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 4302 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 4303 4304 // Try to match some simple smax or umax patterns. 4305 auto *ICI = dyn_cast<ICmpInst>(Cond); 4306 if (!ICI) 4307 return getUnknown(I); 4308 4309 Value *LHS = ICI->getOperand(0); 4310 Value *RHS = ICI->getOperand(1); 4311 4312 switch (ICI->getPredicate()) { 4313 case ICmpInst::ICMP_SLT: 4314 case ICmpInst::ICMP_SLE: 4315 std::swap(LHS, RHS); 4316 LLVM_FALLTHROUGH; 4317 case ICmpInst::ICMP_SGT: 4318 case ICmpInst::ICMP_SGE: 4319 // a >s b ? a+x : b+x -> smax(a, b)+x 4320 // a >s b ? b+x : a+x -> smin(a, b)+x 4321 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4322 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 4323 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 4324 const SCEV *LA = getSCEV(TrueVal); 4325 const SCEV *RA = getSCEV(FalseVal); 4326 const SCEV *LDiff = getMinusSCEV(LA, LS); 4327 const SCEV *RDiff = getMinusSCEV(RA, RS); 4328 if (LDiff == RDiff) 4329 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 4330 LDiff = getMinusSCEV(LA, RS); 4331 RDiff = getMinusSCEV(RA, LS); 4332 if (LDiff == RDiff) 4333 return getAddExpr(getSMinExpr(LS, RS), LDiff); 4334 } 4335 break; 4336 case ICmpInst::ICMP_ULT: 4337 case ICmpInst::ICMP_ULE: 4338 std::swap(LHS, RHS); 4339 LLVM_FALLTHROUGH; 4340 case ICmpInst::ICMP_UGT: 4341 case ICmpInst::ICMP_UGE: 4342 // a >u b ? a+x : b+x -> umax(a, b)+x 4343 // a >u b ? b+x : a+x -> umin(a, b)+x 4344 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4345 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4346 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 4347 const SCEV *LA = getSCEV(TrueVal); 4348 const SCEV *RA = getSCEV(FalseVal); 4349 const SCEV *LDiff = getMinusSCEV(LA, LS); 4350 const SCEV *RDiff = getMinusSCEV(RA, RS); 4351 if (LDiff == RDiff) 4352 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 4353 LDiff = getMinusSCEV(LA, RS); 4354 RDiff = getMinusSCEV(RA, LS); 4355 if (LDiff == RDiff) 4356 return getAddExpr(getUMinExpr(LS, RS), LDiff); 4357 } 4358 break; 4359 case ICmpInst::ICMP_NE: 4360 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 4361 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4362 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4363 const SCEV *One = getOne(I->getType()); 4364 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4365 const SCEV *LA = getSCEV(TrueVal); 4366 const SCEV *RA = getSCEV(FalseVal); 4367 const SCEV *LDiff = getMinusSCEV(LA, LS); 4368 const SCEV *RDiff = getMinusSCEV(RA, One); 4369 if (LDiff == RDiff) 4370 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4371 } 4372 break; 4373 case ICmpInst::ICMP_EQ: 4374 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 4375 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4376 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4377 const SCEV *One = getOne(I->getType()); 4378 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4379 const SCEV *LA = getSCEV(TrueVal); 4380 const SCEV *RA = getSCEV(FalseVal); 4381 const SCEV *LDiff = getMinusSCEV(LA, One); 4382 const SCEV *RDiff = getMinusSCEV(RA, LS); 4383 if (LDiff == RDiff) 4384 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4385 } 4386 break; 4387 default: 4388 break; 4389 } 4390 4391 return getUnknown(I); 4392 } 4393 4394 /// Expand GEP instructions into add and multiply operations. This allows them 4395 /// to be analyzed by regular SCEV code. 4396 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 4397 // Don't attempt to analyze GEPs over unsized objects. 4398 if (!GEP->getSourceElementType()->isSized()) 4399 return getUnknown(GEP); 4400 4401 SmallVector<const SCEV *, 4> IndexExprs; 4402 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 4403 IndexExprs.push_back(getSCEV(*Index)); 4404 return getGEPExpr(GEP, IndexExprs); 4405 } 4406 4407 uint32_t 4408 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 4409 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4410 return C->getAPInt().countTrailingZeros(); 4411 4412 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 4413 return std::min(GetMinTrailingZeros(T->getOperand()), 4414 (uint32_t)getTypeSizeInBits(T->getType())); 4415 4416 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 4417 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4418 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 4419 getTypeSizeInBits(E->getType()) : OpRes; 4420 } 4421 4422 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 4423 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4424 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 4425 getTypeSizeInBits(E->getType()) : OpRes; 4426 } 4427 4428 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 4429 // The result is the min of all operands results. 4430 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4431 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4432 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4433 return MinOpRes; 4434 } 4435 4436 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 4437 // The result is the sum of all operands results. 4438 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 4439 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 4440 for (unsigned i = 1, e = M->getNumOperands(); 4441 SumOpRes != BitWidth && i != e; ++i) 4442 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), 4443 BitWidth); 4444 return SumOpRes; 4445 } 4446 4447 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 4448 // The result is the min of all operands results. 4449 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4450 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4451 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4452 return MinOpRes; 4453 } 4454 4455 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 4456 // The result is the min of all operands results. 4457 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4458 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4459 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4460 return MinOpRes; 4461 } 4462 4463 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 4464 // The result is the min of all operands results. 4465 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4466 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4467 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4468 return MinOpRes; 4469 } 4470 4471 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4472 // For a SCEVUnknown, ask ValueTracking. 4473 unsigned BitWidth = getTypeSizeInBits(U->getType()); 4474 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4475 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC, 4476 nullptr, &DT); 4477 return Zeros.countTrailingOnes(); 4478 } 4479 4480 // SCEVUDivExpr 4481 return 0; 4482 } 4483 4484 /// Helper method to assign a range to V from metadata present in the IR. 4485 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 4486 if (Instruction *I = dyn_cast<Instruction>(V)) 4487 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 4488 return getConstantRangeFromMetadata(*MD); 4489 4490 return None; 4491 } 4492 4493 /// Determine the range for a particular SCEV. If SignHint is 4494 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 4495 /// with a "cleaner" unsigned (resp. signed) representation. 4496 ConstantRange 4497 ScalarEvolution::getRange(const SCEV *S, 4498 ScalarEvolution::RangeSignHint SignHint) { 4499 DenseMap<const SCEV *, ConstantRange> &Cache = 4500 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 4501 : SignedRanges; 4502 4503 // See if we've computed this range already. 4504 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 4505 if (I != Cache.end()) 4506 return I->second; 4507 4508 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4509 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 4510 4511 unsigned BitWidth = getTypeSizeInBits(S->getType()); 4512 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 4513 4514 // If the value has known zeros, the maximum value will have those known zeros 4515 // as well. 4516 uint32_t TZ = GetMinTrailingZeros(S); 4517 if (TZ != 0) { 4518 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 4519 ConservativeResult = 4520 ConstantRange(APInt::getMinValue(BitWidth), 4521 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 4522 else 4523 ConservativeResult = ConstantRange( 4524 APInt::getSignedMinValue(BitWidth), 4525 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 4526 } 4527 4528 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 4529 ConstantRange X = getRange(Add->getOperand(0), SignHint); 4530 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 4531 X = X.add(getRange(Add->getOperand(i), SignHint)); 4532 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 4533 } 4534 4535 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 4536 ConstantRange X = getRange(Mul->getOperand(0), SignHint); 4537 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 4538 X = X.multiply(getRange(Mul->getOperand(i), SignHint)); 4539 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 4540 } 4541 4542 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 4543 ConstantRange X = getRange(SMax->getOperand(0), SignHint); 4544 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 4545 X = X.smax(getRange(SMax->getOperand(i), SignHint)); 4546 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 4547 } 4548 4549 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 4550 ConstantRange X = getRange(UMax->getOperand(0), SignHint); 4551 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 4552 X = X.umax(getRange(UMax->getOperand(i), SignHint)); 4553 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 4554 } 4555 4556 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 4557 ConstantRange X = getRange(UDiv->getLHS(), SignHint); 4558 ConstantRange Y = getRange(UDiv->getRHS(), SignHint); 4559 return setRange(UDiv, SignHint, 4560 ConservativeResult.intersectWith(X.udiv(Y))); 4561 } 4562 4563 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 4564 ConstantRange X = getRange(ZExt->getOperand(), SignHint); 4565 return setRange(ZExt, SignHint, 4566 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 4567 } 4568 4569 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 4570 ConstantRange X = getRange(SExt->getOperand(), SignHint); 4571 return setRange(SExt, SignHint, 4572 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 4573 } 4574 4575 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 4576 ConstantRange X = getRange(Trunc->getOperand(), SignHint); 4577 return setRange(Trunc, SignHint, 4578 ConservativeResult.intersectWith(X.truncate(BitWidth))); 4579 } 4580 4581 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 4582 // If there's no unsigned wrap, the value will never be less than its 4583 // initial value. 4584 if (AddRec->hasNoUnsignedWrap()) 4585 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 4586 if (!C->getValue()->isZero()) 4587 ConservativeResult = ConservativeResult.intersectWith( 4588 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 4589 4590 // If there's no signed wrap, and all the operands have the same sign or 4591 // zero, the value won't ever change sign. 4592 if (AddRec->hasNoSignedWrap()) { 4593 bool AllNonNeg = true; 4594 bool AllNonPos = true; 4595 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 4596 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 4597 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 4598 } 4599 if (AllNonNeg) 4600 ConservativeResult = ConservativeResult.intersectWith( 4601 ConstantRange(APInt(BitWidth, 0), 4602 APInt::getSignedMinValue(BitWidth))); 4603 else if (AllNonPos) 4604 ConservativeResult = ConservativeResult.intersectWith( 4605 ConstantRange(APInt::getSignedMinValue(BitWidth), 4606 APInt(BitWidth, 1))); 4607 } 4608 4609 // TODO: non-affine addrec 4610 if (AddRec->isAffine()) { 4611 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 4612 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 4613 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 4614 auto RangeFromAffine = getRangeForAffineAR( 4615 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4616 BitWidth); 4617 if (!RangeFromAffine.isFullSet()) 4618 ConservativeResult = 4619 ConservativeResult.intersectWith(RangeFromAffine); 4620 4621 auto RangeFromFactoring = getRangeViaFactoring( 4622 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4623 BitWidth); 4624 if (!RangeFromFactoring.isFullSet()) 4625 ConservativeResult = 4626 ConservativeResult.intersectWith(RangeFromFactoring); 4627 } 4628 } 4629 4630 return setRange(AddRec, SignHint, ConservativeResult); 4631 } 4632 4633 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4634 // Check if the IR explicitly contains !range metadata. 4635 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 4636 if (MDRange.hasValue()) 4637 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 4638 4639 // Split here to avoid paying the compile-time cost of calling both 4640 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 4641 // if needed. 4642 const DataLayout &DL = getDataLayout(); 4643 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 4644 // For a SCEVUnknown, ask ValueTracking. 4645 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4646 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); 4647 if (Ones != ~Zeros + 1) 4648 ConservativeResult = 4649 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); 4650 } else { 4651 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 4652 "generalize as needed!"); 4653 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 4654 if (NS > 1) 4655 ConservativeResult = ConservativeResult.intersectWith( 4656 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 4657 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 4658 } 4659 4660 return setRange(U, SignHint, ConservativeResult); 4661 } 4662 4663 return setRange(S, SignHint, ConservativeResult); 4664 } 4665 4666 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 4667 const SCEV *Step, 4668 const SCEV *MaxBECount, 4669 unsigned BitWidth) { 4670 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 4671 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 4672 "Precondition!"); 4673 4674 ConstantRange Result(BitWidth, /* isFullSet = */ true); 4675 4676 // Check for overflow. This must be done with ConstantRange arithmetic 4677 // because we could be called from within the ScalarEvolution overflow 4678 // checking code. 4679 4680 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 4681 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); 4682 ConstantRange ZExtMaxBECountRange = MaxBECountRange.zextOrTrunc(BitWidth * 2); 4683 4684 ConstantRange StepSRange = getSignedRange(Step); 4685 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2); 4686 4687 ConstantRange StartURange = getUnsignedRange(Start); 4688 ConstantRange EndURange = 4689 StartURange.add(MaxBECountRange.multiply(StepSRange)); 4690 4691 // Check for unsigned overflow. 4692 ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2); 4693 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2); 4694 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4695 ZExtEndURange) { 4696 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(), 4697 EndURange.getUnsignedMin()); 4698 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(), 4699 EndURange.getUnsignedMax()); 4700 bool IsFullRange = Min.isMinValue() && Max.isMaxValue(); 4701 if (!IsFullRange) 4702 Result = 4703 Result.intersectWith(ConstantRange(Min, Max + 1)); 4704 } 4705 4706 ConstantRange StartSRange = getSignedRange(Start); 4707 ConstantRange EndSRange = 4708 StartSRange.add(MaxBECountRange.multiply(StepSRange)); 4709 4710 // Check for signed overflow. This must be done with ConstantRange 4711 // arithmetic because we could be called from within the ScalarEvolution 4712 // overflow checking code. 4713 ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2); 4714 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2); 4715 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4716 SExtEndSRange) { 4717 APInt Min = 4718 APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin()); 4719 APInt Max = 4720 APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax()); 4721 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue(); 4722 if (!IsFullRange) 4723 Result = 4724 Result.intersectWith(ConstantRange(Min, Max + 1)); 4725 } 4726 4727 return Result; 4728 } 4729 4730 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 4731 const SCEV *Step, 4732 const SCEV *MaxBECount, 4733 unsigned BitWidth) { 4734 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 4735 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 4736 4737 struct SelectPattern { 4738 Value *Condition = nullptr; 4739 APInt TrueValue; 4740 APInt FalseValue; 4741 4742 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 4743 const SCEV *S) { 4744 Optional<unsigned> CastOp; 4745 APInt Offset(BitWidth, 0); 4746 4747 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 4748 "Should be!"); 4749 4750 // Peel off a constant offset: 4751 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 4752 // In the future we could consider being smarter here and handle 4753 // {Start+Step,+,Step} too. 4754 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 4755 return; 4756 4757 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 4758 S = SA->getOperand(1); 4759 } 4760 4761 // Peel off a cast operation 4762 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 4763 CastOp = SCast->getSCEVType(); 4764 S = SCast->getOperand(); 4765 } 4766 4767 using namespace llvm::PatternMatch; 4768 4769 auto *SU = dyn_cast<SCEVUnknown>(S); 4770 const APInt *TrueVal, *FalseVal; 4771 if (!SU || 4772 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 4773 m_APInt(FalseVal)))) { 4774 Condition = nullptr; 4775 return; 4776 } 4777 4778 TrueValue = *TrueVal; 4779 FalseValue = *FalseVal; 4780 4781 // Re-apply the cast we peeled off earlier 4782 if (CastOp.hasValue()) 4783 switch (*CastOp) { 4784 default: 4785 llvm_unreachable("Unknown SCEV cast type!"); 4786 4787 case scTruncate: 4788 TrueValue = TrueValue.trunc(BitWidth); 4789 FalseValue = FalseValue.trunc(BitWidth); 4790 break; 4791 case scZeroExtend: 4792 TrueValue = TrueValue.zext(BitWidth); 4793 FalseValue = FalseValue.zext(BitWidth); 4794 break; 4795 case scSignExtend: 4796 TrueValue = TrueValue.sext(BitWidth); 4797 FalseValue = FalseValue.sext(BitWidth); 4798 break; 4799 } 4800 4801 // Re-apply the constant offset we peeled off earlier 4802 TrueValue += Offset; 4803 FalseValue += Offset; 4804 } 4805 4806 bool isRecognized() { return Condition != nullptr; } 4807 }; 4808 4809 SelectPattern StartPattern(*this, BitWidth, Start); 4810 if (!StartPattern.isRecognized()) 4811 return ConstantRange(BitWidth, /* isFullSet = */ true); 4812 4813 SelectPattern StepPattern(*this, BitWidth, Step); 4814 if (!StepPattern.isRecognized()) 4815 return ConstantRange(BitWidth, /* isFullSet = */ true); 4816 4817 if (StartPattern.Condition != StepPattern.Condition) { 4818 // We don't handle this case today; but we could, by considering four 4819 // possibilities below instead of two. I'm not sure if there are cases where 4820 // that will help over what getRange already does, though. 4821 return ConstantRange(BitWidth, /* isFullSet = */ true); 4822 } 4823 4824 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 4825 // construct arbitrary general SCEV expressions here. This function is called 4826 // from deep in the call stack, and calling getSCEV (on a sext instruction, 4827 // say) can end up caching a suboptimal value. 4828 4829 // FIXME: without the explicit `this` receiver below, MSVC errors out with 4830 // C2352 and C2512 (otherwise it isn't needed). 4831 4832 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 4833 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 4834 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 4835 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 4836 4837 ConstantRange TrueRange = 4838 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 4839 ConstantRange FalseRange = 4840 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 4841 4842 return TrueRange.unionWith(FalseRange); 4843 } 4844 4845 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 4846 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 4847 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 4848 4849 // Return early if there are no flags to propagate to the SCEV. 4850 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4851 if (BinOp->hasNoUnsignedWrap()) 4852 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 4853 if (BinOp->hasNoSignedWrap()) 4854 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 4855 if (Flags == SCEV::FlagAnyWrap) 4856 return SCEV::FlagAnyWrap; 4857 4858 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 4859 } 4860 4861 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 4862 // Here we check that I is in the header of the innermost loop containing I, 4863 // since we only deal with instructions in the loop header. The actual loop we 4864 // need to check later will come from an add recurrence, but getting that 4865 // requires computing the SCEV of the operands, which can be expensive. This 4866 // check we can do cheaply to rule out some cases early. 4867 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 4868 if (InnermostContainingLoop == nullptr || 4869 InnermostContainingLoop->getHeader() != I->getParent()) 4870 return false; 4871 4872 // Only proceed if we can prove that I does not yield poison. 4873 if (!isKnownNotFullPoison(I)) return false; 4874 4875 // At this point we know that if I is executed, then it does not wrap 4876 // according to at least one of NSW or NUW. If I is not executed, then we do 4877 // not know if the calculation that I represents would wrap. Multiple 4878 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 4879 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 4880 // derived from other instructions that map to the same SCEV. We cannot make 4881 // that guarantee for cases where I is not executed. So we need to find the 4882 // loop that I is considered in relation to and prove that I is executed for 4883 // every iteration of that loop. That implies that the value that I 4884 // calculates does not wrap anywhere in the loop, so then we can apply the 4885 // flags to the SCEV. 4886 // 4887 // We check isLoopInvariant to disambiguate in case we are adding recurrences 4888 // from different loops, so that we know which loop to prove that I is 4889 // executed in. 4890 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 4891 // I could be an extractvalue from a call to an overflow intrinsic. 4892 // TODO: We can do better here in some cases. 4893 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 4894 return false; 4895 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 4896 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 4897 bool AllOtherOpsLoopInvariant = true; 4898 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 4899 ++OtherOpIndex) { 4900 if (OtherOpIndex != OpIndex) { 4901 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 4902 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 4903 AllOtherOpsLoopInvariant = false; 4904 break; 4905 } 4906 } 4907 } 4908 if (AllOtherOpsLoopInvariant && 4909 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 4910 return true; 4911 } 4912 } 4913 return false; 4914 } 4915 4916 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 4917 // If we know that \c I can never be poison period, then that's enough. 4918 if (isSCEVExprNeverPoison(I)) 4919 return true; 4920 4921 // For an add recurrence specifically, we assume that infinite loops without 4922 // side effects are undefined behavior, and then reason as follows: 4923 // 4924 // If the add recurrence is poison in any iteration, it is poison on all 4925 // future iterations (since incrementing poison yields poison). If the result 4926 // of the add recurrence is fed into the loop latch condition and the loop 4927 // does not contain any throws or exiting blocks other than the latch, we now 4928 // have the ability to "choose" whether the backedge is taken or not (by 4929 // choosing a sufficiently evil value for the poison feeding into the branch) 4930 // for every iteration including and after the one in which \p I first became 4931 // poison. There are two possibilities (let's call the iteration in which \p 4932 // I first became poison as K): 4933 // 4934 // 1. In the set of iterations including and after K, the loop body executes 4935 // no side effects. In this case executing the backege an infinte number 4936 // of times will yield undefined behavior. 4937 // 4938 // 2. In the set of iterations including and after K, the loop body executes 4939 // at least one side effect. In this case, that specific instance of side 4940 // effect is control dependent on poison, which also yields undefined 4941 // behavior. 4942 4943 auto *ExitingBB = L->getExitingBlock(); 4944 auto *LatchBB = L->getLoopLatch(); 4945 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 4946 return false; 4947 4948 SmallPtrSet<const Instruction *, 16> Pushed; 4949 SmallVector<const Instruction *, 8> PoisonStack; 4950 4951 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 4952 // things that are known to be fully poison under that assumption go on the 4953 // PoisonStack. 4954 Pushed.insert(I); 4955 PoisonStack.push_back(I); 4956 4957 bool LatchControlDependentOnPoison = false; 4958 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 4959 const Instruction *Poison = PoisonStack.pop_back_val(); 4960 4961 for (auto *PoisonUser : Poison->users()) { 4962 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 4963 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 4964 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 4965 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 4966 assert(BI->isConditional() && "Only possibility!"); 4967 if (BI->getParent() == LatchBB) { 4968 LatchControlDependentOnPoison = true; 4969 break; 4970 } 4971 } 4972 } 4973 } 4974 4975 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 4976 } 4977 4978 ScalarEvolution::LoopProperties 4979 ScalarEvolution::getLoopProperties(const Loop *L) { 4980 typedef ScalarEvolution::LoopProperties LoopProperties; 4981 4982 auto Itr = LoopPropertiesCache.find(L); 4983 if (Itr == LoopPropertiesCache.end()) { 4984 auto HasSideEffects = [](Instruction *I) { 4985 if (auto *SI = dyn_cast<StoreInst>(I)) 4986 return !SI->isSimple(); 4987 4988 return I->mayHaveSideEffects(); 4989 }; 4990 4991 LoopProperties LP = {/* HasNoAbnormalExits */ true, 4992 /*HasNoSideEffects*/ true}; 4993 4994 for (auto *BB : L->getBlocks()) 4995 for (auto &I : *BB) { 4996 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 4997 LP.HasNoAbnormalExits = false; 4998 if (HasSideEffects(&I)) 4999 LP.HasNoSideEffects = false; 5000 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 5001 break; // We're already as pessimistic as we can get. 5002 } 5003 5004 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 5005 assert(InsertPair.second && "We just checked!"); 5006 Itr = InsertPair.first; 5007 } 5008 5009 return Itr->second; 5010 } 5011 5012 const SCEV *ScalarEvolution::createSCEV(Value *V) { 5013 if (!isSCEVable(V->getType())) 5014 return getUnknown(V); 5015 5016 if (Instruction *I = dyn_cast<Instruction>(V)) { 5017 // Don't attempt to analyze instructions in blocks that aren't 5018 // reachable. Such instructions don't matter, and they aren't required 5019 // to obey basic rules for definitions dominating uses which this 5020 // analysis depends on. 5021 if (!DT.isReachableFromEntry(I->getParent())) 5022 return getUnknown(V); 5023 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5024 return getConstant(CI); 5025 else if (isa<ConstantPointerNull>(V)) 5026 return getZero(V->getType()); 5027 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5028 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5029 else if (!isa<ConstantExpr>(V)) 5030 return getUnknown(V); 5031 5032 Operator *U = cast<Operator>(V); 5033 if (auto BO = MatchBinaryOp(U, DT)) { 5034 switch (BO->Opcode) { 5035 case Instruction::Add: { 5036 // The simple thing to do would be to just call getSCEV on both operands 5037 // and call getAddExpr with the result. However if we're looking at a 5038 // bunch of things all added together, this can be quite inefficient, 5039 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5040 // Instead, gather up all the operands and make a single getAddExpr call. 5041 // LLVM IR canonical form means we need only traverse the left operands. 5042 SmallVector<const SCEV *, 4> AddOps; 5043 do { 5044 if (BO->Op) { 5045 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5046 AddOps.push_back(OpSCEV); 5047 break; 5048 } 5049 5050 // If a NUW or NSW flag can be applied to the SCEV for this 5051 // addition, then compute the SCEV for this addition by itself 5052 // with a separate call to getAddExpr. We need to do that 5053 // instead of pushing the operands of the addition onto AddOps, 5054 // since the flags are only known to apply to this particular 5055 // addition - they may not apply to other additions that can be 5056 // formed with operands from AddOps. 5057 const SCEV *RHS = getSCEV(BO->RHS); 5058 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5059 if (Flags != SCEV::FlagAnyWrap) { 5060 const SCEV *LHS = getSCEV(BO->LHS); 5061 if (BO->Opcode == Instruction::Sub) 5062 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5063 else 5064 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5065 break; 5066 } 5067 } 5068 5069 if (BO->Opcode == Instruction::Sub) 5070 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 5071 else 5072 AddOps.push_back(getSCEV(BO->RHS)); 5073 5074 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5075 if (!NewBO || (NewBO->Opcode != Instruction::Add && 5076 NewBO->Opcode != Instruction::Sub)) { 5077 AddOps.push_back(getSCEV(BO->LHS)); 5078 break; 5079 } 5080 BO = NewBO; 5081 } while (true); 5082 5083 return getAddExpr(AddOps); 5084 } 5085 5086 case Instruction::Mul: { 5087 SmallVector<const SCEV *, 4> MulOps; 5088 do { 5089 if (BO->Op) { 5090 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5091 MulOps.push_back(OpSCEV); 5092 break; 5093 } 5094 5095 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5096 if (Flags != SCEV::FlagAnyWrap) { 5097 MulOps.push_back( 5098 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 5099 break; 5100 } 5101 } 5102 5103 MulOps.push_back(getSCEV(BO->RHS)); 5104 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5105 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 5106 MulOps.push_back(getSCEV(BO->LHS)); 5107 break; 5108 } 5109 BO = NewBO; 5110 } while (true); 5111 5112 return getMulExpr(MulOps); 5113 } 5114 case Instruction::UDiv: 5115 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 5116 case Instruction::Sub: { 5117 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5118 if (BO->Op) 5119 Flags = getNoWrapFlagsFromUB(BO->Op); 5120 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 5121 } 5122 case Instruction::And: 5123 // For an expression like x&255 that merely masks off the high bits, 5124 // use zext(trunc(x)) as the SCEV expression. 5125 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5126 if (CI->isNullValue()) 5127 return getSCEV(BO->RHS); 5128 if (CI->isAllOnesValue()) 5129 return getSCEV(BO->LHS); 5130 const APInt &A = CI->getValue(); 5131 5132 // Instcombine's ShrinkDemandedConstant may strip bits out of 5133 // constants, obscuring what would otherwise be a low-bits mask. 5134 // Use computeKnownBits to compute what ShrinkDemandedConstant 5135 // knew about to reconstruct a low-bits mask value. 5136 unsigned LZ = A.countLeadingZeros(); 5137 unsigned TZ = A.countTrailingZeros(); 5138 unsigned BitWidth = A.getBitWidth(); 5139 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 5140 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(), 5141 0, &AC, nullptr, &DT); 5142 5143 APInt EffectiveMask = 5144 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 5145 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { 5146 const SCEV *MulCount = getConstant(ConstantInt::get( 5147 getContext(), APInt::getOneBitSet(BitWidth, TZ))); 5148 return getMulExpr( 5149 getZeroExtendExpr( 5150 getTruncateExpr( 5151 getUDivExactExpr(getSCEV(BO->LHS), MulCount), 5152 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 5153 BO->LHS->getType()), 5154 MulCount); 5155 } 5156 } 5157 break; 5158 5159 case Instruction::Or: 5160 // If the RHS of the Or is a constant, we may have something like: 5161 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 5162 // optimizations will transparently handle this case. 5163 // 5164 // In order for this transformation to be safe, the LHS must be of the 5165 // form X*(2^n) and the Or constant must be less than 2^n. 5166 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5167 const SCEV *LHS = getSCEV(BO->LHS); 5168 const APInt &CIVal = CI->getValue(); 5169 if (GetMinTrailingZeros(LHS) >= 5170 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 5171 // Build a plain add SCEV. 5172 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 5173 // If the LHS of the add was an addrec and it has no-wrap flags, 5174 // transfer the no-wrap flags, since an or won't introduce a wrap. 5175 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 5176 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 5177 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 5178 OldAR->getNoWrapFlags()); 5179 } 5180 return S; 5181 } 5182 } 5183 break; 5184 5185 case Instruction::Xor: 5186 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5187 // If the RHS of xor is -1, then this is a not operation. 5188 if (CI->isAllOnesValue()) 5189 return getNotSCEV(getSCEV(BO->LHS)); 5190 5191 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 5192 // This is a variant of the check for xor with -1, and it handles 5193 // the case where instcombine has trimmed non-demanded bits out 5194 // of an xor with -1. 5195 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 5196 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 5197 if (LBO->getOpcode() == Instruction::And && 5198 LCI->getValue() == CI->getValue()) 5199 if (const SCEVZeroExtendExpr *Z = 5200 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 5201 Type *UTy = BO->LHS->getType(); 5202 const SCEV *Z0 = Z->getOperand(); 5203 Type *Z0Ty = Z0->getType(); 5204 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 5205 5206 // If C is a low-bits mask, the zero extend is serving to 5207 // mask off the high bits. Complement the operand and 5208 // re-apply the zext. 5209 if (APIntOps::isMask(Z0TySize, CI->getValue())) 5210 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 5211 5212 // If C is a single bit, it may be in the sign-bit position 5213 // before the zero-extend. In this case, represent the xor 5214 // using an add, which is equivalent, and re-apply the zext. 5215 APInt Trunc = CI->getValue().trunc(Z0TySize); 5216 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 5217 Trunc.isSignBit()) 5218 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 5219 UTy); 5220 } 5221 } 5222 break; 5223 5224 case Instruction::Shl: 5225 // Turn shift left of a constant amount into a multiply. 5226 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 5227 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 5228 5229 // If the shift count is not less than the bitwidth, the result of 5230 // the shift is undefined. Don't try to analyze it, because the 5231 // resolution chosen here may differ from the resolution chosen in 5232 // other parts of the compiler. 5233 if (SA->getValue().uge(BitWidth)) 5234 break; 5235 5236 // It is currently not resolved how to interpret NSW for left 5237 // shift by BitWidth - 1, so we avoid applying flags in that 5238 // case. Remove this check (or this comment) once the situation 5239 // is resolved. See 5240 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 5241 // and http://reviews.llvm.org/D8890 . 5242 auto Flags = SCEV::FlagAnyWrap; 5243 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 5244 Flags = getNoWrapFlagsFromUB(BO->Op); 5245 5246 Constant *X = ConstantInt::get(getContext(), 5247 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5248 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 5249 } 5250 break; 5251 5252 case Instruction::AShr: 5253 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. 5254 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) 5255 if (Operator *L = dyn_cast<Operator>(BO->LHS)) 5256 if (L->getOpcode() == Instruction::Shl && 5257 L->getOperand(1) == BO->RHS) { 5258 uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType()); 5259 5260 // If the shift count is not less than the bitwidth, the result of 5261 // the shift is undefined. Don't try to analyze it, because the 5262 // resolution chosen here may differ from the resolution chosen in 5263 // other parts of the compiler. 5264 if (CI->getValue().uge(BitWidth)) 5265 break; 5266 5267 uint64_t Amt = BitWidth - CI->getZExtValue(); 5268 if (Amt == BitWidth) 5269 return getSCEV(L->getOperand(0)); // shift by zero --> noop 5270 return getSignExtendExpr( 5271 getTruncateExpr(getSCEV(L->getOperand(0)), 5272 IntegerType::get(getContext(), Amt)), 5273 BO->LHS->getType()); 5274 } 5275 break; 5276 } 5277 } 5278 5279 switch (U->getOpcode()) { 5280 case Instruction::Trunc: 5281 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 5282 5283 case Instruction::ZExt: 5284 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5285 5286 case Instruction::SExt: 5287 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5288 5289 case Instruction::BitCast: 5290 // BitCasts are no-op casts so we just eliminate the cast. 5291 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 5292 return getSCEV(U->getOperand(0)); 5293 break; 5294 5295 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 5296 // lead to pointer expressions which cannot safely be expanded to GEPs, 5297 // because ScalarEvolution doesn't respect the GEP aliasing rules when 5298 // simplifying integer expressions. 5299 5300 case Instruction::GetElementPtr: 5301 return createNodeForGEP(cast<GEPOperator>(U)); 5302 5303 case Instruction::PHI: 5304 return createNodeForPHI(cast<PHINode>(U)); 5305 5306 case Instruction::Select: 5307 // U can also be a select constant expr, which let fall through. Since 5308 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 5309 // constant expressions cannot have instructions as operands, we'd have 5310 // returned getUnknown for a select constant expressions anyway. 5311 if (isa<Instruction>(U)) 5312 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 5313 U->getOperand(1), U->getOperand(2)); 5314 break; 5315 5316 case Instruction::Call: 5317 case Instruction::Invoke: 5318 if (Value *RV = CallSite(U).getReturnedArgOperand()) 5319 return getSCEV(RV); 5320 break; 5321 } 5322 5323 return getUnknown(V); 5324 } 5325 5326 5327 5328 //===----------------------------------------------------------------------===// 5329 // Iteration Count Computation Code 5330 // 5331 5332 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 5333 if (!ExitCount) 5334 return 0; 5335 5336 ConstantInt *ExitConst = ExitCount->getValue(); 5337 5338 // Guard against huge trip counts. 5339 if (ExitConst->getValue().getActiveBits() > 32) 5340 return 0; 5341 5342 // In case of integer overflow, this returns 0, which is correct. 5343 return ((unsigned)ExitConst->getZExtValue()) + 1; 5344 } 5345 5346 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) { 5347 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5348 return getSmallConstantTripCount(L, ExitingBB); 5349 5350 // No trip count information for multiple exits. 5351 return 0; 5352 } 5353 5354 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, 5355 BasicBlock *ExitingBlock) { 5356 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5357 assert(L->isLoopExiting(ExitingBlock) && 5358 "Exiting block must actually branch out of the loop!"); 5359 const SCEVConstant *ExitCount = 5360 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 5361 return getConstantTripCount(ExitCount); 5362 } 5363 5364 unsigned ScalarEvolution::getSmallConstantMaxTripCount(Loop *L) { 5365 const auto *MaxExitCount = 5366 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 5367 return getConstantTripCount(MaxExitCount); 5368 } 5369 5370 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) { 5371 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5372 return getSmallConstantTripMultiple(L, ExitingBB); 5373 5374 // No trip multiple information for multiple exits. 5375 return 0; 5376 } 5377 5378 /// Returns the largest constant divisor of the trip count of this loop as a 5379 /// normal unsigned value, if possible. This means that the actual trip count is 5380 /// always a multiple of the returned value (don't forget the trip count could 5381 /// very well be zero as well!). 5382 /// 5383 /// Returns 1 if the trip count is unknown or not guaranteed to be the 5384 /// multiple of a constant (which is also the case if the trip count is simply 5385 /// constant, use getSmallConstantTripCount for that case), Will also return 1 5386 /// if the trip count is very large (>= 2^32). 5387 /// 5388 /// As explained in the comments for getSmallConstantTripCount, this assumes 5389 /// that control exits the loop via ExitingBlock. 5390 unsigned 5391 ScalarEvolution::getSmallConstantTripMultiple(Loop *L, 5392 BasicBlock *ExitingBlock) { 5393 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5394 assert(L->isLoopExiting(ExitingBlock) && 5395 "Exiting block must actually branch out of the loop!"); 5396 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 5397 if (ExitCount == getCouldNotCompute()) 5398 return 1; 5399 5400 // Get the trip count from the BE count by adding 1. 5401 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType())); 5402 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt 5403 // to factor simple cases. 5404 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) 5405 TCMul = Mul->getOperand(0); 5406 5407 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); 5408 if (!MulC) 5409 return 1; 5410 5411 ConstantInt *Result = MulC->getValue(); 5412 5413 // Guard against huge trip counts (this requires checking 5414 // for zero to handle the case where the trip count == -1 and the 5415 // addition wraps). 5416 if (!Result || Result->getValue().getActiveBits() > 32 || 5417 Result->getValue().getActiveBits() == 0) 5418 return 1; 5419 5420 return (unsigned)Result->getZExtValue(); 5421 } 5422 5423 /// Get the expression for the number of loop iterations for which this loop is 5424 /// guaranteed not to exit via ExitingBlock. Otherwise return 5425 /// SCEVCouldNotCompute. 5426 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { 5427 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 5428 } 5429 5430 const SCEV * 5431 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 5432 SCEVUnionPredicate &Preds) { 5433 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 5434 } 5435 5436 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 5437 return getBackedgeTakenInfo(L).getExact(this); 5438 } 5439 5440 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 5441 /// known never to be less than the actual backedge taken count. 5442 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 5443 return getBackedgeTakenInfo(L).getMax(this); 5444 } 5445 5446 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 5447 return getBackedgeTakenInfo(L).isMaxOrZero(this); 5448 } 5449 5450 /// Push PHI nodes in the header of the given loop onto the given Worklist. 5451 static void 5452 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 5453 BasicBlock *Header = L->getHeader(); 5454 5455 // Push all Loop-header PHIs onto the Worklist stack. 5456 for (BasicBlock::iterator I = Header->begin(); 5457 PHINode *PN = dyn_cast<PHINode>(I); ++I) 5458 Worklist.push_back(PN); 5459 } 5460 5461 const ScalarEvolution::BackedgeTakenInfo & 5462 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 5463 auto &BTI = getBackedgeTakenInfo(L); 5464 if (BTI.hasFullInfo()) 5465 return BTI; 5466 5467 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5468 5469 if (!Pair.second) 5470 return Pair.first->second; 5471 5472 BackedgeTakenInfo Result = 5473 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 5474 5475 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 5476 } 5477 5478 const ScalarEvolution::BackedgeTakenInfo & 5479 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 5480 // Initially insert an invalid entry for this loop. If the insertion 5481 // succeeds, proceed to actually compute a backedge-taken count and 5482 // update the value. The temporary CouldNotCompute value tells SCEV 5483 // code elsewhere that it shouldn't attempt to request a new 5484 // backedge-taken count, which could result in infinite recursion. 5485 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 5486 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5487 if (!Pair.second) 5488 return Pair.first->second; 5489 5490 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 5491 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 5492 // must be cleared in this scope. 5493 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 5494 5495 if (Result.getExact(this) != getCouldNotCompute()) { 5496 assert(isLoopInvariant(Result.getExact(this), L) && 5497 isLoopInvariant(Result.getMax(this), L) && 5498 "Computed backedge-taken count isn't loop invariant for loop!"); 5499 ++NumTripCountsComputed; 5500 } 5501 else if (Result.getMax(this) == getCouldNotCompute() && 5502 isa<PHINode>(L->getHeader()->begin())) { 5503 // Only count loops that have phi nodes as not being computable. 5504 ++NumTripCountsNotComputed; 5505 } 5506 5507 // Now that we know more about the trip count for this loop, forget any 5508 // existing SCEV values for PHI nodes in this loop since they are only 5509 // conservative estimates made without the benefit of trip count 5510 // information. This is similar to the code in forgetLoop, except that 5511 // it handles SCEVUnknown PHI nodes specially. 5512 if (Result.hasAnyInfo()) { 5513 SmallVector<Instruction *, 16> Worklist; 5514 PushLoopPHIs(L, Worklist); 5515 5516 SmallPtrSet<Instruction *, 8> Visited; 5517 while (!Worklist.empty()) { 5518 Instruction *I = Worklist.pop_back_val(); 5519 if (!Visited.insert(I).second) 5520 continue; 5521 5522 ValueExprMapType::iterator It = 5523 ValueExprMap.find_as(static_cast<Value *>(I)); 5524 if (It != ValueExprMap.end()) { 5525 const SCEV *Old = It->second; 5526 5527 // SCEVUnknown for a PHI either means that it has an unrecognized 5528 // structure, or it's a PHI that's in the progress of being computed 5529 // by createNodeForPHI. In the former case, additional loop trip 5530 // count information isn't going to change anything. In the later 5531 // case, createNodeForPHI will perform the necessary updates on its 5532 // own when it gets to that point. 5533 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 5534 eraseValueFromMap(It->first); 5535 forgetMemoizedResults(Old); 5536 } 5537 if (PHINode *PN = dyn_cast<PHINode>(I)) 5538 ConstantEvolutionLoopExitValue.erase(PN); 5539 } 5540 5541 PushDefUseChildren(I, Worklist); 5542 } 5543 } 5544 5545 // Re-lookup the insert position, since the call to 5546 // computeBackedgeTakenCount above could result in a 5547 // recusive call to getBackedgeTakenInfo (on a different 5548 // loop), which would invalidate the iterator computed 5549 // earlier. 5550 return BackedgeTakenCounts.find(L)->second = std::move(Result); 5551 } 5552 5553 void ScalarEvolution::forgetLoop(const Loop *L) { 5554 // Drop any stored trip count value. 5555 auto RemoveLoopFromBackedgeMap = 5556 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 5557 auto BTCPos = Map.find(L); 5558 if (BTCPos != Map.end()) { 5559 BTCPos->second.clear(); 5560 Map.erase(BTCPos); 5561 } 5562 }; 5563 5564 RemoveLoopFromBackedgeMap(BackedgeTakenCounts); 5565 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); 5566 5567 // Drop information about expressions based on loop-header PHIs. 5568 SmallVector<Instruction *, 16> Worklist; 5569 PushLoopPHIs(L, Worklist); 5570 5571 SmallPtrSet<Instruction *, 8> Visited; 5572 while (!Worklist.empty()) { 5573 Instruction *I = Worklist.pop_back_val(); 5574 if (!Visited.insert(I).second) 5575 continue; 5576 5577 ValueExprMapType::iterator It = 5578 ValueExprMap.find_as(static_cast<Value *>(I)); 5579 if (It != ValueExprMap.end()) { 5580 eraseValueFromMap(It->first); 5581 forgetMemoizedResults(It->second); 5582 if (PHINode *PN = dyn_cast<PHINode>(I)) 5583 ConstantEvolutionLoopExitValue.erase(PN); 5584 } 5585 5586 PushDefUseChildren(I, Worklist); 5587 } 5588 5589 // Forget all contained loops too, to avoid dangling entries in the 5590 // ValuesAtScopes map. 5591 for (Loop *I : *L) 5592 forgetLoop(I); 5593 5594 LoopPropertiesCache.erase(L); 5595 } 5596 5597 void ScalarEvolution::forgetValue(Value *V) { 5598 Instruction *I = dyn_cast<Instruction>(V); 5599 if (!I) return; 5600 5601 // Drop information about expressions based on loop-header PHIs. 5602 SmallVector<Instruction *, 16> Worklist; 5603 Worklist.push_back(I); 5604 5605 SmallPtrSet<Instruction *, 8> Visited; 5606 while (!Worklist.empty()) { 5607 I = Worklist.pop_back_val(); 5608 if (!Visited.insert(I).second) 5609 continue; 5610 5611 ValueExprMapType::iterator It = 5612 ValueExprMap.find_as(static_cast<Value *>(I)); 5613 if (It != ValueExprMap.end()) { 5614 eraseValueFromMap(It->first); 5615 forgetMemoizedResults(It->second); 5616 if (PHINode *PN = dyn_cast<PHINode>(I)) 5617 ConstantEvolutionLoopExitValue.erase(PN); 5618 } 5619 5620 PushDefUseChildren(I, Worklist); 5621 } 5622 } 5623 5624 /// Get the exact loop backedge taken count considering all loop exits. A 5625 /// computable result can only be returned for loops with a single exit. 5626 /// Returning the minimum taken count among all exits is incorrect because one 5627 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 5628 /// the limit of each loop test is never skipped. This is a valid assumption as 5629 /// long as the loop exits via that test. For precise results, it is the 5630 /// caller's responsibility to specify the relevant loop exit using 5631 /// getExact(ExitingBlock, SE). 5632 const SCEV * 5633 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, 5634 SCEVUnionPredicate *Preds) const { 5635 // If any exits were not computable, the loop is not computable. 5636 if (!isComplete() || ExitNotTaken.empty()) 5637 return SE->getCouldNotCompute(); 5638 5639 const SCEV *BECount = nullptr; 5640 for (auto &ENT : ExitNotTaken) { 5641 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 5642 5643 if (!BECount) 5644 BECount = ENT.ExactNotTaken; 5645 else if (BECount != ENT.ExactNotTaken) 5646 return SE->getCouldNotCompute(); 5647 if (Preds && !ENT.hasAlwaysTruePredicate()) 5648 Preds->add(ENT.Predicate.get()); 5649 5650 assert((Preds || ENT.hasAlwaysTruePredicate()) && 5651 "Predicate should be always true!"); 5652 } 5653 5654 assert(BECount && "Invalid not taken count for loop exit"); 5655 return BECount; 5656 } 5657 5658 /// Get the exact not taken count for this loop exit. 5659 const SCEV * 5660 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 5661 ScalarEvolution *SE) const { 5662 for (auto &ENT : ExitNotTaken) 5663 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 5664 return ENT.ExactNotTaken; 5665 5666 return SE->getCouldNotCompute(); 5667 } 5668 5669 /// getMax - Get the max backedge taken count for the loop. 5670 const SCEV * 5671 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 5672 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5673 return !ENT.hasAlwaysTruePredicate(); 5674 }; 5675 5676 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 5677 return SE->getCouldNotCompute(); 5678 5679 return getMax(); 5680 } 5681 5682 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 5683 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5684 return !ENT.hasAlwaysTruePredicate(); 5685 }; 5686 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 5687 } 5688 5689 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 5690 ScalarEvolution *SE) const { 5691 if (getMax() && getMax() != SE->getCouldNotCompute() && 5692 SE->hasOperand(getMax(), S)) 5693 return true; 5694 5695 for (auto &ENT : ExitNotTaken) 5696 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 5697 SE->hasOperand(ENT.ExactNotTaken, S)) 5698 return true; 5699 5700 return false; 5701 } 5702 5703 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 5704 /// computable exit into a persistent ExitNotTakenInfo array. 5705 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 5706 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 5707 &&ExitCounts, 5708 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 5709 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 5710 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5711 ExitNotTaken.reserve(ExitCounts.size()); 5712 std::transform( 5713 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 5714 [&](const EdgeExitInfo &EEI) { 5715 BasicBlock *ExitBB = EEI.first; 5716 const ExitLimit &EL = EEI.second; 5717 if (EL.Predicates.empty()) 5718 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 5719 5720 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 5721 for (auto *Pred : EL.Predicates) 5722 Predicate->add(Pred); 5723 5724 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 5725 }); 5726 } 5727 5728 /// Invalidate this result and free the ExitNotTakenInfo array. 5729 void ScalarEvolution::BackedgeTakenInfo::clear() { 5730 ExitNotTaken.clear(); 5731 } 5732 5733 /// Compute the number of times the backedge of the specified loop will execute. 5734 ScalarEvolution::BackedgeTakenInfo 5735 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 5736 bool AllowPredicates) { 5737 SmallVector<BasicBlock *, 8> ExitingBlocks; 5738 L->getExitingBlocks(ExitingBlocks); 5739 5740 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5741 5742 SmallVector<EdgeExitInfo, 4> ExitCounts; 5743 bool CouldComputeBECount = true; 5744 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 5745 const SCEV *MustExitMaxBECount = nullptr; 5746 const SCEV *MayExitMaxBECount = nullptr; 5747 bool MustExitMaxOrZero = false; 5748 5749 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 5750 // and compute maxBECount. 5751 // Do a union of all the predicates here. 5752 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 5753 BasicBlock *ExitBB = ExitingBlocks[i]; 5754 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 5755 5756 assert((AllowPredicates || EL.Predicates.empty()) && 5757 "Predicated exit limit when predicates are not allowed!"); 5758 5759 // 1. For each exit that can be computed, add an entry to ExitCounts. 5760 // CouldComputeBECount is true only if all exits can be computed. 5761 if (EL.ExactNotTaken == getCouldNotCompute()) 5762 // We couldn't compute an exact value for this exit, so 5763 // we won't be able to compute an exact value for the loop. 5764 CouldComputeBECount = false; 5765 else 5766 ExitCounts.emplace_back(ExitBB, EL); 5767 5768 // 2. Derive the loop's MaxBECount from each exit's max number of 5769 // non-exiting iterations. Partition the loop exits into two kinds: 5770 // LoopMustExits and LoopMayExits. 5771 // 5772 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 5773 // is a LoopMayExit. If any computable LoopMustExit is found, then 5774 // MaxBECount is the minimum EL.MaxNotTaken of computable 5775 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 5776 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 5777 // computable EL.MaxNotTaken. 5778 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 5779 DT.dominates(ExitBB, Latch)) { 5780 if (!MustExitMaxBECount) { 5781 MustExitMaxBECount = EL.MaxNotTaken; 5782 MustExitMaxOrZero = EL.MaxOrZero; 5783 } else { 5784 MustExitMaxBECount = 5785 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 5786 } 5787 } else if (MayExitMaxBECount != getCouldNotCompute()) { 5788 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 5789 MayExitMaxBECount = EL.MaxNotTaken; 5790 else { 5791 MayExitMaxBECount = 5792 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 5793 } 5794 } 5795 } 5796 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 5797 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 5798 // The loop backedge will be taken the maximum or zero times if there's 5799 // a single exit that must be taken the maximum or zero times. 5800 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 5801 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 5802 MaxBECount, MaxOrZero); 5803 } 5804 5805 ScalarEvolution::ExitLimit 5806 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 5807 bool AllowPredicates) { 5808 5809 // Okay, we've chosen an exiting block. See what condition causes us to exit 5810 // at this block and remember the exit block and whether all other targets 5811 // lead to the loop header. 5812 bool MustExecuteLoopHeader = true; 5813 BasicBlock *Exit = nullptr; 5814 for (auto *SBB : successors(ExitingBlock)) 5815 if (!L->contains(SBB)) { 5816 if (Exit) // Multiple exit successors. 5817 return getCouldNotCompute(); 5818 Exit = SBB; 5819 } else if (SBB != L->getHeader()) { 5820 MustExecuteLoopHeader = false; 5821 } 5822 5823 // At this point, we know we have a conditional branch that determines whether 5824 // the loop is exited. However, we don't know if the branch is executed each 5825 // time through the loop. If not, then the execution count of the branch will 5826 // not be equal to the trip count of the loop. 5827 // 5828 // Currently we check for this by checking to see if the Exit branch goes to 5829 // the loop header. If so, we know it will always execute the same number of 5830 // times as the loop. We also handle the case where the exit block *is* the 5831 // loop header. This is common for un-rotated loops. 5832 // 5833 // If both of those tests fail, walk up the unique predecessor chain to the 5834 // header, stopping if there is an edge that doesn't exit the loop. If the 5835 // header is reached, the execution count of the branch will be equal to the 5836 // trip count of the loop. 5837 // 5838 // More extensive analysis could be done to handle more cases here. 5839 // 5840 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 5841 // The simple checks failed, try climbing the unique predecessor chain 5842 // up to the header. 5843 bool Ok = false; 5844 for (BasicBlock *BB = ExitingBlock; BB; ) { 5845 BasicBlock *Pred = BB->getUniquePredecessor(); 5846 if (!Pred) 5847 return getCouldNotCompute(); 5848 TerminatorInst *PredTerm = Pred->getTerminator(); 5849 for (const BasicBlock *PredSucc : PredTerm->successors()) { 5850 if (PredSucc == BB) 5851 continue; 5852 // If the predecessor has a successor that isn't BB and isn't 5853 // outside the loop, assume the worst. 5854 if (L->contains(PredSucc)) 5855 return getCouldNotCompute(); 5856 } 5857 if (Pred == L->getHeader()) { 5858 Ok = true; 5859 break; 5860 } 5861 BB = Pred; 5862 } 5863 if (!Ok) 5864 return getCouldNotCompute(); 5865 } 5866 5867 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 5868 TerminatorInst *Term = ExitingBlock->getTerminator(); 5869 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 5870 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 5871 // Proceed to the next level to examine the exit condition expression. 5872 return computeExitLimitFromCond( 5873 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), 5874 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 5875 } 5876 5877 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 5878 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 5879 /*ControlsExit=*/IsOnlyExit); 5880 5881 return getCouldNotCompute(); 5882 } 5883 5884 ScalarEvolution::ExitLimit 5885 ScalarEvolution::computeExitLimitFromCond(const Loop *L, 5886 Value *ExitCond, 5887 BasicBlock *TBB, 5888 BasicBlock *FBB, 5889 bool ControlsExit, 5890 bool AllowPredicates) { 5891 // Check if the controlling expression for this loop is an And or Or. 5892 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 5893 if (BO->getOpcode() == Instruction::And) { 5894 // Recurse on the operands of the and. 5895 bool EitherMayExit = L->contains(TBB); 5896 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5897 ControlsExit && !EitherMayExit, 5898 AllowPredicates); 5899 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5900 ControlsExit && !EitherMayExit, 5901 AllowPredicates); 5902 const SCEV *BECount = getCouldNotCompute(); 5903 const SCEV *MaxBECount = getCouldNotCompute(); 5904 if (EitherMayExit) { 5905 // Both conditions must be true for the loop to continue executing. 5906 // Choose the less conservative count. 5907 if (EL0.ExactNotTaken == getCouldNotCompute() || 5908 EL1.ExactNotTaken == getCouldNotCompute()) 5909 BECount = getCouldNotCompute(); 5910 else 5911 BECount = 5912 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 5913 if (EL0.MaxNotTaken == getCouldNotCompute()) 5914 MaxBECount = EL1.MaxNotTaken; 5915 else if (EL1.MaxNotTaken == getCouldNotCompute()) 5916 MaxBECount = EL0.MaxNotTaken; 5917 else 5918 MaxBECount = 5919 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 5920 } else { 5921 // Both conditions must be true at the same time for the loop to exit. 5922 // For now, be conservative. 5923 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 5924 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 5925 MaxBECount = EL0.MaxNotTaken; 5926 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 5927 BECount = EL0.ExactNotTaken; 5928 } 5929 5930 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 5931 // to be more aggressive when computing BECount than when computing 5932 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 5933 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 5934 // to not. 5935 if (isa<SCEVCouldNotCompute>(MaxBECount) && 5936 !isa<SCEVCouldNotCompute>(BECount)) 5937 MaxBECount = BECount; 5938 5939 return ExitLimit(BECount, MaxBECount, false, 5940 {&EL0.Predicates, &EL1.Predicates}); 5941 } 5942 if (BO->getOpcode() == Instruction::Or) { 5943 // Recurse on the operands of the or. 5944 bool EitherMayExit = L->contains(FBB); 5945 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5946 ControlsExit && !EitherMayExit, 5947 AllowPredicates); 5948 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5949 ControlsExit && !EitherMayExit, 5950 AllowPredicates); 5951 const SCEV *BECount = getCouldNotCompute(); 5952 const SCEV *MaxBECount = getCouldNotCompute(); 5953 if (EitherMayExit) { 5954 // Both conditions must be false for the loop to continue executing. 5955 // Choose the less conservative count. 5956 if (EL0.ExactNotTaken == getCouldNotCompute() || 5957 EL1.ExactNotTaken == getCouldNotCompute()) 5958 BECount = getCouldNotCompute(); 5959 else 5960 BECount = 5961 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 5962 if (EL0.MaxNotTaken == getCouldNotCompute()) 5963 MaxBECount = EL1.MaxNotTaken; 5964 else if (EL1.MaxNotTaken == getCouldNotCompute()) 5965 MaxBECount = EL0.MaxNotTaken; 5966 else 5967 MaxBECount = 5968 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 5969 } else { 5970 // Both conditions must be false at the same time for the loop to exit. 5971 // For now, be conservative. 5972 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 5973 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 5974 MaxBECount = EL0.MaxNotTaken; 5975 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 5976 BECount = EL0.ExactNotTaken; 5977 } 5978 5979 return ExitLimit(BECount, MaxBECount, false, 5980 {&EL0.Predicates, &EL1.Predicates}); 5981 } 5982 } 5983 5984 // With an icmp, it may be feasible to compute an exact backedge-taken count. 5985 // Proceed to the next level to examine the icmp. 5986 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 5987 ExitLimit EL = 5988 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 5989 if (EL.hasFullInfo() || !AllowPredicates) 5990 return EL; 5991 5992 // Try again, but use SCEV predicates this time. 5993 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, 5994 /*AllowPredicates=*/true); 5995 } 5996 5997 // Check for a constant condition. These are normally stripped out by 5998 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 5999 // preserve the CFG and is temporarily leaving constant conditions 6000 // in place. 6001 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 6002 if (L->contains(FBB) == !CI->getZExtValue()) 6003 // The backedge is always taken. 6004 return getCouldNotCompute(); 6005 else 6006 // The backedge is never taken. 6007 return getZero(CI->getType()); 6008 } 6009 6010 // If it's not an integer or pointer comparison then compute it the hard way. 6011 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6012 } 6013 6014 ScalarEvolution::ExitLimit 6015 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 6016 ICmpInst *ExitCond, 6017 BasicBlock *TBB, 6018 BasicBlock *FBB, 6019 bool ControlsExit, 6020 bool AllowPredicates) { 6021 6022 // If the condition was exit on true, convert the condition to exit on false 6023 ICmpInst::Predicate Cond; 6024 if (!L->contains(FBB)) 6025 Cond = ExitCond->getPredicate(); 6026 else 6027 Cond = ExitCond->getInversePredicate(); 6028 6029 // Handle common loops like: for (X = "string"; *X; ++X) 6030 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 6031 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 6032 ExitLimit ItCnt = 6033 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); 6034 if (ItCnt.hasAnyInfo()) 6035 return ItCnt; 6036 } 6037 6038 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 6039 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 6040 6041 // Try to evaluate any dependencies out of the loop. 6042 LHS = getSCEVAtScope(LHS, L); 6043 RHS = getSCEVAtScope(RHS, L); 6044 6045 // At this point, we would like to compute how many iterations of the 6046 // loop the predicate will return true for these inputs. 6047 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 6048 // If there is a loop-invariant, force it into the RHS. 6049 std::swap(LHS, RHS); 6050 Cond = ICmpInst::getSwappedPredicate(Cond); 6051 } 6052 6053 // Simplify the operands before analyzing them. 6054 (void)SimplifyICmpOperands(Cond, LHS, RHS); 6055 6056 // If we have a comparison of a chrec against a constant, try to use value 6057 // ranges to answer this query. 6058 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 6059 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 6060 if (AddRec->getLoop() == L) { 6061 // Form the constant range. 6062 ConstantRange CompRange = 6063 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt()); 6064 6065 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 6066 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 6067 } 6068 6069 switch (Cond) { 6070 case ICmpInst::ICMP_NE: { // while (X != Y) 6071 // Convert to: while (X-Y != 0) 6072 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 6073 AllowPredicates); 6074 if (EL.hasAnyInfo()) return EL; 6075 break; 6076 } 6077 case ICmpInst::ICMP_EQ: { // while (X == Y) 6078 // Convert to: while (X-Y == 0) 6079 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 6080 if (EL.hasAnyInfo()) return EL; 6081 break; 6082 } 6083 case ICmpInst::ICMP_SLT: 6084 case ICmpInst::ICMP_ULT: { // while (X < Y) 6085 bool IsSigned = Cond == ICmpInst::ICMP_SLT; 6086 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 6087 AllowPredicates); 6088 if (EL.hasAnyInfo()) return EL; 6089 break; 6090 } 6091 case ICmpInst::ICMP_SGT: 6092 case ICmpInst::ICMP_UGT: { // while (X > Y) 6093 bool IsSigned = Cond == ICmpInst::ICMP_SGT; 6094 ExitLimit EL = 6095 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 6096 AllowPredicates); 6097 if (EL.hasAnyInfo()) return EL; 6098 break; 6099 } 6100 default: 6101 break; 6102 } 6103 6104 auto *ExhaustiveCount = 6105 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6106 6107 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 6108 return ExhaustiveCount; 6109 6110 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 6111 ExitCond->getOperand(1), L, Cond); 6112 } 6113 6114 ScalarEvolution::ExitLimit 6115 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 6116 SwitchInst *Switch, 6117 BasicBlock *ExitingBlock, 6118 bool ControlsExit) { 6119 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 6120 6121 // Give up if the exit is the default dest of a switch. 6122 if (Switch->getDefaultDest() == ExitingBlock) 6123 return getCouldNotCompute(); 6124 6125 assert(L->contains(Switch->getDefaultDest()) && 6126 "Default case must not exit the loop!"); 6127 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 6128 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 6129 6130 // while (X != Y) --> while (X-Y != 0) 6131 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 6132 if (EL.hasAnyInfo()) 6133 return EL; 6134 6135 return getCouldNotCompute(); 6136 } 6137 6138 static ConstantInt * 6139 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 6140 ScalarEvolution &SE) { 6141 const SCEV *InVal = SE.getConstant(C); 6142 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 6143 assert(isa<SCEVConstant>(Val) && 6144 "Evaluation of SCEV at constant didn't fold correctly?"); 6145 return cast<SCEVConstant>(Val)->getValue(); 6146 } 6147 6148 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 6149 /// compute the backedge execution count. 6150 ScalarEvolution::ExitLimit 6151 ScalarEvolution::computeLoadConstantCompareExitLimit( 6152 LoadInst *LI, 6153 Constant *RHS, 6154 const Loop *L, 6155 ICmpInst::Predicate predicate) { 6156 6157 if (LI->isVolatile()) return getCouldNotCompute(); 6158 6159 // Check to see if the loaded pointer is a getelementptr of a global. 6160 // TODO: Use SCEV instead of manually grubbing with GEPs. 6161 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 6162 if (!GEP) return getCouldNotCompute(); 6163 6164 // Make sure that it is really a constant global we are gepping, with an 6165 // initializer, and make sure the first IDX is really 0. 6166 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 6167 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 6168 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 6169 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 6170 return getCouldNotCompute(); 6171 6172 // Okay, we allow one non-constant index into the GEP instruction. 6173 Value *VarIdx = nullptr; 6174 std::vector<Constant*> Indexes; 6175 unsigned VarIdxNum = 0; 6176 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 6177 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 6178 Indexes.push_back(CI); 6179 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 6180 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 6181 VarIdx = GEP->getOperand(i); 6182 VarIdxNum = i-2; 6183 Indexes.push_back(nullptr); 6184 } 6185 6186 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 6187 if (!VarIdx) 6188 return getCouldNotCompute(); 6189 6190 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 6191 // Check to see if X is a loop variant variable value now. 6192 const SCEV *Idx = getSCEV(VarIdx); 6193 Idx = getSCEVAtScope(Idx, L); 6194 6195 // We can only recognize very limited forms of loop index expressions, in 6196 // particular, only affine AddRec's like {C1,+,C2}. 6197 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 6198 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 6199 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 6200 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 6201 return getCouldNotCompute(); 6202 6203 unsigned MaxSteps = MaxBruteForceIterations; 6204 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 6205 ConstantInt *ItCst = ConstantInt::get( 6206 cast<IntegerType>(IdxExpr->getType()), IterationNum); 6207 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 6208 6209 // Form the GEP offset. 6210 Indexes[VarIdxNum] = Val; 6211 6212 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 6213 Indexes); 6214 if (!Result) break; // Cannot compute! 6215 6216 // Evaluate the condition for this iteration. 6217 Result = ConstantExpr::getICmp(predicate, Result, RHS); 6218 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 6219 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 6220 ++NumArrayLenItCounts; 6221 return getConstant(ItCst); // Found terminating iteration! 6222 } 6223 } 6224 return getCouldNotCompute(); 6225 } 6226 6227 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 6228 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 6229 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 6230 if (!RHS) 6231 return getCouldNotCompute(); 6232 6233 const BasicBlock *Latch = L->getLoopLatch(); 6234 if (!Latch) 6235 return getCouldNotCompute(); 6236 6237 const BasicBlock *Predecessor = L->getLoopPredecessor(); 6238 if (!Predecessor) 6239 return getCouldNotCompute(); 6240 6241 // Return true if V is of the form "LHS `shift_op` <positive constant>". 6242 // Return LHS in OutLHS and shift_opt in OutOpCode. 6243 auto MatchPositiveShift = 6244 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 6245 6246 using namespace PatternMatch; 6247 6248 ConstantInt *ShiftAmt; 6249 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6250 OutOpCode = Instruction::LShr; 6251 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6252 OutOpCode = Instruction::AShr; 6253 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6254 OutOpCode = Instruction::Shl; 6255 else 6256 return false; 6257 6258 return ShiftAmt->getValue().isStrictlyPositive(); 6259 }; 6260 6261 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 6262 // 6263 // loop: 6264 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 6265 // %iv.shifted = lshr i32 %iv, <positive constant> 6266 // 6267 // Return true on a successful match. Return the corresponding PHI node (%iv 6268 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 6269 auto MatchShiftRecurrence = 6270 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 6271 Optional<Instruction::BinaryOps> PostShiftOpCode; 6272 6273 { 6274 Instruction::BinaryOps OpC; 6275 Value *V; 6276 6277 // If we encounter a shift instruction, "peel off" the shift operation, 6278 // and remember that we did so. Later when we inspect %iv's backedge 6279 // value, we will make sure that the backedge value uses the same 6280 // operation. 6281 // 6282 // Note: the peeled shift operation does not have to be the same 6283 // instruction as the one feeding into the PHI's backedge value. We only 6284 // really care about it being the same *kind* of shift instruction -- 6285 // that's all that is required for our later inferences to hold. 6286 if (MatchPositiveShift(LHS, V, OpC)) { 6287 PostShiftOpCode = OpC; 6288 LHS = V; 6289 } 6290 } 6291 6292 PNOut = dyn_cast<PHINode>(LHS); 6293 if (!PNOut || PNOut->getParent() != L->getHeader()) 6294 return false; 6295 6296 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 6297 Value *OpLHS; 6298 6299 return 6300 // The backedge value for the PHI node must be a shift by a positive 6301 // amount 6302 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 6303 6304 // of the PHI node itself 6305 OpLHS == PNOut && 6306 6307 // and the kind of shift should be match the kind of shift we peeled 6308 // off, if any. 6309 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 6310 }; 6311 6312 PHINode *PN; 6313 Instruction::BinaryOps OpCode; 6314 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 6315 return getCouldNotCompute(); 6316 6317 const DataLayout &DL = getDataLayout(); 6318 6319 // The key rationale for this optimization is that for some kinds of shift 6320 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 6321 // within a finite number of iterations. If the condition guarding the 6322 // backedge (in the sense that the backedge is taken if the condition is true) 6323 // is false for the value the shift recurrence stabilizes to, then we know 6324 // that the backedge is taken only a finite number of times. 6325 6326 ConstantInt *StableValue = nullptr; 6327 switch (OpCode) { 6328 default: 6329 llvm_unreachable("Impossible case!"); 6330 6331 case Instruction::AShr: { 6332 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 6333 // bitwidth(K) iterations. 6334 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 6335 bool KnownZero, KnownOne; 6336 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, 6337 Predecessor->getTerminator(), &DT); 6338 auto *Ty = cast<IntegerType>(RHS->getType()); 6339 if (KnownZero) 6340 StableValue = ConstantInt::get(Ty, 0); 6341 else if (KnownOne) 6342 StableValue = ConstantInt::get(Ty, -1, true); 6343 else 6344 return getCouldNotCompute(); 6345 6346 break; 6347 } 6348 case Instruction::LShr: 6349 case Instruction::Shl: 6350 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 6351 // stabilize to 0 in at most bitwidth(K) iterations. 6352 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 6353 break; 6354 } 6355 6356 auto *Result = 6357 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 6358 assert(Result->getType()->isIntegerTy(1) && 6359 "Otherwise cannot be an operand to a branch instruction"); 6360 6361 if (Result->isZeroValue()) { 6362 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 6363 const SCEV *UpperBound = 6364 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 6365 return ExitLimit(getCouldNotCompute(), UpperBound, false); 6366 } 6367 6368 return getCouldNotCompute(); 6369 } 6370 6371 /// Return true if we can constant fold an instruction of the specified type, 6372 /// assuming that all operands were constants. 6373 static bool CanConstantFold(const Instruction *I) { 6374 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 6375 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 6376 isa<LoadInst>(I)) 6377 return true; 6378 6379 if (const CallInst *CI = dyn_cast<CallInst>(I)) 6380 if (const Function *F = CI->getCalledFunction()) 6381 return canConstantFoldCallTo(F); 6382 return false; 6383 } 6384 6385 /// Determine whether this instruction can constant evolve within this loop 6386 /// assuming its operands can all constant evolve. 6387 static bool canConstantEvolve(Instruction *I, const Loop *L) { 6388 // An instruction outside of the loop can't be derived from a loop PHI. 6389 if (!L->contains(I)) return false; 6390 6391 if (isa<PHINode>(I)) { 6392 // We don't currently keep track of the control flow needed to evaluate 6393 // PHIs, so we cannot handle PHIs inside of loops. 6394 return L->getHeader() == I->getParent(); 6395 } 6396 6397 // If we won't be able to constant fold this expression even if the operands 6398 // are constants, bail early. 6399 return CanConstantFold(I); 6400 } 6401 6402 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 6403 /// recursing through each instruction operand until reaching a loop header phi. 6404 static PHINode * 6405 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 6406 DenseMap<Instruction *, PHINode *> &PHIMap) { 6407 6408 // Otherwise, we can evaluate this instruction if all of its operands are 6409 // constant or derived from a PHI node themselves. 6410 PHINode *PHI = nullptr; 6411 for (Value *Op : UseInst->operands()) { 6412 if (isa<Constant>(Op)) continue; 6413 6414 Instruction *OpInst = dyn_cast<Instruction>(Op); 6415 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 6416 6417 PHINode *P = dyn_cast<PHINode>(OpInst); 6418 if (!P) 6419 // If this operand is already visited, reuse the prior result. 6420 // We may have P != PHI if this is the deepest point at which the 6421 // inconsistent paths meet. 6422 P = PHIMap.lookup(OpInst); 6423 if (!P) { 6424 // Recurse and memoize the results, whether a phi is found or not. 6425 // This recursive call invalidates pointers into PHIMap. 6426 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap); 6427 PHIMap[OpInst] = P; 6428 } 6429 if (!P) 6430 return nullptr; // Not evolving from PHI 6431 if (PHI && PHI != P) 6432 return nullptr; // Evolving from multiple different PHIs. 6433 PHI = P; 6434 } 6435 // This is a expression evolving from a constant PHI! 6436 return PHI; 6437 } 6438 6439 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 6440 /// in the loop that V is derived from. We allow arbitrary operations along the 6441 /// way, but the operands of an operation must either be constants or a value 6442 /// derived from a constant PHI. If this expression does not fit with these 6443 /// constraints, return null. 6444 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 6445 Instruction *I = dyn_cast<Instruction>(V); 6446 if (!I || !canConstantEvolve(I, L)) return nullptr; 6447 6448 if (PHINode *PN = dyn_cast<PHINode>(I)) 6449 return PN; 6450 6451 // Record non-constant instructions contained by the loop. 6452 DenseMap<Instruction *, PHINode *> PHIMap; 6453 return getConstantEvolvingPHIOperands(I, L, PHIMap); 6454 } 6455 6456 /// EvaluateExpression - Given an expression that passes the 6457 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 6458 /// in the loop has the value PHIVal. If we can't fold this expression for some 6459 /// reason, return null. 6460 static Constant *EvaluateExpression(Value *V, const Loop *L, 6461 DenseMap<Instruction *, Constant *> &Vals, 6462 const DataLayout &DL, 6463 const TargetLibraryInfo *TLI) { 6464 // Convenient constant check, but redundant for recursive calls. 6465 if (Constant *C = dyn_cast<Constant>(V)) return C; 6466 Instruction *I = dyn_cast<Instruction>(V); 6467 if (!I) return nullptr; 6468 6469 if (Constant *C = Vals.lookup(I)) return C; 6470 6471 // An instruction inside the loop depends on a value outside the loop that we 6472 // weren't given a mapping for, or a value such as a call inside the loop. 6473 if (!canConstantEvolve(I, L)) return nullptr; 6474 6475 // An unmapped PHI can be due to a branch or another loop inside this loop, 6476 // or due to this not being the initial iteration through a loop where we 6477 // couldn't compute the evolution of this particular PHI last time. 6478 if (isa<PHINode>(I)) return nullptr; 6479 6480 std::vector<Constant*> Operands(I->getNumOperands()); 6481 6482 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 6483 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 6484 if (!Operand) { 6485 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 6486 if (!Operands[i]) return nullptr; 6487 continue; 6488 } 6489 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 6490 Vals[Operand] = C; 6491 if (!C) return nullptr; 6492 Operands[i] = C; 6493 } 6494 6495 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 6496 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6497 Operands[1], DL, TLI); 6498 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 6499 if (!LI->isVolatile()) 6500 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6501 } 6502 return ConstantFoldInstOperands(I, Operands, DL, TLI); 6503 } 6504 6505 6506 // If every incoming value to PN except the one for BB is a specific Constant, 6507 // return that, else return nullptr. 6508 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 6509 Constant *IncomingVal = nullptr; 6510 6511 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 6512 if (PN->getIncomingBlock(i) == BB) 6513 continue; 6514 6515 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 6516 if (!CurrentVal) 6517 return nullptr; 6518 6519 if (IncomingVal != CurrentVal) { 6520 if (IncomingVal) 6521 return nullptr; 6522 IncomingVal = CurrentVal; 6523 } 6524 } 6525 6526 return IncomingVal; 6527 } 6528 6529 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 6530 /// in the header of its containing loop, we know the loop executes a 6531 /// constant number of times, and the PHI node is just a recurrence 6532 /// involving constants, fold it. 6533 Constant * 6534 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 6535 const APInt &BEs, 6536 const Loop *L) { 6537 auto I = ConstantEvolutionLoopExitValue.find(PN); 6538 if (I != ConstantEvolutionLoopExitValue.end()) 6539 return I->second; 6540 6541 if (BEs.ugt(MaxBruteForceIterations)) 6542 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 6543 6544 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 6545 6546 DenseMap<Instruction *, Constant *> CurrentIterVals; 6547 BasicBlock *Header = L->getHeader(); 6548 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6549 6550 BasicBlock *Latch = L->getLoopLatch(); 6551 if (!Latch) 6552 return nullptr; 6553 6554 for (auto &I : *Header) { 6555 PHINode *PHI = dyn_cast<PHINode>(&I); 6556 if (!PHI) break; 6557 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6558 if (!StartCST) continue; 6559 CurrentIterVals[PHI] = StartCST; 6560 } 6561 if (!CurrentIterVals.count(PN)) 6562 return RetVal = nullptr; 6563 6564 Value *BEValue = PN->getIncomingValueForBlock(Latch); 6565 6566 // Execute the loop symbolically to determine the exit value. 6567 if (BEs.getActiveBits() >= 32) 6568 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! 6569 6570 unsigned NumIterations = BEs.getZExtValue(); // must be in range 6571 unsigned IterationNum = 0; 6572 const DataLayout &DL = getDataLayout(); 6573 for (; ; ++IterationNum) { 6574 if (IterationNum == NumIterations) 6575 return RetVal = CurrentIterVals[PN]; // Got exit value! 6576 6577 // Compute the value of the PHIs for the next iteration. 6578 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 6579 DenseMap<Instruction *, Constant *> NextIterVals; 6580 Constant *NextPHI = 6581 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6582 if (!NextPHI) 6583 return nullptr; // Couldn't evaluate! 6584 NextIterVals[PN] = NextPHI; 6585 6586 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 6587 6588 // Also evaluate the other PHI nodes. However, we don't get to stop if we 6589 // cease to be able to evaluate one of them or if they stop evolving, 6590 // because that doesn't necessarily prevent us from computing PN. 6591 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 6592 for (const auto &I : CurrentIterVals) { 6593 PHINode *PHI = dyn_cast<PHINode>(I.first); 6594 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 6595 PHIsToCompute.emplace_back(PHI, I.second); 6596 } 6597 // We use two distinct loops because EvaluateExpression may invalidate any 6598 // iterators into CurrentIterVals. 6599 for (const auto &I : PHIsToCompute) { 6600 PHINode *PHI = I.first; 6601 Constant *&NextPHI = NextIterVals[PHI]; 6602 if (!NextPHI) { // Not already computed. 6603 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6604 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6605 } 6606 if (NextPHI != I.second) 6607 StoppedEvolving = false; 6608 } 6609 6610 // If all entries in CurrentIterVals == NextIterVals then we can stop 6611 // iterating, the loop can't continue to change. 6612 if (StoppedEvolving) 6613 return RetVal = CurrentIterVals[PN]; 6614 6615 CurrentIterVals.swap(NextIterVals); 6616 } 6617 } 6618 6619 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 6620 Value *Cond, 6621 bool ExitWhen) { 6622 PHINode *PN = getConstantEvolvingPHI(Cond, L); 6623 if (!PN) return getCouldNotCompute(); 6624 6625 // If the loop is canonicalized, the PHI will have exactly two entries. 6626 // That's the only form we support here. 6627 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 6628 6629 DenseMap<Instruction *, Constant *> CurrentIterVals; 6630 BasicBlock *Header = L->getHeader(); 6631 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6632 6633 BasicBlock *Latch = L->getLoopLatch(); 6634 assert(Latch && "Should follow from NumIncomingValues == 2!"); 6635 6636 for (auto &I : *Header) { 6637 PHINode *PHI = dyn_cast<PHINode>(&I); 6638 if (!PHI) 6639 break; 6640 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6641 if (!StartCST) continue; 6642 CurrentIterVals[PHI] = StartCST; 6643 } 6644 if (!CurrentIterVals.count(PN)) 6645 return getCouldNotCompute(); 6646 6647 // Okay, we find a PHI node that defines the trip count of this loop. Execute 6648 // the loop symbolically to determine when the condition gets a value of 6649 // "ExitWhen". 6650 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 6651 const DataLayout &DL = getDataLayout(); 6652 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 6653 auto *CondVal = dyn_cast_or_null<ConstantInt>( 6654 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 6655 6656 // Couldn't symbolically evaluate. 6657 if (!CondVal) return getCouldNotCompute(); 6658 6659 if (CondVal->getValue() == uint64_t(ExitWhen)) { 6660 ++NumBruteForceTripCountsComputed; 6661 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 6662 } 6663 6664 // Update all the PHI nodes for the next iteration. 6665 DenseMap<Instruction *, Constant *> NextIterVals; 6666 6667 // Create a list of which PHIs we need to compute. We want to do this before 6668 // calling EvaluateExpression on them because that may invalidate iterators 6669 // into CurrentIterVals. 6670 SmallVector<PHINode *, 8> PHIsToCompute; 6671 for (const auto &I : CurrentIterVals) { 6672 PHINode *PHI = dyn_cast<PHINode>(I.first); 6673 if (!PHI || PHI->getParent() != Header) continue; 6674 PHIsToCompute.push_back(PHI); 6675 } 6676 for (PHINode *PHI : PHIsToCompute) { 6677 Constant *&NextPHI = NextIterVals[PHI]; 6678 if (NextPHI) continue; // Already computed! 6679 6680 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6681 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6682 } 6683 CurrentIterVals.swap(NextIterVals); 6684 } 6685 6686 // Too many iterations were needed to evaluate. 6687 return getCouldNotCompute(); 6688 } 6689 6690 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 6691 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 6692 ValuesAtScopes[V]; 6693 // Check to see if we've folded this expression at this loop before. 6694 for (auto &LS : Values) 6695 if (LS.first == L) 6696 return LS.second ? LS.second : V; 6697 6698 Values.emplace_back(L, nullptr); 6699 6700 // Otherwise compute it. 6701 const SCEV *C = computeSCEVAtScope(V, L); 6702 for (auto &LS : reverse(ValuesAtScopes[V])) 6703 if (LS.first == L) { 6704 LS.second = C; 6705 break; 6706 } 6707 return C; 6708 } 6709 6710 /// This builds up a Constant using the ConstantExpr interface. That way, we 6711 /// will return Constants for objects which aren't represented by a 6712 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 6713 /// Returns NULL if the SCEV isn't representable as a Constant. 6714 static Constant *BuildConstantFromSCEV(const SCEV *V) { 6715 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 6716 case scCouldNotCompute: 6717 case scAddRecExpr: 6718 break; 6719 case scConstant: 6720 return cast<SCEVConstant>(V)->getValue(); 6721 case scUnknown: 6722 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 6723 case scSignExtend: { 6724 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 6725 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 6726 return ConstantExpr::getSExt(CastOp, SS->getType()); 6727 break; 6728 } 6729 case scZeroExtend: { 6730 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 6731 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 6732 return ConstantExpr::getZExt(CastOp, SZ->getType()); 6733 break; 6734 } 6735 case scTruncate: { 6736 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 6737 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 6738 return ConstantExpr::getTrunc(CastOp, ST->getType()); 6739 break; 6740 } 6741 case scAddExpr: { 6742 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 6743 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 6744 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6745 unsigned AS = PTy->getAddressSpace(); 6746 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6747 C = ConstantExpr::getBitCast(C, DestPtrTy); 6748 } 6749 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 6750 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 6751 if (!C2) return nullptr; 6752 6753 // First pointer! 6754 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 6755 unsigned AS = C2->getType()->getPointerAddressSpace(); 6756 std::swap(C, C2); 6757 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6758 // The offsets have been converted to bytes. We can add bytes to an 6759 // i8* by GEP with the byte count in the first index. 6760 C = ConstantExpr::getBitCast(C, DestPtrTy); 6761 } 6762 6763 // Don't bother trying to sum two pointers. We probably can't 6764 // statically compute a load that results from it anyway. 6765 if (C2->getType()->isPointerTy()) 6766 return nullptr; 6767 6768 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6769 if (PTy->getElementType()->isStructTy()) 6770 C2 = ConstantExpr::getIntegerCast( 6771 C2, Type::getInt32Ty(C->getContext()), true); 6772 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 6773 } else 6774 C = ConstantExpr::getAdd(C, C2); 6775 } 6776 return C; 6777 } 6778 break; 6779 } 6780 case scMulExpr: { 6781 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 6782 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 6783 // Don't bother with pointers at all. 6784 if (C->getType()->isPointerTy()) return nullptr; 6785 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 6786 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 6787 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 6788 C = ConstantExpr::getMul(C, C2); 6789 } 6790 return C; 6791 } 6792 break; 6793 } 6794 case scUDivExpr: { 6795 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 6796 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 6797 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 6798 if (LHS->getType() == RHS->getType()) 6799 return ConstantExpr::getUDiv(LHS, RHS); 6800 break; 6801 } 6802 case scSMaxExpr: 6803 case scUMaxExpr: 6804 break; // TODO: smax, umax. 6805 } 6806 return nullptr; 6807 } 6808 6809 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 6810 if (isa<SCEVConstant>(V)) return V; 6811 6812 // If this instruction is evolved from a constant-evolving PHI, compute the 6813 // exit value from the loop without using SCEVs. 6814 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 6815 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 6816 const Loop *LI = this->LI[I->getParent()]; 6817 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 6818 if (PHINode *PN = dyn_cast<PHINode>(I)) 6819 if (PN->getParent() == LI->getHeader()) { 6820 // Okay, there is no closed form solution for the PHI node. Check 6821 // to see if the loop that contains it has a known backedge-taken 6822 // count. If so, we may be able to force computation of the exit 6823 // value. 6824 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 6825 if (const SCEVConstant *BTCC = 6826 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 6827 // Okay, we know how many times the containing loop executes. If 6828 // this is a constant evolving PHI node, get the final value at 6829 // the specified iteration number. 6830 Constant *RV = 6831 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 6832 if (RV) return getSCEV(RV); 6833 } 6834 } 6835 6836 // Okay, this is an expression that we cannot symbolically evaluate 6837 // into a SCEV. Check to see if it's possible to symbolically evaluate 6838 // the arguments into constants, and if so, try to constant propagate the 6839 // result. This is particularly useful for computing loop exit values. 6840 if (CanConstantFold(I)) { 6841 SmallVector<Constant *, 4> Operands; 6842 bool MadeImprovement = false; 6843 for (Value *Op : I->operands()) { 6844 if (Constant *C = dyn_cast<Constant>(Op)) { 6845 Operands.push_back(C); 6846 continue; 6847 } 6848 6849 // If any of the operands is non-constant and if they are 6850 // non-integer and non-pointer, don't even try to analyze them 6851 // with scev techniques. 6852 if (!isSCEVable(Op->getType())) 6853 return V; 6854 6855 const SCEV *OrigV = getSCEV(Op); 6856 const SCEV *OpV = getSCEVAtScope(OrigV, L); 6857 MadeImprovement |= OrigV != OpV; 6858 6859 Constant *C = BuildConstantFromSCEV(OpV); 6860 if (!C) return V; 6861 if (C->getType() != Op->getType()) 6862 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 6863 Op->getType(), 6864 false), 6865 C, Op->getType()); 6866 Operands.push_back(C); 6867 } 6868 6869 // Check to see if getSCEVAtScope actually made an improvement. 6870 if (MadeImprovement) { 6871 Constant *C = nullptr; 6872 const DataLayout &DL = getDataLayout(); 6873 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 6874 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6875 Operands[1], DL, &TLI); 6876 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 6877 if (!LI->isVolatile()) 6878 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6879 } else 6880 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 6881 if (!C) return V; 6882 return getSCEV(C); 6883 } 6884 } 6885 } 6886 6887 // This is some other type of SCEVUnknown, just return it. 6888 return V; 6889 } 6890 6891 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 6892 // Avoid performing the look-up in the common case where the specified 6893 // expression has no loop-variant portions. 6894 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 6895 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 6896 if (OpAtScope != Comm->getOperand(i)) { 6897 // Okay, at least one of these operands is loop variant but might be 6898 // foldable. Build a new instance of the folded commutative expression. 6899 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 6900 Comm->op_begin()+i); 6901 NewOps.push_back(OpAtScope); 6902 6903 for (++i; i != e; ++i) { 6904 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 6905 NewOps.push_back(OpAtScope); 6906 } 6907 if (isa<SCEVAddExpr>(Comm)) 6908 return getAddExpr(NewOps); 6909 if (isa<SCEVMulExpr>(Comm)) 6910 return getMulExpr(NewOps); 6911 if (isa<SCEVSMaxExpr>(Comm)) 6912 return getSMaxExpr(NewOps); 6913 if (isa<SCEVUMaxExpr>(Comm)) 6914 return getUMaxExpr(NewOps); 6915 llvm_unreachable("Unknown commutative SCEV type!"); 6916 } 6917 } 6918 // If we got here, all operands are loop invariant. 6919 return Comm; 6920 } 6921 6922 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 6923 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 6924 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 6925 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 6926 return Div; // must be loop invariant 6927 return getUDivExpr(LHS, RHS); 6928 } 6929 6930 // If this is a loop recurrence for a loop that does not contain L, then we 6931 // are dealing with the final value computed by the loop. 6932 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 6933 // First, attempt to evaluate each operand. 6934 // Avoid performing the look-up in the common case where the specified 6935 // expression has no loop-variant portions. 6936 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 6937 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 6938 if (OpAtScope == AddRec->getOperand(i)) 6939 continue; 6940 6941 // Okay, at least one of these operands is loop variant but might be 6942 // foldable. Build a new instance of the folded commutative expression. 6943 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 6944 AddRec->op_begin()+i); 6945 NewOps.push_back(OpAtScope); 6946 for (++i; i != e; ++i) 6947 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 6948 6949 const SCEV *FoldedRec = 6950 getAddRecExpr(NewOps, AddRec->getLoop(), 6951 AddRec->getNoWrapFlags(SCEV::FlagNW)); 6952 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 6953 // The addrec may be folded to a nonrecurrence, for example, if the 6954 // induction variable is multiplied by zero after constant folding. Go 6955 // ahead and return the folded value. 6956 if (!AddRec) 6957 return FoldedRec; 6958 break; 6959 } 6960 6961 // If the scope is outside the addrec's loop, evaluate it by using the 6962 // loop exit value of the addrec. 6963 if (!AddRec->getLoop()->contains(L)) { 6964 // To evaluate this recurrence, we need to know how many times the AddRec 6965 // loop iterates. Compute this now. 6966 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 6967 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 6968 6969 // Then, evaluate the AddRec. 6970 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 6971 } 6972 6973 return AddRec; 6974 } 6975 6976 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 6977 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6978 if (Op == Cast->getOperand()) 6979 return Cast; // must be loop invariant 6980 return getZeroExtendExpr(Op, Cast->getType()); 6981 } 6982 6983 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 6984 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6985 if (Op == Cast->getOperand()) 6986 return Cast; // must be loop invariant 6987 return getSignExtendExpr(Op, Cast->getType()); 6988 } 6989 6990 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 6991 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6992 if (Op == Cast->getOperand()) 6993 return Cast; // must be loop invariant 6994 return getTruncateExpr(Op, Cast->getType()); 6995 } 6996 6997 llvm_unreachable("Unknown SCEV type!"); 6998 } 6999 7000 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 7001 return getSCEVAtScope(getSCEV(V), L); 7002 } 7003 7004 /// Finds the minimum unsigned root of the following equation: 7005 /// 7006 /// A * X = B (mod N) 7007 /// 7008 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 7009 /// A and B isn't important. 7010 /// 7011 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 7012 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, 7013 ScalarEvolution &SE) { 7014 uint32_t BW = A.getBitWidth(); 7015 assert(BW == B.getBitWidth() && "Bit widths must be the same."); 7016 assert(A != 0 && "A must be non-zero."); 7017 7018 // 1. D = gcd(A, N) 7019 // 7020 // The gcd of A and N may have only one prime factor: 2. The number of 7021 // trailing zeros in A is its multiplicity 7022 uint32_t Mult2 = A.countTrailingZeros(); 7023 // D = 2^Mult2 7024 7025 // 2. Check if B is divisible by D. 7026 // 7027 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 7028 // is not less than multiplicity of this prime factor for D. 7029 if (B.countTrailingZeros() < Mult2) 7030 return SE.getCouldNotCompute(); 7031 7032 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 7033 // modulo (N / D). 7034 // 7035 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this 7036 // bit width during computations. 7037 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 7038 APInt Mod(BW + 1, 0); 7039 Mod.setBit(BW - Mult2); // Mod = N / D 7040 APInt I = AD.multiplicativeInverse(Mod); 7041 7042 // 4. Compute the minimum unsigned root of the equation: 7043 // I * (B / D) mod (N / D) 7044 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); 7045 7046 // The result is guaranteed to be less than 2^BW so we may truncate it to BW 7047 // bits. 7048 return SE.getConstant(Result.trunc(BW)); 7049 } 7050 7051 /// Find the roots of the quadratic equation for the given quadratic chrec 7052 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 7053 /// two SCEVCouldNotCompute objects. 7054 /// 7055 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 7056 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 7057 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 7058 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 7059 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 7060 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 7061 7062 // We currently can only solve this if the coefficients are constants. 7063 if (!LC || !MC || !NC) 7064 return None; 7065 7066 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 7067 const APInt &L = LC->getAPInt(); 7068 const APInt &M = MC->getAPInt(); 7069 const APInt &N = NC->getAPInt(); 7070 APInt Two(BitWidth, 2); 7071 APInt Four(BitWidth, 4); 7072 7073 { 7074 using namespace APIntOps; 7075 const APInt& C = L; 7076 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 7077 // The B coefficient is M-N/2 7078 APInt B(M); 7079 B -= sdiv(N,Two); 7080 7081 // The A coefficient is N/2 7082 APInt A(N.sdiv(Two)); 7083 7084 // Compute the B^2-4ac term. 7085 APInt SqrtTerm(B); 7086 SqrtTerm *= B; 7087 SqrtTerm -= Four * (A * C); 7088 7089 if (SqrtTerm.isNegative()) { 7090 // The loop is provably infinite. 7091 return None; 7092 } 7093 7094 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 7095 // integer value or else APInt::sqrt() will assert. 7096 APInt SqrtVal(SqrtTerm.sqrt()); 7097 7098 // Compute the two solutions for the quadratic formula. 7099 // The divisions must be performed as signed divisions. 7100 APInt NegB(-B); 7101 APInt TwoA(A << 1); 7102 if (TwoA.isMinValue()) 7103 return None; 7104 7105 LLVMContext &Context = SE.getContext(); 7106 7107 ConstantInt *Solution1 = 7108 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 7109 ConstantInt *Solution2 = 7110 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 7111 7112 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 7113 cast<SCEVConstant>(SE.getConstant(Solution2))); 7114 } // end APIntOps namespace 7115 } 7116 7117 ScalarEvolution::ExitLimit 7118 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 7119 bool AllowPredicates) { 7120 7121 // This is only used for loops with a "x != y" exit test. The exit condition 7122 // is now expressed as a single expression, V = x-y. So the exit test is 7123 // effectively V != 0. We know and take advantage of the fact that this 7124 // expression only being used in a comparison by zero context. 7125 7126 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 7127 // If the value is a constant 7128 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7129 // If the value is already zero, the branch will execute zero times. 7130 if (C->getValue()->isZero()) return C; 7131 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7132 } 7133 7134 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 7135 if (!AddRec && AllowPredicates) 7136 // Try to make this an AddRec using runtime tests, in the first X 7137 // iterations of this loop, where X is the SCEV expression found by the 7138 // algorithm below. 7139 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 7140 7141 if (!AddRec || AddRec->getLoop() != L) 7142 return getCouldNotCompute(); 7143 7144 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 7145 // the quadratic equation to solve it. 7146 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 7147 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 7148 const SCEVConstant *R1 = Roots->first; 7149 const SCEVConstant *R2 = Roots->second; 7150 // Pick the smallest positive root value. 7151 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 7152 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 7153 if (!CB->getZExtValue()) 7154 std::swap(R1, R2); // R1 is the minimum root now. 7155 7156 // We can only use this value if the chrec ends up with an exact zero 7157 // value at this index. When solving for "X*X != 5", for example, we 7158 // should not accept a root of 2. 7159 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 7160 if (Val->isZero()) 7161 // We found a quadratic root! 7162 return ExitLimit(R1, R1, false, Predicates); 7163 } 7164 } 7165 return getCouldNotCompute(); 7166 } 7167 7168 // Otherwise we can only handle this if it is affine. 7169 if (!AddRec->isAffine()) 7170 return getCouldNotCompute(); 7171 7172 // If this is an affine expression, the execution count of this branch is 7173 // the minimum unsigned root of the following equation: 7174 // 7175 // Start + Step*N = 0 (mod 2^BW) 7176 // 7177 // equivalent to: 7178 // 7179 // Step*N = -Start (mod 2^BW) 7180 // 7181 // where BW is the common bit width of Start and Step. 7182 7183 // Get the initial value for the loop. 7184 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 7185 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 7186 7187 // For now we handle only constant steps. 7188 // 7189 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 7190 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 7191 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 7192 // We have not yet seen any such cases. 7193 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 7194 if (!StepC || StepC->getValue()->equalsInt(0)) 7195 return getCouldNotCompute(); 7196 7197 // For positive steps (counting up until unsigned overflow): 7198 // N = -Start/Step (as unsigned) 7199 // For negative steps (counting down to zero): 7200 // N = Start/-Step 7201 // First compute the unsigned distance from zero in the direction of Step. 7202 bool CountDown = StepC->getAPInt().isNegative(); 7203 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 7204 7205 // Handle unitary steps, which cannot wraparound. 7206 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 7207 // N = Distance (as unsigned) 7208 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { 7209 APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax(); 7210 7211 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 7212 // we end up with a loop whose backedge-taken count is n - 1. Detect this 7213 // case, and see if we can improve the bound. 7214 // 7215 // Explicitly handling this here is necessary because getUnsignedRange 7216 // isn't context-sensitive; it doesn't know that we only care about the 7217 // range inside the loop. 7218 const SCEV *Zero = getZero(Distance->getType()); 7219 const SCEV *One = getOne(Distance->getType()); 7220 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 7221 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 7222 // If Distance + 1 doesn't overflow, we can compute the maximum distance 7223 // as "unsigned_max(Distance + 1) - 1". 7224 ConstantRange CR = getUnsignedRange(DistancePlusOne); 7225 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 7226 } 7227 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 7228 } 7229 7230 // As a special case, handle the instance where Step is a positive power of 7231 // two. In this case, determining whether Step divides Distance evenly can be 7232 // done by counting and comparing the number of trailing zeros of Step and 7233 // Distance. 7234 if (!CountDown) { 7235 const APInt &StepV = StepC->getAPInt(); 7236 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It 7237 // also returns true if StepV is maximally negative (eg, INT_MIN), but that 7238 // case is not handled as this code is guarded by !CountDown. 7239 if (StepV.isPowerOf2() && 7240 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) { 7241 // Here we've constrained the equation to be of the form 7242 // 7243 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0) 7244 // 7245 // where we're operating on a W bit wide integer domain and k is 7246 // non-negative. The smallest unsigned solution for X is the trip count. 7247 // 7248 // (0) is equivalent to: 7249 // 7250 // 2^(N + k) * Distance' - 2^N * X = L * 2^W 7251 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N 7252 // <=> 2^k * Distance' - X = L * 2^(W - N) 7253 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1) 7254 // 7255 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS 7256 // by 2^(W - N). 7257 // 7258 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2) 7259 // 7260 // E.g. say we're solving 7261 // 7262 // 2 * Val = 2 * X (in i8) ... (3) 7263 // 7264 // then from (2), we get X = Val URem i8 128 (k = 0 in this case). 7265 // 7266 // Note: It is tempting to solve (3) by setting X = Val, but Val is not 7267 // necessarily the smallest unsigned value of X that satisfies (3). 7268 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3) 7269 // is i8 1, not i8 -127 7270 7271 const auto *ModuloResult = getUDivExactExpr(Distance, Step); 7272 7273 // Since SCEV does not have a URem node, we construct one using a truncate 7274 // and a zero extend. 7275 7276 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros(); 7277 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth); 7278 auto *WideTy = Distance->getType(); 7279 7280 const SCEV *Limit = 7281 getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy); 7282 return ExitLimit(Limit, Limit, false, Predicates); 7283 } 7284 } 7285 7286 // If the condition controls loop exit (the loop exits only if the expression 7287 // is true) and the addition is no-wrap we can use unsigned divide to 7288 // compute the backedge count. In this case, the step may not divide the 7289 // distance, but we don't care because if the condition is "missed" the loop 7290 // will have undefined behavior due to wrapping. 7291 if (ControlsExit && AddRec->hasNoSelfWrap() && 7292 loopHasNoAbnormalExits(AddRec->getLoop())) { 7293 const SCEV *Exact = 7294 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 7295 return ExitLimit(Exact, Exact, false, Predicates); 7296 } 7297 7298 // Then, try to solve the above equation provided that Start is constant. 7299 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) { 7300 const SCEV *E = SolveLinEquationWithOverflow( 7301 StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this); 7302 return ExitLimit(E, E, false, Predicates); 7303 } 7304 return getCouldNotCompute(); 7305 } 7306 7307 ScalarEvolution::ExitLimit 7308 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 7309 // Loops that look like: while (X == 0) are very strange indeed. We don't 7310 // handle them yet except for the trivial case. This could be expanded in the 7311 // future as needed. 7312 7313 // If the value is a constant, check to see if it is known to be non-zero 7314 // already. If so, the backedge will execute zero times. 7315 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7316 if (!C->getValue()->isNullValue()) 7317 return getZero(C->getType()); 7318 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7319 } 7320 7321 // We could implement others, but I really doubt anyone writes loops like 7322 // this, and if they did, they would already be constant folded. 7323 return getCouldNotCompute(); 7324 } 7325 7326 std::pair<BasicBlock *, BasicBlock *> 7327 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 7328 // If the block has a unique predecessor, then there is no path from the 7329 // predecessor to the block that does not go through the direct edge 7330 // from the predecessor to the block. 7331 if (BasicBlock *Pred = BB->getSinglePredecessor()) 7332 return {Pred, BB}; 7333 7334 // A loop's header is defined to be a block that dominates the loop. 7335 // If the header has a unique predecessor outside the loop, it must be 7336 // a block that has exactly one successor that can reach the loop. 7337 if (Loop *L = LI.getLoopFor(BB)) 7338 return {L->getLoopPredecessor(), L->getHeader()}; 7339 7340 return {nullptr, nullptr}; 7341 } 7342 7343 /// SCEV structural equivalence is usually sufficient for testing whether two 7344 /// expressions are equal, however for the purposes of looking for a condition 7345 /// guarding a loop, it can be useful to be a little more general, since a 7346 /// front-end may have replicated the controlling expression. 7347 /// 7348 static bool HasSameValue(const SCEV *A, const SCEV *B) { 7349 // Quick check to see if they are the same SCEV. 7350 if (A == B) return true; 7351 7352 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 7353 // Not all instructions that are "identical" compute the same value. For 7354 // instance, two distinct alloca instructions allocating the same type are 7355 // identical and do not read memory; but compute distinct values. 7356 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 7357 }; 7358 7359 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 7360 // two different instructions with the same value. Check for this case. 7361 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 7362 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 7363 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 7364 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 7365 if (ComputesEqualValues(AI, BI)) 7366 return true; 7367 7368 // Otherwise assume they may have a different value. 7369 return false; 7370 } 7371 7372 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 7373 const SCEV *&LHS, const SCEV *&RHS, 7374 unsigned Depth) { 7375 bool Changed = false; 7376 7377 // If we hit the max recursion limit bail out. 7378 if (Depth >= 3) 7379 return false; 7380 7381 // Canonicalize a constant to the right side. 7382 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 7383 // Check for both operands constant. 7384 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 7385 if (ConstantExpr::getICmp(Pred, 7386 LHSC->getValue(), 7387 RHSC->getValue())->isNullValue()) 7388 goto trivially_false; 7389 else 7390 goto trivially_true; 7391 } 7392 // Otherwise swap the operands to put the constant on the right. 7393 std::swap(LHS, RHS); 7394 Pred = ICmpInst::getSwappedPredicate(Pred); 7395 Changed = true; 7396 } 7397 7398 // If we're comparing an addrec with a value which is loop-invariant in the 7399 // addrec's loop, put the addrec on the left. Also make a dominance check, 7400 // as both operands could be addrecs loop-invariant in each other's loop. 7401 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 7402 const Loop *L = AR->getLoop(); 7403 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 7404 std::swap(LHS, RHS); 7405 Pred = ICmpInst::getSwappedPredicate(Pred); 7406 Changed = true; 7407 } 7408 } 7409 7410 // If there's a constant operand, canonicalize comparisons with boundary 7411 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 7412 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 7413 const APInt &RA = RC->getAPInt(); 7414 7415 bool SimplifiedByConstantRange = false; 7416 7417 if (!ICmpInst::isEquality(Pred)) { 7418 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 7419 if (ExactCR.isFullSet()) 7420 goto trivially_true; 7421 else if (ExactCR.isEmptySet()) 7422 goto trivially_false; 7423 7424 APInt NewRHS; 7425 CmpInst::Predicate NewPred; 7426 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 7427 ICmpInst::isEquality(NewPred)) { 7428 // We were able to convert an inequality to an equality. 7429 Pred = NewPred; 7430 RHS = getConstant(NewRHS); 7431 Changed = SimplifiedByConstantRange = true; 7432 } 7433 } 7434 7435 if (!SimplifiedByConstantRange) { 7436 switch (Pred) { 7437 default: 7438 break; 7439 case ICmpInst::ICMP_EQ: 7440 case ICmpInst::ICMP_NE: 7441 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 7442 if (!RA) 7443 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 7444 if (const SCEVMulExpr *ME = 7445 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 7446 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 7447 ME->getOperand(0)->isAllOnesValue()) { 7448 RHS = AE->getOperand(1); 7449 LHS = ME->getOperand(1); 7450 Changed = true; 7451 } 7452 break; 7453 7454 7455 // The "Should have been caught earlier!" messages refer to the fact 7456 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 7457 // should have fired on the corresponding cases, and canonicalized the 7458 // check to trivially_true or trivially_false. 7459 7460 case ICmpInst::ICMP_UGE: 7461 assert(!RA.isMinValue() && "Should have been caught earlier!"); 7462 Pred = ICmpInst::ICMP_UGT; 7463 RHS = getConstant(RA - 1); 7464 Changed = true; 7465 break; 7466 case ICmpInst::ICMP_ULE: 7467 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 7468 Pred = ICmpInst::ICMP_ULT; 7469 RHS = getConstant(RA + 1); 7470 Changed = true; 7471 break; 7472 case ICmpInst::ICMP_SGE: 7473 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 7474 Pred = ICmpInst::ICMP_SGT; 7475 RHS = getConstant(RA - 1); 7476 Changed = true; 7477 break; 7478 case ICmpInst::ICMP_SLE: 7479 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 7480 Pred = ICmpInst::ICMP_SLT; 7481 RHS = getConstant(RA + 1); 7482 Changed = true; 7483 break; 7484 } 7485 } 7486 } 7487 7488 // Check for obvious equality. 7489 if (HasSameValue(LHS, RHS)) { 7490 if (ICmpInst::isTrueWhenEqual(Pred)) 7491 goto trivially_true; 7492 if (ICmpInst::isFalseWhenEqual(Pred)) 7493 goto trivially_false; 7494 } 7495 7496 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 7497 // adding or subtracting 1 from one of the operands. 7498 switch (Pred) { 7499 case ICmpInst::ICMP_SLE: 7500 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { 7501 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7502 SCEV::FlagNSW); 7503 Pred = ICmpInst::ICMP_SLT; 7504 Changed = true; 7505 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { 7506 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 7507 SCEV::FlagNSW); 7508 Pred = ICmpInst::ICMP_SLT; 7509 Changed = true; 7510 } 7511 break; 7512 case ICmpInst::ICMP_SGE: 7513 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { 7514 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 7515 SCEV::FlagNSW); 7516 Pred = ICmpInst::ICMP_SGT; 7517 Changed = true; 7518 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { 7519 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7520 SCEV::FlagNSW); 7521 Pred = ICmpInst::ICMP_SGT; 7522 Changed = true; 7523 } 7524 break; 7525 case ICmpInst::ICMP_ULE: 7526 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { 7527 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7528 SCEV::FlagNUW); 7529 Pred = ICmpInst::ICMP_ULT; 7530 Changed = true; 7531 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { 7532 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 7533 Pred = ICmpInst::ICMP_ULT; 7534 Changed = true; 7535 } 7536 break; 7537 case ICmpInst::ICMP_UGE: 7538 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { 7539 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 7540 Pred = ICmpInst::ICMP_UGT; 7541 Changed = true; 7542 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { 7543 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7544 SCEV::FlagNUW); 7545 Pred = ICmpInst::ICMP_UGT; 7546 Changed = true; 7547 } 7548 break; 7549 default: 7550 break; 7551 } 7552 7553 // TODO: More simplifications are possible here. 7554 7555 // Recursively simplify until we either hit a recursion limit or nothing 7556 // changes. 7557 if (Changed) 7558 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 7559 7560 return Changed; 7561 7562 trivially_true: 7563 // Return 0 == 0. 7564 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7565 Pred = ICmpInst::ICMP_EQ; 7566 return true; 7567 7568 trivially_false: 7569 // Return 0 != 0. 7570 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7571 Pred = ICmpInst::ICMP_NE; 7572 return true; 7573 } 7574 7575 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 7576 return getSignedRange(S).getSignedMax().isNegative(); 7577 } 7578 7579 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 7580 return getSignedRange(S).getSignedMin().isStrictlyPositive(); 7581 } 7582 7583 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 7584 return !getSignedRange(S).getSignedMin().isNegative(); 7585 } 7586 7587 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 7588 return !getSignedRange(S).getSignedMax().isStrictlyPositive(); 7589 } 7590 7591 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 7592 return isKnownNegative(S) || isKnownPositive(S); 7593 } 7594 7595 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 7596 const SCEV *LHS, const SCEV *RHS) { 7597 // Canonicalize the inputs first. 7598 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7599 7600 // If LHS or RHS is an addrec, check to see if the condition is true in 7601 // every iteration of the loop. 7602 // If LHS and RHS are both addrec, both conditions must be true in 7603 // every iteration of the loop. 7604 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 7605 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 7606 bool LeftGuarded = false; 7607 bool RightGuarded = false; 7608 if (LAR) { 7609 const Loop *L = LAR->getLoop(); 7610 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 7611 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 7612 if (!RAR) return true; 7613 LeftGuarded = true; 7614 } 7615 } 7616 if (RAR) { 7617 const Loop *L = RAR->getLoop(); 7618 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 7619 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 7620 if (!LAR) return true; 7621 RightGuarded = true; 7622 } 7623 } 7624 if (LeftGuarded && RightGuarded) 7625 return true; 7626 7627 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 7628 return true; 7629 7630 // Otherwise see what can be done with known constant ranges. 7631 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); 7632 } 7633 7634 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 7635 ICmpInst::Predicate Pred, 7636 bool &Increasing) { 7637 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 7638 7639 #ifndef NDEBUG 7640 // Verify an invariant: inverting the predicate should turn a monotonically 7641 // increasing change to a monotonically decreasing one, and vice versa. 7642 bool IncreasingSwapped; 7643 bool ResultSwapped = isMonotonicPredicateImpl( 7644 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 7645 7646 assert(Result == ResultSwapped && "should be able to analyze both!"); 7647 if (ResultSwapped) 7648 assert(Increasing == !IncreasingSwapped && 7649 "monotonicity should flip as we flip the predicate"); 7650 #endif 7651 7652 return Result; 7653 } 7654 7655 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 7656 ICmpInst::Predicate Pred, 7657 bool &Increasing) { 7658 7659 // A zero step value for LHS means the induction variable is essentially a 7660 // loop invariant value. We don't really depend on the predicate actually 7661 // flipping from false to true (for increasing predicates, and the other way 7662 // around for decreasing predicates), all we care about is that *if* the 7663 // predicate changes then it only changes from false to true. 7664 // 7665 // A zero step value in itself is not very useful, but there may be places 7666 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 7667 // as general as possible. 7668 7669 switch (Pred) { 7670 default: 7671 return false; // Conservative answer 7672 7673 case ICmpInst::ICMP_UGT: 7674 case ICmpInst::ICMP_UGE: 7675 case ICmpInst::ICMP_ULT: 7676 case ICmpInst::ICMP_ULE: 7677 if (!LHS->hasNoUnsignedWrap()) 7678 return false; 7679 7680 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 7681 return true; 7682 7683 case ICmpInst::ICMP_SGT: 7684 case ICmpInst::ICMP_SGE: 7685 case ICmpInst::ICMP_SLT: 7686 case ICmpInst::ICMP_SLE: { 7687 if (!LHS->hasNoSignedWrap()) 7688 return false; 7689 7690 const SCEV *Step = LHS->getStepRecurrence(*this); 7691 7692 if (isKnownNonNegative(Step)) { 7693 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 7694 return true; 7695 } 7696 7697 if (isKnownNonPositive(Step)) { 7698 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 7699 return true; 7700 } 7701 7702 return false; 7703 } 7704 7705 } 7706 7707 llvm_unreachable("switch has default clause!"); 7708 } 7709 7710 bool ScalarEvolution::isLoopInvariantPredicate( 7711 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 7712 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 7713 const SCEV *&InvariantRHS) { 7714 7715 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 7716 if (!isLoopInvariant(RHS, L)) { 7717 if (!isLoopInvariant(LHS, L)) 7718 return false; 7719 7720 std::swap(LHS, RHS); 7721 Pred = ICmpInst::getSwappedPredicate(Pred); 7722 } 7723 7724 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 7725 if (!ArLHS || ArLHS->getLoop() != L) 7726 return false; 7727 7728 bool Increasing; 7729 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 7730 return false; 7731 7732 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 7733 // true as the loop iterates, and the backedge is control dependent on 7734 // "ArLHS `Pred` RHS" == true then we can reason as follows: 7735 // 7736 // * if the predicate was false in the first iteration then the predicate 7737 // is never evaluated again, since the loop exits without taking the 7738 // backedge. 7739 // * if the predicate was true in the first iteration then it will 7740 // continue to be true for all future iterations since it is 7741 // monotonically increasing. 7742 // 7743 // For both the above possibilities, we can replace the loop varying 7744 // predicate with its value on the first iteration of the loop (which is 7745 // loop invariant). 7746 // 7747 // A similar reasoning applies for a monotonically decreasing predicate, by 7748 // replacing true with false and false with true in the above two bullets. 7749 7750 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 7751 7752 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 7753 return false; 7754 7755 InvariantPred = Pred; 7756 InvariantLHS = ArLHS->getStart(); 7757 InvariantRHS = RHS; 7758 return true; 7759 } 7760 7761 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 7762 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 7763 if (HasSameValue(LHS, RHS)) 7764 return ICmpInst::isTrueWhenEqual(Pred); 7765 7766 // This code is split out from isKnownPredicate because it is called from 7767 // within isLoopEntryGuardedByCond. 7768 7769 auto CheckRanges = 7770 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 7771 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 7772 .contains(RangeLHS); 7773 }; 7774 7775 // The check at the top of the function catches the case where the values are 7776 // known to be equal. 7777 if (Pred == CmpInst::ICMP_EQ) 7778 return false; 7779 7780 if (Pred == CmpInst::ICMP_NE) 7781 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 7782 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 7783 isKnownNonZero(getMinusSCEV(LHS, RHS)); 7784 7785 if (CmpInst::isSigned(Pred)) 7786 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 7787 7788 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 7789 } 7790 7791 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 7792 const SCEV *LHS, 7793 const SCEV *RHS) { 7794 7795 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 7796 // Return Y via OutY. 7797 auto MatchBinaryAddToConst = 7798 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 7799 SCEV::NoWrapFlags ExpectedFlags) { 7800 const SCEV *NonConstOp, *ConstOp; 7801 SCEV::NoWrapFlags FlagsPresent; 7802 7803 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 7804 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 7805 return false; 7806 7807 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 7808 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 7809 }; 7810 7811 APInt C; 7812 7813 switch (Pred) { 7814 default: 7815 break; 7816 7817 case ICmpInst::ICMP_SGE: 7818 std::swap(LHS, RHS); 7819 case ICmpInst::ICMP_SLE: 7820 // X s<= (X + C)<nsw> if C >= 0 7821 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 7822 return true; 7823 7824 // (X + C)<nsw> s<= X if C <= 0 7825 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 7826 !C.isStrictlyPositive()) 7827 return true; 7828 break; 7829 7830 case ICmpInst::ICMP_SGT: 7831 std::swap(LHS, RHS); 7832 case ICmpInst::ICMP_SLT: 7833 // X s< (X + C)<nsw> if C > 0 7834 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 7835 C.isStrictlyPositive()) 7836 return true; 7837 7838 // (X + C)<nsw> s< X if C < 0 7839 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 7840 return true; 7841 break; 7842 } 7843 7844 return false; 7845 } 7846 7847 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 7848 const SCEV *LHS, 7849 const SCEV *RHS) { 7850 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 7851 return false; 7852 7853 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 7854 // the stack can result in exponential time complexity. 7855 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 7856 7857 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 7858 // 7859 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 7860 // isKnownPredicate. isKnownPredicate is more powerful, but also more 7861 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 7862 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 7863 // use isKnownPredicate later if needed. 7864 return isKnownNonNegative(RHS) && 7865 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 7866 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 7867 } 7868 7869 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 7870 ICmpInst::Predicate Pred, 7871 const SCEV *LHS, const SCEV *RHS) { 7872 // No need to even try if we know the module has no guards. 7873 if (!HasGuards) 7874 return false; 7875 7876 return any_of(*BB, [&](Instruction &I) { 7877 using namespace llvm::PatternMatch; 7878 7879 Value *Condition; 7880 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 7881 m_Value(Condition))) && 7882 isImpliedCond(Pred, LHS, RHS, Condition, false); 7883 }); 7884 } 7885 7886 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 7887 /// protected by a conditional between LHS and RHS. This is used to 7888 /// to eliminate casts. 7889 bool 7890 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 7891 ICmpInst::Predicate Pred, 7892 const SCEV *LHS, const SCEV *RHS) { 7893 // Interpret a null as meaning no loop, where there is obviously no guard 7894 // (interprocedural conditions notwithstanding). 7895 if (!L) return true; 7896 7897 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 7898 return true; 7899 7900 BasicBlock *Latch = L->getLoopLatch(); 7901 if (!Latch) 7902 return false; 7903 7904 BranchInst *LoopContinuePredicate = 7905 dyn_cast<BranchInst>(Latch->getTerminator()); 7906 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 7907 isImpliedCond(Pred, LHS, RHS, 7908 LoopContinuePredicate->getCondition(), 7909 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 7910 return true; 7911 7912 // We don't want more than one activation of the following loops on the stack 7913 // -- that can lead to O(n!) time complexity. 7914 if (WalkingBEDominatingConds) 7915 return false; 7916 7917 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 7918 7919 // See if we can exploit a trip count to prove the predicate. 7920 const auto &BETakenInfo = getBackedgeTakenInfo(L); 7921 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 7922 if (LatchBECount != getCouldNotCompute()) { 7923 // We know that Latch branches back to the loop header exactly 7924 // LatchBECount times. This means the backdege condition at Latch is 7925 // equivalent to "{0,+,1} u< LatchBECount". 7926 Type *Ty = LatchBECount->getType(); 7927 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 7928 const SCEV *LoopCounter = 7929 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 7930 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 7931 LatchBECount)) 7932 return true; 7933 } 7934 7935 // Check conditions due to any @llvm.assume intrinsics. 7936 for (auto &AssumeVH : AC.assumptions()) { 7937 if (!AssumeVH) 7938 continue; 7939 auto *CI = cast<CallInst>(AssumeVH); 7940 if (!DT.dominates(CI, Latch->getTerminator())) 7941 continue; 7942 7943 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 7944 return true; 7945 } 7946 7947 // If the loop is not reachable from the entry block, we risk running into an 7948 // infinite loop as we walk up into the dom tree. These loops do not matter 7949 // anyway, so we just return a conservative answer when we see them. 7950 if (!DT.isReachableFromEntry(L->getHeader())) 7951 return false; 7952 7953 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 7954 return true; 7955 7956 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 7957 DTN != HeaderDTN; DTN = DTN->getIDom()) { 7958 7959 assert(DTN && "should reach the loop header before reaching the root!"); 7960 7961 BasicBlock *BB = DTN->getBlock(); 7962 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 7963 return true; 7964 7965 BasicBlock *PBB = BB->getSinglePredecessor(); 7966 if (!PBB) 7967 continue; 7968 7969 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 7970 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 7971 continue; 7972 7973 Value *Condition = ContinuePredicate->getCondition(); 7974 7975 // If we have an edge `E` within the loop body that dominates the only 7976 // latch, the condition guarding `E` also guards the backedge. This 7977 // reasoning works only for loops with a single latch. 7978 7979 BasicBlockEdge DominatingEdge(PBB, BB); 7980 if (DominatingEdge.isSingleEdge()) { 7981 // We're constructively (and conservatively) enumerating edges within the 7982 // loop body that dominate the latch. The dominator tree better agree 7983 // with us on this: 7984 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 7985 7986 if (isImpliedCond(Pred, LHS, RHS, Condition, 7987 BB != ContinuePredicate->getSuccessor(0))) 7988 return true; 7989 } 7990 } 7991 7992 return false; 7993 } 7994 7995 bool 7996 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 7997 ICmpInst::Predicate Pred, 7998 const SCEV *LHS, const SCEV *RHS) { 7999 // Interpret a null as meaning no loop, where there is obviously no guard 8000 // (interprocedural conditions notwithstanding). 8001 if (!L) return false; 8002 8003 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 8004 return true; 8005 8006 // Starting at the loop predecessor, climb up the predecessor chain, as long 8007 // as there are predecessors that can be found that have unique successors 8008 // leading to the original header. 8009 for (std::pair<BasicBlock *, BasicBlock *> 8010 Pair(L->getLoopPredecessor(), L->getHeader()); 8011 Pair.first; 8012 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 8013 8014 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) 8015 return true; 8016 8017 BranchInst *LoopEntryPredicate = 8018 dyn_cast<BranchInst>(Pair.first->getTerminator()); 8019 if (!LoopEntryPredicate || 8020 LoopEntryPredicate->isUnconditional()) 8021 continue; 8022 8023 if (isImpliedCond(Pred, LHS, RHS, 8024 LoopEntryPredicate->getCondition(), 8025 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 8026 return true; 8027 } 8028 8029 // Check conditions due to any @llvm.assume intrinsics. 8030 for (auto &AssumeVH : AC.assumptions()) { 8031 if (!AssumeVH) 8032 continue; 8033 auto *CI = cast<CallInst>(AssumeVH); 8034 if (!DT.dominates(CI, L->getHeader())) 8035 continue; 8036 8037 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8038 return true; 8039 } 8040 8041 return false; 8042 } 8043 8044 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 8045 const SCEV *LHS, const SCEV *RHS, 8046 Value *FoundCondValue, 8047 bool Inverse) { 8048 if (!PendingLoopPredicates.insert(FoundCondValue).second) 8049 return false; 8050 8051 auto ClearOnExit = 8052 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 8053 8054 // Recursively handle And and Or conditions. 8055 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 8056 if (BO->getOpcode() == Instruction::And) { 8057 if (!Inverse) 8058 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8059 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8060 } else if (BO->getOpcode() == Instruction::Or) { 8061 if (Inverse) 8062 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8063 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8064 } 8065 } 8066 8067 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 8068 if (!ICI) return false; 8069 8070 // Now that we found a conditional branch that dominates the loop or controls 8071 // the loop latch. Check to see if it is the comparison we are looking for. 8072 ICmpInst::Predicate FoundPred; 8073 if (Inverse) 8074 FoundPred = ICI->getInversePredicate(); 8075 else 8076 FoundPred = ICI->getPredicate(); 8077 8078 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 8079 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 8080 8081 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 8082 } 8083 8084 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 8085 const SCEV *RHS, 8086 ICmpInst::Predicate FoundPred, 8087 const SCEV *FoundLHS, 8088 const SCEV *FoundRHS) { 8089 // Balance the types. 8090 if (getTypeSizeInBits(LHS->getType()) < 8091 getTypeSizeInBits(FoundLHS->getType())) { 8092 if (CmpInst::isSigned(Pred)) { 8093 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 8094 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 8095 } else { 8096 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 8097 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 8098 } 8099 } else if (getTypeSizeInBits(LHS->getType()) > 8100 getTypeSizeInBits(FoundLHS->getType())) { 8101 if (CmpInst::isSigned(FoundPred)) { 8102 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 8103 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 8104 } else { 8105 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 8106 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 8107 } 8108 } 8109 8110 // Canonicalize the query to match the way instcombine will have 8111 // canonicalized the comparison. 8112 if (SimplifyICmpOperands(Pred, LHS, RHS)) 8113 if (LHS == RHS) 8114 return CmpInst::isTrueWhenEqual(Pred); 8115 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 8116 if (FoundLHS == FoundRHS) 8117 return CmpInst::isFalseWhenEqual(FoundPred); 8118 8119 // Check to see if we can make the LHS or RHS match. 8120 if (LHS == FoundRHS || RHS == FoundLHS) { 8121 if (isa<SCEVConstant>(RHS)) { 8122 std::swap(FoundLHS, FoundRHS); 8123 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 8124 } else { 8125 std::swap(LHS, RHS); 8126 Pred = ICmpInst::getSwappedPredicate(Pred); 8127 } 8128 } 8129 8130 // Check whether the found predicate is the same as the desired predicate. 8131 if (FoundPred == Pred) 8132 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8133 8134 // Check whether swapping the found predicate makes it the same as the 8135 // desired predicate. 8136 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 8137 if (isa<SCEVConstant>(RHS)) 8138 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 8139 else 8140 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 8141 RHS, LHS, FoundLHS, FoundRHS); 8142 } 8143 8144 // Unsigned comparison is the same as signed comparison when both the operands 8145 // are non-negative. 8146 if (CmpInst::isUnsigned(FoundPred) && 8147 CmpInst::getSignedPredicate(FoundPred) == Pred && 8148 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 8149 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8150 8151 // Check if we can make progress by sharpening ranges. 8152 if (FoundPred == ICmpInst::ICMP_NE && 8153 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 8154 8155 const SCEVConstant *C = nullptr; 8156 const SCEV *V = nullptr; 8157 8158 if (isa<SCEVConstant>(FoundLHS)) { 8159 C = cast<SCEVConstant>(FoundLHS); 8160 V = FoundRHS; 8161 } else { 8162 C = cast<SCEVConstant>(FoundRHS); 8163 V = FoundLHS; 8164 } 8165 8166 // The guarding predicate tells us that C != V. If the known range 8167 // of V is [C, t), we can sharpen the range to [C + 1, t). The 8168 // range we consider has to correspond to same signedness as the 8169 // predicate we're interested in folding. 8170 8171 APInt Min = ICmpInst::isSigned(Pred) ? 8172 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); 8173 8174 if (Min == C->getAPInt()) { 8175 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 8176 // This is true even if (Min + 1) wraps around -- in case of 8177 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 8178 8179 APInt SharperMin = Min + 1; 8180 8181 switch (Pred) { 8182 case ICmpInst::ICMP_SGE: 8183 case ICmpInst::ICMP_UGE: 8184 // We know V `Pred` SharperMin. If this implies LHS `Pred` 8185 // RHS, we're done. 8186 if (isImpliedCondOperands(Pred, LHS, RHS, V, 8187 getConstant(SharperMin))) 8188 return true; 8189 8190 case ICmpInst::ICMP_SGT: 8191 case ICmpInst::ICMP_UGT: 8192 // We know from the range information that (V `Pred` Min || 8193 // V == Min). We know from the guarding condition that !(V 8194 // == Min). This gives us 8195 // 8196 // V `Pred` Min || V == Min && !(V == Min) 8197 // => V `Pred` Min 8198 // 8199 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 8200 8201 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 8202 return true; 8203 8204 default: 8205 // No change 8206 break; 8207 } 8208 } 8209 } 8210 8211 // Check whether the actual condition is beyond sufficient. 8212 if (FoundPred == ICmpInst::ICMP_EQ) 8213 if (ICmpInst::isTrueWhenEqual(Pred)) 8214 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8215 return true; 8216 if (Pred == ICmpInst::ICMP_NE) 8217 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 8218 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 8219 return true; 8220 8221 // Otherwise assume the worst. 8222 return false; 8223 } 8224 8225 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 8226 const SCEV *&L, const SCEV *&R, 8227 SCEV::NoWrapFlags &Flags) { 8228 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 8229 if (!AE || AE->getNumOperands() != 2) 8230 return false; 8231 8232 L = AE->getOperand(0); 8233 R = AE->getOperand(1); 8234 Flags = AE->getNoWrapFlags(); 8235 return true; 8236 } 8237 8238 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 8239 const SCEV *Less) { 8240 // We avoid subtracting expressions here because this function is usually 8241 // fairly deep in the call stack (i.e. is called many times). 8242 8243 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 8244 const auto *LAR = cast<SCEVAddRecExpr>(Less); 8245 const auto *MAR = cast<SCEVAddRecExpr>(More); 8246 8247 if (LAR->getLoop() != MAR->getLoop()) 8248 return None; 8249 8250 // We look at affine expressions only; not for correctness but to keep 8251 // getStepRecurrence cheap. 8252 if (!LAR->isAffine() || !MAR->isAffine()) 8253 return None; 8254 8255 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 8256 return None; 8257 8258 Less = LAR->getStart(); 8259 More = MAR->getStart(); 8260 8261 // fall through 8262 } 8263 8264 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 8265 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 8266 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 8267 return M - L; 8268 } 8269 8270 const SCEV *L, *R; 8271 SCEV::NoWrapFlags Flags; 8272 if (splitBinaryAdd(Less, L, R, Flags)) 8273 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8274 if (R == More) 8275 return -(LC->getAPInt()); 8276 8277 if (splitBinaryAdd(More, L, R, Flags)) 8278 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8279 if (R == Less) 8280 return LC->getAPInt(); 8281 8282 return None; 8283 } 8284 8285 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 8286 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 8287 const SCEV *FoundLHS, const SCEV *FoundRHS) { 8288 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 8289 return false; 8290 8291 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8292 if (!AddRecLHS) 8293 return false; 8294 8295 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 8296 if (!AddRecFoundLHS) 8297 return false; 8298 8299 // We'd like to let SCEV reason about control dependencies, so we constrain 8300 // both the inequalities to be about add recurrences on the same loop. This 8301 // way we can use isLoopEntryGuardedByCond later. 8302 8303 const Loop *L = AddRecFoundLHS->getLoop(); 8304 if (L != AddRecLHS->getLoop()) 8305 return false; 8306 8307 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 8308 // 8309 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 8310 // ... (2) 8311 // 8312 // Informal proof for (2), assuming (1) [*]: 8313 // 8314 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 8315 // 8316 // Then 8317 // 8318 // FoundLHS s< FoundRHS s< INT_MIN - C 8319 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 8320 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 8321 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 8322 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 8323 // <=> FoundLHS + C s< FoundRHS + C 8324 // 8325 // [*]: (1) can be proved by ruling out overflow. 8326 // 8327 // [**]: This can be proved by analyzing all the four possibilities: 8328 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 8329 // (A s>= 0, B s>= 0). 8330 // 8331 // Note: 8332 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 8333 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 8334 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 8335 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 8336 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 8337 // C)". 8338 8339 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 8340 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 8341 if (!LDiff || !RDiff || *LDiff != *RDiff) 8342 return false; 8343 8344 if (LDiff->isMinValue()) 8345 return true; 8346 8347 APInt FoundRHSLimit; 8348 8349 if (Pred == CmpInst::ICMP_ULT) { 8350 FoundRHSLimit = -(*RDiff); 8351 } else { 8352 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 8353 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 8354 } 8355 8356 // Try to prove (1) or (2), as needed. 8357 return isLoopEntryGuardedByCond(L, Pred, FoundRHS, 8358 getConstant(FoundRHSLimit)); 8359 } 8360 8361 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 8362 const SCEV *LHS, const SCEV *RHS, 8363 const SCEV *FoundLHS, 8364 const SCEV *FoundRHS) { 8365 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8366 return true; 8367 8368 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8369 return true; 8370 8371 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 8372 FoundLHS, FoundRHS) || 8373 // ~x < ~y --> x > y 8374 isImpliedCondOperandsHelper(Pred, LHS, RHS, 8375 getNotSCEV(FoundRHS), 8376 getNotSCEV(FoundLHS)); 8377 } 8378 8379 8380 /// If Expr computes ~A, return A else return nullptr 8381 static const SCEV *MatchNotExpr(const SCEV *Expr) { 8382 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 8383 if (!Add || Add->getNumOperands() != 2 || 8384 !Add->getOperand(0)->isAllOnesValue()) 8385 return nullptr; 8386 8387 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 8388 if (!AddRHS || AddRHS->getNumOperands() != 2 || 8389 !AddRHS->getOperand(0)->isAllOnesValue()) 8390 return nullptr; 8391 8392 return AddRHS->getOperand(1); 8393 } 8394 8395 8396 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 8397 template<typename MaxExprType> 8398 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 8399 const SCEV *Candidate) { 8400 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 8401 if (!MaxExpr) return false; 8402 8403 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 8404 } 8405 8406 8407 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 8408 template<typename MaxExprType> 8409 static bool IsMinConsistingOf(ScalarEvolution &SE, 8410 const SCEV *MaybeMinExpr, 8411 const SCEV *Candidate) { 8412 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 8413 if (!MaybeMaxExpr) 8414 return false; 8415 8416 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 8417 } 8418 8419 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 8420 ICmpInst::Predicate Pred, 8421 const SCEV *LHS, const SCEV *RHS) { 8422 8423 // If both sides are affine addrecs for the same loop, with equal 8424 // steps, and we know the recurrences don't wrap, then we only 8425 // need to check the predicate on the starting values. 8426 8427 if (!ICmpInst::isRelational(Pred)) 8428 return false; 8429 8430 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 8431 if (!LAR) 8432 return false; 8433 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 8434 if (!RAR) 8435 return false; 8436 if (LAR->getLoop() != RAR->getLoop()) 8437 return false; 8438 if (!LAR->isAffine() || !RAR->isAffine()) 8439 return false; 8440 8441 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 8442 return false; 8443 8444 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 8445 SCEV::FlagNSW : SCEV::FlagNUW; 8446 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 8447 return false; 8448 8449 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 8450 } 8451 8452 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 8453 /// expression? 8454 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 8455 ICmpInst::Predicate Pred, 8456 const SCEV *LHS, const SCEV *RHS) { 8457 switch (Pred) { 8458 default: 8459 return false; 8460 8461 case ICmpInst::ICMP_SGE: 8462 std::swap(LHS, RHS); 8463 LLVM_FALLTHROUGH; 8464 case ICmpInst::ICMP_SLE: 8465 return 8466 // min(A, ...) <= A 8467 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 8468 // A <= max(A, ...) 8469 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 8470 8471 case ICmpInst::ICMP_UGE: 8472 std::swap(LHS, RHS); 8473 LLVM_FALLTHROUGH; 8474 case ICmpInst::ICMP_ULE: 8475 return 8476 // min(A, ...) <= A 8477 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 8478 // A <= max(A, ...) 8479 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 8480 } 8481 8482 llvm_unreachable("covered switch fell through?!"); 8483 } 8484 8485 bool 8486 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 8487 const SCEV *LHS, const SCEV *RHS, 8488 const SCEV *FoundLHS, 8489 const SCEV *FoundRHS) { 8490 auto IsKnownPredicateFull = 8491 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8492 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 8493 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 8494 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 8495 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 8496 }; 8497 8498 switch (Pred) { 8499 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 8500 case ICmpInst::ICMP_EQ: 8501 case ICmpInst::ICMP_NE: 8502 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 8503 return true; 8504 break; 8505 case ICmpInst::ICMP_SLT: 8506 case ICmpInst::ICMP_SLE: 8507 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 8508 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 8509 return true; 8510 break; 8511 case ICmpInst::ICMP_SGT: 8512 case ICmpInst::ICMP_SGE: 8513 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 8514 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 8515 return true; 8516 break; 8517 case ICmpInst::ICMP_ULT: 8518 case ICmpInst::ICMP_ULE: 8519 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 8520 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 8521 return true; 8522 break; 8523 case ICmpInst::ICMP_UGT: 8524 case ICmpInst::ICMP_UGE: 8525 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 8526 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 8527 return true; 8528 break; 8529 } 8530 8531 return false; 8532 } 8533 8534 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 8535 const SCEV *LHS, 8536 const SCEV *RHS, 8537 const SCEV *FoundLHS, 8538 const SCEV *FoundRHS) { 8539 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 8540 // The restriction on `FoundRHS` be lifted easily -- it exists only to 8541 // reduce the compile time impact of this optimization. 8542 return false; 8543 8544 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 8545 if (!Addend) 8546 return false; 8547 8548 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 8549 8550 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 8551 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 8552 ConstantRange FoundLHSRange = 8553 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 8554 8555 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 8556 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 8557 8558 // We can also compute the range of values for `LHS` that satisfy the 8559 // consequent, "`LHS` `Pred` `RHS`": 8560 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 8561 ConstantRange SatisfyingLHSRange = 8562 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 8563 8564 // The antecedent implies the consequent if every value of `LHS` that 8565 // satisfies the antecedent also satisfies the consequent. 8566 return SatisfyingLHSRange.contains(LHSRange); 8567 } 8568 8569 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 8570 bool IsSigned, bool NoWrap) { 8571 assert(isKnownPositive(Stride) && "Positive stride expected!"); 8572 8573 if (NoWrap) return false; 8574 8575 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8576 const SCEV *One = getOne(Stride->getType()); 8577 8578 if (IsSigned) { 8579 APInt MaxRHS = getSignedRange(RHS).getSignedMax(); 8580 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 8581 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8582 .getSignedMax(); 8583 8584 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 8585 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); 8586 } 8587 8588 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); 8589 APInt MaxValue = APInt::getMaxValue(BitWidth); 8590 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8591 .getUnsignedMax(); 8592 8593 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 8594 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); 8595 } 8596 8597 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 8598 bool IsSigned, bool NoWrap) { 8599 if (NoWrap) return false; 8600 8601 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8602 const SCEV *One = getOne(Stride->getType()); 8603 8604 if (IsSigned) { 8605 APInt MinRHS = getSignedRange(RHS).getSignedMin(); 8606 APInt MinValue = APInt::getSignedMinValue(BitWidth); 8607 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8608 .getSignedMax(); 8609 8610 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 8611 return (MinValue + MaxStrideMinusOne).sgt(MinRHS); 8612 } 8613 8614 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); 8615 APInt MinValue = APInt::getMinValue(BitWidth); 8616 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8617 .getUnsignedMax(); 8618 8619 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 8620 return (MinValue + MaxStrideMinusOne).ugt(MinRHS); 8621 } 8622 8623 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 8624 bool Equality) { 8625 const SCEV *One = getOne(Step->getType()); 8626 Delta = Equality ? getAddExpr(Delta, Step) 8627 : getAddExpr(Delta, getMinusSCEV(Step, One)); 8628 return getUDivExpr(Delta, Step); 8629 } 8630 8631 ScalarEvolution::ExitLimit 8632 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 8633 const Loop *L, bool IsSigned, 8634 bool ControlsExit, bool AllowPredicates) { 8635 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8636 // We handle only IV < Invariant 8637 if (!isLoopInvariant(RHS, L)) 8638 return getCouldNotCompute(); 8639 8640 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8641 bool PredicatedIV = false; 8642 8643 if (!IV && AllowPredicates) { 8644 // Try to make this an AddRec using runtime tests, in the first X 8645 // iterations of this loop, where X is the SCEV expression found by the 8646 // algorithm below. 8647 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 8648 PredicatedIV = true; 8649 } 8650 8651 // Avoid weird loops 8652 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8653 return getCouldNotCompute(); 8654 8655 bool NoWrap = ControlsExit && 8656 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8657 8658 const SCEV *Stride = IV->getStepRecurrence(*this); 8659 8660 bool PositiveStride = isKnownPositive(Stride); 8661 8662 // Avoid negative or zero stride values. 8663 if (!PositiveStride) { 8664 // We can compute the correct backedge taken count for loops with unknown 8665 // strides if we can prove that the loop is not an infinite loop with side 8666 // effects. Here's the loop structure we are trying to handle - 8667 // 8668 // i = start 8669 // do { 8670 // A[i] = i; 8671 // i += s; 8672 // } while (i < end); 8673 // 8674 // The backedge taken count for such loops is evaluated as - 8675 // (max(end, start + stride) - start - 1) /u stride 8676 // 8677 // The additional preconditions that we need to check to prove correctness 8678 // of the above formula is as follows - 8679 // 8680 // a) IV is either nuw or nsw depending upon signedness (indicated by the 8681 // NoWrap flag). 8682 // b) loop is single exit with no side effects. 8683 // 8684 // 8685 // Precondition a) implies that if the stride is negative, this is a single 8686 // trip loop. The backedge taken count formula reduces to zero in this case. 8687 // 8688 // Precondition b) implies that the unknown stride cannot be zero otherwise 8689 // we have UB. 8690 // 8691 // The positive stride case is the same as isKnownPositive(Stride) returning 8692 // true (original behavior of the function). 8693 // 8694 // We want to make sure that the stride is truly unknown as there are edge 8695 // cases where ScalarEvolution propagates no wrap flags to the 8696 // post-increment/decrement IV even though the increment/decrement operation 8697 // itself is wrapping. The computed backedge taken count may be wrong in 8698 // such cases. This is prevented by checking that the stride is not known to 8699 // be either positive or non-positive. For example, no wrap flags are 8700 // propagated to the post-increment IV of this loop with a trip count of 2 - 8701 // 8702 // unsigned char i; 8703 // for(i=127; i<128; i+=129) 8704 // A[i] = i; 8705 // 8706 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 8707 !loopHasNoSideEffects(L)) 8708 return getCouldNotCompute(); 8709 8710 } else if (!Stride->isOne() && 8711 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 8712 // Avoid proven overflow cases: this will ensure that the backedge taken 8713 // count will not generate any unsigned overflow. Relaxed no-overflow 8714 // conditions exploit NoWrapFlags, allowing to optimize in presence of 8715 // undefined behaviors like the case of C language. 8716 return getCouldNotCompute(); 8717 8718 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 8719 : ICmpInst::ICMP_ULT; 8720 const SCEV *Start = IV->getStart(); 8721 const SCEV *End = RHS; 8722 // If the backedge is taken at least once, then it will be taken 8723 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 8724 // is the LHS value of the less-than comparison the first time it is evaluated 8725 // and End is the RHS. 8726 const SCEV *BECountIfBackedgeTaken = 8727 computeBECount(getMinusSCEV(End, Start), Stride, false); 8728 // If the loop entry is guarded by the result of the backedge test of the 8729 // first loop iteration, then we know the backedge will be taken at least 8730 // once and so the backedge taken count is as above. If not then we use the 8731 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 8732 // as if the backedge is taken at least once max(End,Start) is End and so the 8733 // result is as above, and if not max(End,Start) is Start so we get a backedge 8734 // count of zero. 8735 const SCEV *BECount; 8736 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 8737 BECount = BECountIfBackedgeTaken; 8738 else { 8739 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 8740 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 8741 } 8742 8743 const SCEV *MaxBECount; 8744 bool MaxOrZero = false; 8745 if (isa<SCEVConstant>(BECount)) 8746 MaxBECount = BECount; 8747 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 8748 // If we know exactly how many times the backedge will be taken if it's 8749 // taken at least once, then the backedge count will either be that or 8750 // zero. 8751 MaxBECount = BECountIfBackedgeTaken; 8752 MaxOrZero = true; 8753 } else { 8754 // Calculate the maximum backedge count based on the range of values 8755 // permitted by Start, End, and Stride. 8756 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() 8757 : getUnsignedRange(Start).getUnsignedMin(); 8758 8759 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8760 8761 APInt StrideForMaxBECount; 8762 8763 if (PositiveStride) 8764 StrideForMaxBECount = 8765 IsSigned ? getSignedRange(Stride).getSignedMin() 8766 : getUnsignedRange(Stride).getUnsignedMin(); 8767 else 8768 // Using a stride of 1 is safe when computing max backedge taken count for 8769 // a loop with unknown stride. 8770 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned); 8771 8772 APInt Limit = 8773 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1) 8774 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1); 8775 8776 // Although End can be a MAX expression we estimate MaxEnd considering only 8777 // the case End = RHS. This is safe because in the other case (End - Start) 8778 // is zero, leading to a zero maximum backedge taken count. 8779 APInt MaxEnd = 8780 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) 8781 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); 8782 8783 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), 8784 getConstant(StrideForMaxBECount), false); 8785 } 8786 8787 if (isa<SCEVCouldNotCompute>(MaxBECount)) 8788 MaxBECount = BECount; 8789 8790 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 8791 } 8792 8793 ScalarEvolution::ExitLimit 8794 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 8795 const Loop *L, bool IsSigned, 8796 bool ControlsExit, bool AllowPredicates) { 8797 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8798 // We handle only IV > Invariant 8799 if (!isLoopInvariant(RHS, L)) 8800 return getCouldNotCompute(); 8801 8802 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8803 if (!IV && AllowPredicates) 8804 // Try to make this an AddRec using runtime tests, in the first X 8805 // iterations of this loop, where X is the SCEV expression found by the 8806 // algorithm below. 8807 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 8808 8809 // Avoid weird loops 8810 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8811 return getCouldNotCompute(); 8812 8813 bool NoWrap = ControlsExit && 8814 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8815 8816 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 8817 8818 // Avoid negative or zero stride values 8819 if (!isKnownPositive(Stride)) 8820 return getCouldNotCompute(); 8821 8822 // Avoid proven overflow cases: this will ensure that the backedge taken count 8823 // will not generate any unsigned overflow. Relaxed no-overflow conditions 8824 // exploit NoWrapFlags, allowing to optimize in presence of undefined 8825 // behaviors like the case of C language. 8826 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 8827 return getCouldNotCompute(); 8828 8829 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 8830 : ICmpInst::ICMP_UGT; 8831 8832 const SCEV *Start = IV->getStart(); 8833 const SCEV *End = RHS; 8834 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 8835 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 8836 8837 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 8838 8839 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() 8840 : getUnsignedRange(Start).getUnsignedMax(); 8841 8842 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() 8843 : getUnsignedRange(Stride).getUnsignedMin(); 8844 8845 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8846 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 8847 : APInt::getMinValue(BitWidth) + (MinStride - 1); 8848 8849 // Although End can be a MIN expression we estimate MinEnd considering only 8850 // the case End = RHS. This is safe because in the other case (Start - End) 8851 // is zero, leading to a zero maximum backedge taken count. 8852 APInt MinEnd = 8853 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) 8854 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); 8855 8856 8857 const SCEV *MaxBECount = getCouldNotCompute(); 8858 if (isa<SCEVConstant>(BECount)) 8859 MaxBECount = BECount; 8860 else 8861 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 8862 getConstant(MinStride), false); 8863 8864 if (isa<SCEVCouldNotCompute>(MaxBECount)) 8865 MaxBECount = BECount; 8866 8867 return ExitLimit(BECount, MaxBECount, false, Predicates); 8868 } 8869 8870 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 8871 ScalarEvolution &SE) const { 8872 if (Range.isFullSet()) // Infinite loop. 8873 return SE.getCouldNotCompute(); 8874 8875 // If the start is a non-zero constant, shift the range to simplify things. 8876 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 8877 if (!SC->getValue()->isZero()) { 8878 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 8879 Operands[0] = SE.getZero(SC->getType()); 8880 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 8881 getNoWrapFlags(FlagNW)); 8882 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 8883 return ShiftedAddRec->getNumIterationsInRange( 8884 Range.subtract(SC->getAPInt()), SE); 8885 // This is strange and shouldn't happen. 8886 return SE.getCouldNotCompute(); 8887 } 8888 8889 // The only time we can solve this is when we have all constant indices. 8890 // Otherwise, we cannot determine the overflow conditions. 8891 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 8892 return SE.getCouldNotCompute(); 8893 8894 // Okay at this point we know that all elements of the chrec are constants and 8895 // that the start element is zero. 8896 8897 // First check to see if the range contains zero. If not, the first 8898 // iteration exits. 8899 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 8900 if (!Range.contains(APInt(BitWidth, 0))) 8901 return SE.getZero(getType()); 8902 8903 if (isAffine()) { 8904 // If this is an affine expression then we have this situation: 8905 // Solve {0,+,A} in Range === Ax in Range 8906 8907 // We know that zero is in the range. If A is positive then we know that 8908 // the upper value of the range must be the first possible exit value. 8909 // If A is negative then the lower of the range is the last possible loop 8910 // value. Also note that we already checked for a full range. 8911 APInt One(BitWidth,1); 8912 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 8913 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); 8914 8915 // The exit value should be (End+A)/A. 8916 APInt ExitVal = (End + A).udiv(A); 8917 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 8918 8919 // Evaluate at the exit value. If we really did fall out of the valid 8920 // range, then we computed our trip count, otherwise wrap around or other 8921 // things must have happened. 8922 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 8923 if (Range.contains(Val->getValue())) 8924 return SE.getCouldNotCompute(); // Something strange happened 8925 8926 // Ensure that the previous value is in the range. This is a sanity check. 8927 assert(Range.contains( 8928 EvaluateConstantChrecAtConstant(this, 8929 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && 8930 "Linear scev computation is off in a bad way!"); 8931 return SE.getConstant(ExitValue); 8932 } else if (isQuadratic()) { 8933 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 8934 // quadratic equation to solve it. To do this, we must frame our problem in 8935 // terms of figuring out when zero is crossed, instead of when 8936 // Range.getUpper() is crossed. 8937 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 8938 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 8939 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 8940 8941 // Next, solve the constructed addrec 8942 if (auto Roots = 8943 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 8944 const SCEVConstant *R1 = Roots->first; 8945 const SCEVConstant *R2 = Roots->second; 8946 // Pick the smallest positive root value. 8947 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 8948 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 8949 if (!CB->getZExtValue()) 8950 std::swap(R1, R2); // R1 is the minimum root now. 8951 8952 // Make sure the root is not off by one. The returned iteration should 8953 // not be in the range, but the previous one should be. When solving 8954 // for "X*X < 5", for example, we should not return a root of 2. 8955 ConstantInt *R1Val = 8956 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 8957 if (Range.contains(R1Val->getValue())) { 8958 // The next iteration must be out of the range... 8959 ConstantInt *NextVal = 8960 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 8961 8962 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 8963 if (!Range.contains(R1Val->getValue())) 8964 return SE.getConstant(NextVal); 8965 return SE.getCouldNotCompute(); // Something strange happened 8966 } 8967 8968 // If R1 was not in the range, then it is a good return value. Make 8969 // sure that R1-1 WAS in the range though, just in case. 8970 ConstantInt *NextVal = 8971 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 8972 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 8973 if (Range.contains(R1Val->getValue())) 8974 return R1; 8975 return SE.getCouldNotCompute(); // Something strange happened 8976 } 8977 } 8978 } 8979 8980 return SE.getCouldNotCompute(); 8981 } 8982 8983 // Return true when S contains at least an undef value. 8984 static inline bool containsUndefs(const SCEV *S) { 8985 return SCEVExprContains(S, [](const SCEV *S) { 8986 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 8987 return isa<UndefValue>(SU->getValue()); 8988 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 8989 return isa<UndefValue>(SC->getValue()); 8990 return false; 8991 }); 8992 } 8993 8994 namespace { 8995 // Collect all steps of SCEV expressions. 8996 struct SCEVCollectStrides { 8997 ScalarEvolution &SE; 8998 SmallVectorImpl<const SCEV *> &Strides; 8999 9000 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 9001 : SE(SE), Strides(S) {} 9002 9003 bool follow(const SCEV *S) { 9004 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 9005 Strides.push_back(AR->getStepRecurrence(SE)); 9006 return true; 9007 } 9008 bool isDone() const { return false; } 9009 }; 9010 9011 // Collect all SCEVUnknown and SCEVMulExpr expressions. 9012 struct SCEVCollectTerms { 9013 SmallVectorImpl<const SCEV *> &Terms; 9014 9015 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) 9016 : Terms(T) {} 9017 9018 bool follow(const SCEV *S) { 9019 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 9020 isa<SCEVSignExtendExpr>(S)) { 9021 if (!containsUndefs(S)) 9022 Terms.push_back(S); 9023 9024 // Stop recursion: once we collected a term, do not walk its operands. 9025 return false; 9026 } 9027 9028 // Keep looking. 9029 return true; 9030 } 9031 bool isDone() const { return false; } 9032 }; 9033 9034 // Check if a SCEV contains an AddRecExpr. 9035 struct SCEVHasAddRec { 9036 bool &ContainsAddRec; 9037 9038 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 9039 ContainsAddRec = false; 9040 } 9041 9042 bool follow(const SCEV *S) { 9043 if (isa<SCEVAddRecExpr>(S)) { 9044 ContainsAddRec = true; 9045 9046 // Stop recursion: once we collected a term, do not walk its operands. 9047 return false; 9048 } 9049 9050 // Keep looking. 9051 return true; 9052 } 9053 bool isDone() const { return false; } 9054 }; 9055 9056 // Find factors that are multiplied with an expression that (possibly as a 9057 // subexpression) contains an AddRecExpr. In the expression: 9058 // 9059 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 9060 // 9061 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 9062 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 9063 // parameters as they form a product with an induction variable. 9064 // 9065 // This collector expects all array size parameters to be in the same MulExpr. 9066 // It might be necessary to later add support for collecting parameters that are 9067 // spread over different nested MulExpr. 9068 struct SCEVCollectAddRecMultiplies { 9069 SmallVectorImpl<const SCEV *> &Terms; 9070 ScalarEvolution &SE; 9071 9072 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 9073 : Terms(T), SE(SE) {} 9074 9075 bool follow(const SCEV *S) { 9076 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 9077 bool HasAddRec = false; 9078 SmallVector<const SCEV *, 0> Operands; 9079 for (auto Op : Mul->operands()) { 9080 if (isa<SCEVUnknown>(Op)) { 9081 Operands.push_back(Op); 9082 } else { 9083 bool ContainsAddRec; 9084 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 9085 visitAll(Op, ContiansAddRec); 9086 HasAddRec |= ContainsAddRec; 9087 } 9088 } 9089 if (Operands.size() == 0) 9090 return true; 9091 9092 if (!HasAddRec) 9093 return false; 9094 9095 Terms.push_back(SE.getMulExpr(Operands)); 9096 // Stop recursion: once we collected a term, do not walk its operands. 9097 return false; 9098 } 9099 9100 // Keep looking. 9101 return true; 9102 } 9103 bool isDone() const { return false; } 9104 }; 9105 } 9106 9107 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 9108 /// two places: 9109 /// 1) The strides of AddRec expressions. 9110 /// 2) Unknowns that are multiplied with AddRec expressions. 9111 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 9112 SmallVectorImpl<const SCEV *> &Terms) { 9113 SmallVector<const SCEV *, 4> Strides; 9114 SCEVCollectStrides StrideCollector(*this, Strides); 9115 visitAll(Expr, StrideCollector); 9116 9117 DEBUG({ 9118 dbgs() << "Strides:\n"; 9119 for (const SCEV *S : Strides) 9120 dbgs() << *S << "\n"; 9121 }); 9122 9123 for (const SCEV *S : Strides) { 9124 SCEVCollectTerms TermCollector(Terms); 9125 visitAll(S, TermCollector); 9126 } 9127 9128 DEBUG({ 9129 dbgs() << "Terms:\n"; 9130 for (const SCEV *T : Terms) 9131 dbgs() << *T << "\n"; 9132 }); 9133 9134 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 9135 visitAll(Expr, MulCollector); 9136 } 9137 9138 static bool findArrayDimensionsRec(ScalarEvolution &SE, 9139 SmallVectorImpl<const SCEV *> &Terms, 9140 SmallVectorImpl<const SCEV *> &Sizes) { 9141 int Last = Terms.size() - 1; 9142 const SCEV *Step = Terms[Last]; 9143 9144 // End of recursion. 9145 if (Last == 0) { 9146 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 9147 SmallVector<const SCEV *, 2> Qs; 9148 for (const SCEV *Op : M->operands()) 9149 if (!isa<SCEVConstant>(Op)) 9150 Qs.push_back(Op); 9151 9152 Step = SE.getMulExpr(Qs); 9153 } 9154 9155 Sizes.push_back(Step); 9156 return true; 9157 } 9158 9159 for (const SCEV *&Term : Terms) { 9160 // Normalize the terms before the next call to findArrayDimensionsRec. 9161 const SCEV *Q, *R; 9162 SCEVDivision::divide(SE, Term, Step, &Q, &R); 9163 9164 // Bail out when GCD does not evenly divide one of the terms. 9165 if (!R->isZero()) 9166 return false; 9167 9168 Term = Q; 9169 } 9170 9171 // Remove all SCEVConstants. 9172 Terms.erase( 9173 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 9174 Terms.end()); 9175 9176 if (Terms.size() > 0) 9177 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 9178 return false; 9179 9180 Sizes.push_back(Step); 9181 return true; 9182 } 9183 9184 9185 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 9186 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 9187 for (const SCEV *T : Terms) 9188 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 9189 return true; 9190 return false; 9191 } 9192 9193 // Return the number of product terms in S. 9194 static inline int numberOfTerms(const SCEV *S) { 9195 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 9196 return Expr->getNumOperands(); 9197 return 1; 9198 } 9199 9200 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 9201 if (isa<SCEVConstant>(T)) 9202 return nullptr; 9203 9204 if (isa<SCEVUnknown>(T)) 9205 return T; 9206 9207 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 9208 SmallVector<const SCEV *, 2> Factors; 9209 for (const SCEV *Op : M->operands()) 9210 if (!isa<SCEVConstant>(Op)) 9211 Factors.push_back(Op); 9212 9213 return SE.getMulExpr(Factors); 9214 } 9215 9216 return T; 9217 } 9218 9219 /// Return the size of an element read or written by Inst. 9220 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 9221 Type *Ty; 9222 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 9223 Ty = Store->getValueOperand()->getType(); 9224 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 9225 Ty = Load->getType(); 9226 else 9227 return nullptr; 9228 9229 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 9230 return getSizeOfExpr(ETy, Ty); 9231 } 9232 9233 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 9234 SmallVectorImpl<const SCEV *> &Sizes, 9235 const SCEV *ElementSize) const { 9236 if (Terms.size() < 1 || !ElementSize) 9237 return; 9238 9239 // Early return when Terms do not contain parameters: we do not delinearize 9240 // non parametric SCEVs. 9241 if (!containsParameters(Terms)) 9242 return; 9243 9244 DEBUG({ 9245 dbgs() << "Terms:\n"; 9246 for (const SCEV *T : Terms) 9247 dbgs() << *T << "\n"; 9248 }); 9249 9250 // Remove duplicates. 9251 std::sort(Terms.begin(), Terms.end()); 9252 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 9253 9254 // Put larger terms first. 9255 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 9256 return numberOfTerms(LHS) > numberOfTerms(RHS); 9257 }); 9258 9259 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9260 9261 // Try to divide all terms by the element size. If term is not divisible by 9262 // element size, proceed with the original term. 9263 for (const SCEV *&Term : Terms) { 9264 const SCEV *Q, *R; 9265 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); 9266 if (!Q->isZero()) 9267 Term = Q; 9268 } 9269 9270 SmallVector<const SCEV *, 4> NewTerms; 9271 9272 // Remove constant factors. 9273 for (const SCEV *T : Terms) 9274 if (const SCEV *NewT = removeConstantFactors(SE, T)) 9275 NewTerms.push_back(NewT); 9276 9277 DEBUG({ 9278 dbgs() << "Terms after sorting:\n"; 9279 for (const SCEV *T : NewTerms) 9280 dbgs() << *T << "\n"; 9281 }); 9282 9283 if (NewTerms.empty() || 9284 !findArrayDimensionsRec(SE, NewTerms, Sizes)) { 9285 Sizes.clear(); 9286 return; 9287 } 9288 9289 // The last element to be pushed into Sizes is the size of an element. 9290 Sizes.push_back(ElementSize); 9291 9292 DEBUG({ 9293 dbgs() << "Sizes:\n"; 9294 for (const SCEV *S : Sizes) 9295 dbgs() << *S << "\n"; 9296 }); 9297 } 9298 9299 void ScalarEvolution::computeAccessFunctions( 9300 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 9301 SmallVectorImpl<const SCEV *> &Sizes) { 9302 9303 // Early exit in case this SCEV is not an affine multivariate function. 9304 if (Sizes.empty()) 9305 return; 9306 9307 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 9308 if (!AR->isAffine()) 9309 return; 9310 9311 const SCEV *Res = Expr; 9312 int Last = Sizes.size() - 1; 9313 for (int i = Last; i >= 0; i--) { 9314 const SCEV *Q, *R; 9315 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 9316 9317 DEBUG({ 9318 dbgs() << "Res: " << *Res << "\n"; 9319 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 9320 dbgs() << "Res divided by Sizes[i]:\n"; 9321 dbgs() << "Quotient: " << *Q << "\n"; 9322 dbgs() << "Remainder: " << *R << "\n"; 9323 }); 9324 9325 Res = Q; 9326 9327 // Do not record the last subscript corresponding to the size of elements in 9328 // the array. 9329 if (i == Last) { 9330 9331 // Bail out if the remainder is too complex. 9332 if (isa<SCEVAddRecExpr>(R)) { 9333 Subscripts.clear(); 9334 Sizes.clear(); 9335 return; 9336 } 9337 9338 continue; 9339 } 9340 9341 // Record the access function for the current subscript. 9342 Subscripts.push_back(R); 9343 } 9344 9345 // Also push in last position the remainder of the last division: it will be 9346 // the access function of the innermost dimension. 9347 Subscripts.push_back(Res); 9348 9349 std::reverse(Subscripts.begin(), Subscripts.end()); 9350 9351 DEBUG({ 9352 dbgs() << "Subscripts:\n"; 9353 for (const SCEV *S : Subscripts) 9354 dbgs() << *S << "\n"; 9355 }); 9356 } 9357 9358 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 9359 /// sizes of an array access. Returns the remainder of the delinearization that 9360 /// is the offset start of the array. The SCEV->delinearize algorithm computes 9361 /// the multiples of SCEV coefficients: that is a pattern matching of sub 9362 /// expressions in the stride and base of a SCEV corresponding to the 9363 /// computation of a GCD (greatest common divisor) of base and stride. When 9364 /// SCEV->delinearize fails, it returns the SCEV unchanged. 9365 /// 9366 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 9367 /// 9368 /// void foo(long n, long m, long o, double A[n][m][o]) { 9369 /// 9370 /// for (long i = 0; i < n; i++) 9371 /// for (long j = 0; j < m; j++) 9372 /// for (long k = 0; k < o; k++) 9373 /// A[i][j][k] = 1.0; 9374 /// } 9375 /// 9376 /// the delinearization input is the following AddRec SCEV: 9377 /// 9378 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 9379 /// 9380 /// From this SCEV, we are able to say that the base offset of the access is %A 9381 /// because it appears as an offset that does not divide any of the strides in 9382 /// the loops: 9383 /// 9384 /// CHECK: Base offset: %A 9385 /// 9386 /// and then SCEV->delinearize determines the size of some of the dimensions of 9387 /// the array as these are the multiples by which the strides are happening: 9388 /// 9389 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 9390 /// 9391 /// Note that the outermost dimension remains of UnknownSize because there are 9392 /// no strides that would help identifying the size of the last dimension: when 9393 /// the array has been statically allocated, one could compute the size of that 9394 /// dimension by dividing the overall size of the array by the size of the known 9395 /// dimensions: %m * %o * 8. 9396 /// 9397 /// Finally delinearize provides the access functions for the array reference 9398 /// that does correspond to A[i][j][k] of the above C testcase: 9399 /// 9400 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 9401 /// 9402 /// The testcases are checking the output of a function pass: 9403 /// DelinearizationPass that walks through all loads and stores of a function 9404 /// asking for the SCEV of the memory access with respect to all enclosing 9405 /// loops, calling SCEV->delinearize on that and printing the results. 9406 9407 void ScalarEvolution::delinearize(const SCEV *Expr, 9408 SmallVectorImpl<const SCEV *> &Subscripts, 9409 SmallVectorImpl<const SCEV *> &Sizes, 9410 const SCEV *ElementSize) { 9411 // First step: collect parametric terms. 9412 SmallVector<const SCEV *, 4> Terms; 9413 collectParametricTerms(Expr, Terms); 9414 9415 if (Terms.empty()) 9416 return; 9417 9418 // Second step: find subscript sizes. 9419 findArrayDimensions(Terms, Sizes, ElementSize); 9420 9421 if (Sizes.empty()) 9422 return; 9423 9424 // Third step: compute the access functions for each subscript. 9425 computeAccessFunctions(Expr, Subscripts, Sizes); 9426 9427 if (Subscripts.empty()) 9428 return; 9429 9430 DEBUG({ 9431 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 9432 dbgs() << "ArrayDecl[UnknownSize]"; 9433 for (const SCEV *S : Sizes) 9434 dbgs() << "[" << *S << "]"; 9435 9436 dbgs() << "\nArrayRef"; 9437 for (const SCEV *S : Subscripts) 9438 dbgs() << "[" << *S << "]"; 9439 dbgs() << "\n"; 9440 }); 9441 } 9442 9443 //===----------------------------------------------------------------------===// 9444 // SCEVCallbackVH Class Implementation 9445 //===----------------------------------------------------------------------===// 9446 9447 void ScalarEvolution::SCEVCallbackVH::deleted() { 9448 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9449 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 9450 SE->ConstantEvolutionLoopExitValue.erase(PN); 9451 SE->eraseValueFromMap(getValPtr()); 9452 // this now dangles! 9453 } 9454 9455 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 9456 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9457 9458 // Forget all the expressions associated with users of the old value, 9459 // so that future queries will recompute the expressions using the new 9460 // value. 9461 Value *Old = getValPtr(); 9462 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 9463 SmallPtrSet<User *, 8> Visited; 9464 while (!Worklist.empty()) { 9465 User *U = Worklist.pop_back_val(); 9466 // Deleting the Old value will cause this to dangle. Postpone 9467 // that until everything else is done. 9468 if (U == Old) 9469 continue; 9470 if (!Visited.insert(U).second) 9471 continue; 9472 if (PHINode *PN = dyn_cast<PHINode>(U)) 9473 SE->ConstantEvolutionLoopExitValue.erase(PN); 9474 SE->eraseValueFromMap(U); 9475 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 9476 } 9477 // Delete the Old value. 9478 if (PHINode *PN = dyn_cast<PHINode>(Old)) 9479 SE->ConstantEvolutionLoopExitValue.erase(PN); 9480 SE->eraseValueFromMap(Old); 9481 // this now dangles! 9482 } 9483 9484 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 9485 : CallbackVH(V), SE(se) {} 9486 9487 //===----------------------------------------------------------------------===// 9488 // ScalarEvolution Class Implementation 9489 //===----------------------------------------------------------------------===// 9490 9491 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 9492 AssumptionCache &AC, DominatorTree &DT, 9493 LoopInfo &LI) 9494 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 9495 CouldNotCompute(new SCEVCouldNotCompute()), 9496 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9497 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), 9498 FirstUnknown(nullptr) { 9499 9500 // To use guards for proving predicates, we need to scan every instruction in 9501 // relevant basic blocks, and not just terminators. Doing this is a waste of 9502 // time if the IR does not actually contain any calls to 9503 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 9504 // 9505 // This pessimizes the case where a pass that preserves ScalarEvolution wants 9506 // to _add_ guards to the module when there weren't any before, and wants 9507 // ScalarEvolution to optimize based on those guards. For now we prefer to be 9508 // efficient in lieu of being smart in that rather obscure case. 9509 9510 auto *GuardDecl = F.getParent()->getFunction( 9511 Intrinsic::getName(Intrinsic::experimental_guard)); 9512 HasGuards = GuardDecl && !GuardDecl->use_empty(); 9513 } 9514 9515 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 9516 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 9517 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 9518 ValueExprMap(std::move(Arg.ValueExprMap)), 9519 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 9520 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9521 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 9522 PredicatedBackedgeTakenCounts( 9523 std::move(Arg.PredicatedBackedgeTakenCounts)), 9524 ConstantEvolutionLoopExitValue( 9525 std::move(Arg.ConstantEvolutionLoopExitValue)), 9526 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 9527 LoopDispositions(std::move(Arg.LoopDispositions)), 9528 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 9529 BlockDispositions(std::move(Arg.BlockDispositions)), 9530 UnsignedRanges(std::move(Arg.UnsignedRanges)), 9531 SignedRanges(std::move(Arg.SignedRanges)), 9532 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 9533 UniquePreds(std::move(Arg.UniquePreds)), 9534 SCEVAllocator(std::move(Arg.SCEVAllocator)), 9535 FirstUnknown(Arg.FirstUnknown) { 9536 Arg.FirstUnknown = nullptr; 9537 } 9538 9539 ScalarEvolution::~ScalarEvolution() { 9540 // Iterate through all the SCEVUnknown instances and call their 9541 // destructors, so that they release their references to their values. 9542 for (SCEVUnknown *U = FirstUnknown; U;) { 9543 SCEVUnknown *Tmp = U; 9544 U = U->Next; 9545 Tmp->~SCEVUnknown(); 9546 } 9547 FirstUnknown = nullptr; 9548 9549 ExprValueMap.clear(); 9550 ValueExprMap.clear(); 9551 HasRecMap.clear(); 9552 9553 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 9554 // that a loop had multiple computable exits. 9555 for (auto &BTCI : BackedgeTakenCounts) 9556 BTCI.second.clear(); 9557 for (auto &BTCI : PredicatedBackedgeTakenCounts) 9558 BTCI.second.clear(); 9559 9560 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 9561 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 9562 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 9563 } 9564 9565 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 9566 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 9567 } 9568 9569 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 9570 const Loop *L) { 9571 // Print all inner loops first 9572 for (Loop *I : *L) 9573 PrintLoopInfo(OS, SE, I); 9574 9575 OS << "Loop "; 9576 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9577 OS << ": "; 9578 9579 SmallVector<BasicBlock *, 8> ExitBlocks; 9580 L->getExitBlocks(ExitBlocks); 9581 if (ExitBlocks.size() != 1) 9582 OS << "<multiple exits> "; 9583 9584 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 9585 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 9586 } else { 9587 OS << "Unpredictable backedge-taken count. "; 9588 } 9589 9590 OS << "\n" 9591 "Loop "; 9592 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9593 OS << ": "; 9594 9595 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 9596 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 9597 if (SE->isBackedgeTakenCountMaxOrZero(L)) 9598 OS << ", actual taken count either this or zero."; 9599 } else { 9600 OS << "Unpredictable max backedge-taken count. "; 9601 } 9602 9603 OS << "\n" 9604 "Loop "; 9605 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9606 OS << ": "; 9607 9608 SCEVUnionPredicate Pred; 9609 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 9610 if (!isa<SCEVCouldNotCompute>(PBT)) { 9611 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 9612 OS << " Predicates:\n"; 9613 Pred.print(OS, 4); 9614 } else { 9615 OS << "Unpredictable predicated backedge-taken count. "; 9616 } 9617 OS << "\n"; 9618 } 9619 9620 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 9621 switch (LD) { 9622 case ScalarEvolution::LoopVariant: 9623 return "Variant"; 9624 case ScalarEvolution::LoopInvariant: 9625 return "Invariant"; 9626 case ScalarEvolution::LoopComputable: 9627 return "Computable"; 9628 } 9629 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 9630 } 9631 9632 void ScalarEvolution::print(raw_ostream &OS) const { 9633 // ScalarEvolution's implementation of the print method is to print 9634 // out SCEV values of all instructions that are interesting. Doing 9635 // this potentially causes it to create new SCEV objects though, 9636 // which technically conflicts with the const qualifier. This isn't 9637 // observable from outside the class though, so casting away the 9638 // const isn't dangerous. 9639 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9640 9641 OS << "Classifying expressions for: "; 9642 F.printAsOperand(OS, /*PrintType=*/false); 9643 OS << "\n"; 9644 for (Instruction &I : instructions(F)) 9645 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 9646 OS << I << '\n'; 9647 OS << " --> "; 9648 const SCEV *SV = SE.getSCEV(&I); 9649 SV->print(OS); 9650 if (!isa<SCEVCouldNotCompute>(SV)) { 9651 OS << " U: "; 9652 SE.getUnsignedRange(SV).print(OS); 9653 OS << " S: "; 9654 SE.getSignedRange(SV).print(OS); 9655 } 9656 9657 const Loop *L = LI.getLoopFor(I.getParent()); 9658 9659 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 9660 if (AtUse != SV) { 9661 OS << " --> "; 9662 AtUse->print(OS); 9663 if (!isa<SCEVCouldNotCompute>(AtUse)) { 9664 OS << " U: "; 9665 SE.getUnsignedRange(AtUse).print(OS); 9666 OS << " S: "; 9667 SE.getSignedRange(AtUse).print(OS); 9668 } 9669 } 9670 9671 if (L) { 9672 OS << "\t\t" "Exits: "; 9673 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 9674 if (!SE.isLoopInvariant(ExitValue, L)) { 9675 OS << "<<Unknown>>"; 9676 } else { 9677 OS << *ExitValue; 9678 } 9679 9680 bool First = true; 9681 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 9682 if (First) { 9683 OS << "\t\t" "LoopDispositions: { "; 9684 First = false; 9685 } else { 9686 OS << ", "; 9687 } 9688 9689 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9690 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 9691 } 9692 9693 for (auto *InnerL : depth_first(L)) { 9694 if (InnerL == L) 9695 continue; 9696 if (First) { 9697 OS << "\t\t" "LoopDispositions: { "; 9698 First = false; 9699 } else { 9700 OS << ", "; 9701 } 9702 9703 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9704 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 9705 } 9706 9707 OS << " }"; 9708 } 9709 9710 OS << "\n"; 9711 } 9712 9713 OS << "Determining loop execution counts for: "; 9714 F.printAsOperand(OS, /*PrintType=*/false); 9715 OS << "\n"; 9716 for (Loop *I : LI) 9717 PrintLoopInfo(OS, &SE, I); 9718 } 9719 9720 ScalarEvolution::LoopDisposition 9721 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 9722 auto &Values = LoopDispositions[S]; 9723 for (auto &V : Values) { 9724 if (V.getPointer() == L) 9725 return V.getInt(); 9726 } 9727 Values.emplace_back(L, LoopVariant); 9728 LoopDisposition D = computeLoopDisposition(S, L); 9729 auto &Values2 = LoopDispositions[S]; 9730 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9731 if (V.getPointer() == L) { 9732 V.setInt(D); 9733 break; 9734 } 9735 } 9736 return D; 9737 } 9738 9739 ScalarEvolution::LoopDisposition 9740 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 9741 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9742 case scConstant: 9743 return LoopInvariant; 9744 case scTruncate: 9745 case scZeroExtend: 9746 case scSignExtend: 9747 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 9748 case scAddRecExpr: { 9749 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9750 9751 // If L is the addrec's loop, it's computable. 9752 if (AR->getLoop() == L) 9753 return LoopComputable; 9754 9755 // Add recurrences are never invariant in the function-body (null loop). 9756 if (!L) 9757 return LoopVariant; 9758 9759 // This recurrence is variant w.r.t. L if L contains AR's loop. 9760 if (L->contains(AR->getLoop())) 9761 return LoopVariant; 9762 9763 // This recurrence is invariant w.r.t. L if AR's loop contains L. 9764 if (AR->getLoop()->contains(L)) 9765 return LoopInvariant; 9766 9767 // This recurrence is variant w.r.t. L if any of its operands 9768 // are variant. 9769 for (auto *Op : AR->operands()) 9770 if (!isLoopInvariant(Op, L)) 9771 return LoopVariant; 9772 9773 // Otherwise it's loop-invariant. 9774 return LoopInvariant; 9775 } 9776 case scAddExpr: 9777 case scMulExpr: 9778 case scUMaxExpr: 9779 case scSMaxExpr: { 9780 bool HasVarying = false; 9781 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 9782 LoopDisposition D = getLoopDisposition(Op, L); 9783 if (D == LoopVariant) 9784 return LoopVariant; 9785 if (D == LoopComputable) 9786 HasVarying = true; 9787 } 9788 return HasVarying ? LoopComputable : LoopInvariant; 9789 } 9790 case scUDivExpr: { 9791 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 9792 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 9793 if (LD == LoopVariant) 9794 return LoopVariant; 9795 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 9796 if (RD == LoopVariant) 9797 return LoopVariant; 9798 return (LD == LoopInvariant && RD == LoopInvariant) ? 9799 LoopInvariant : LoopComputable; 9800 } 9801 case scUnknown: 9802 // All non-instruction values are loop invariant. All instructions are loop 9803 // invariant if they are not contained in the specified loop. 9804 // Instructions are never considered invariant in the function body 9805 // (null loop) because they are defined within the "loop". 9806 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 9807 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 9808 return LoopInvariant; 9809 case scCouldNotCompute: 9810 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 9811 } 9812 llvm_unreachable("Unknown SCEV kind!"); 9813 } 9814 9815 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 9816 return getLoopDisposition(S, L) == LoopInvariant; 9817 } 9818 9819 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 9820 return getLoopDisposition(S, L) == LoopComputable; 9821 } 9822 9823 ScalarEvolution::BlockDisposition 9824 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 9825 auto &Values = BlockDispositions[S]; 9826 for (auto &V : Values) { 9827 if (V.getPointer() == BB) 9828 return V.getInt(); 9829 } 9830 Values.emplace_back(BB, DoesNotDominateBlock); 9831 BlockDisposition D = computeBlockDisposition(S, BB); 9832 auto &Values2 = BlockDispositions[S]; 9833 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9834 if (V.getPointer() == BB) { 9835 V.setInt(D); 9836 break; 9837 } 9838 } 9839 return D; 9840 } 9841 9842 ScalarEvolution::BlockDisposition 9843 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 9844 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9845 case scConstant: 9846 return ProperlyDominatesBlock; 9847 case scTruncate: 9848 case scZeroExtend: 9849 case scSignExtend: 9850 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 9851 case scAddRecExpr: { 9852 // This uses a "dominates" query instead of "properly dominates" query 9853 // to test for proper dominance too, because the instruction which 9854 // produces the addrec's value is a PHI, and a PHI effectively properly 9855 // dominates its entire containing block. 9856 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9857 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 9858 return DoesNotDominateBlock; 9859 9860 // Fall through into SCEVNAryExpr handling. 9861 LLVM_FALLTHROUGH; 9862 } 9863 case scAddExpr: 9864 case scMulExpr: 9865 case scUMaxExpr: 9866 case scSMaxExpr: { 9867 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 9868 bool Proper = true; 9869 for (const SCEV *NAryOp : NAry->operands()) { 9870 BlockDisposition D = getBlockDisposition(NAryOp, BB); 9871 if (D == DoesNotDominateBlock) 9872 return DoesNotDominateBlock; 9873 if (D == DominatesBlock) 9874 Proper = false; 9875 } 9876 return Proper ? ProperlyDominatesBlock : DominatesBlock; 9877 } 9878 case scUDivExpr: { 9879 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 9880 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 9881 BlockDisposition LD = getBlockDisposition(LHS, BB); 9882 if (LD == DoesNotDominateBlock) 9883 return DoesNotDominateBlock; 9884 BlockDisposition RD = getBlockDisposition(RHS, BB); 9885 if (RD == DoesNotDominateBlock) 9886 return DoesNotDominateBlock; 9887 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 9888 ProperlyDominatesBlock : DominatesBlock; 9889 } 9890 case scUnknown: 9891 if (Instruction *I = 9892 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 9893 if (I->getParent() == BB) 9894 return DominatesBlock; 9895 if (DT.properlyDominates(I->getParent(), BB)) 9896 return ProperlyDominatesBlock; 9897 return DoesNotDominateBlock; 9898 } 9899 return ProperlyDominatesBlock; 9900 case scCouldNotCompute: 9901 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 9902 } 9903 llvm_unreachable("Unknown SCEV kind!"); 9904 } 9905 9906 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 9907 return getBlockDisposition(S, BB) >= DominatesBlock; 9908 } 9909 9910 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 9911 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 9912 } 9913 9914 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 9915 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 9916 } 9917 9918 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 9919 ValuesAtScopes.erase(S); 9920 LoopDispositions.erase(S); 9921 BlockDispositions.erase(S); 9922 UnsignedRanges.erase(S); 9923 SignedRanges.erase(S); 9924 ExprValueMap.erase(S); 9925 HasRecMap.erase(S); 9926 9927 auto RemoveSCEVFromBackedgeMap = 9928 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 9929 for (auto I = Map.begin(), E = Map.end(); I != E;) { 9930 BackedgeTakenInfo &BEInfo = I->second; 9931 if (BEInfo.hasOperand(S, this)) { 9932 BEInfo.clear(); 9933 Map.erase(I++); 9934 } else 9935 ++I; 9936 } 9937 }; 9938 9939 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 9940 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 9941 } 9942 9943 typedef DenseMap<const Loop *, std::string> VerifyMap; 9944 9945 /// replaceSubString - Replaces all occurrences of From in Str with To. 9946 static void replaceSubString(std::string &Str, StringRef From, StringRef To) { 9947 size_t Pos = 0; 9948 while ((Pos = Str.find(From, Pos)) != std::string::npos) { 9949 Str.replace(Pos, From.size(), To.data(), To.size()); 9950 Pos += To.size(); 9951 } 9952 } 9953 9954 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. 9955 static void 9956 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { 9957 std::string &S = Map[L]; 9958 if (S.empty()) { 9959 raw_string_ostream OS(S); 9960 SE.getBackedgeTakenCount(L)->print(OS); 9961 9962 // false and 0 are semantically equivalent. This can happen in dead loops. 9963 replaceSubString(OS.str(), "false", "0"); 9964 // Remove wrap flags, their use in SCEV is highly fragile. 9965 // FIXME: Remove this when SCEV gets smarter about them. 9966 replaceSubString(OS.str(), "<nw>", ""); 9967 replaceSubString(OS.str(), "<nsw>", ""); 9968 replaceSubString(OS.str(), "<nuw>", ""); 9969 } 9970 9971 for (auto *R : reverse(*L)) 9972 getLoopBackedgeTakenCounts(R, Map, SE); // recurse. 9973 } 9974 9975 void ScalarEvolution::verify() const { 9976 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9977 9978 // Gather stringified backedge taken counts for all loops using SCEV's caches. 9979 // FIXME: It would be much better to store actual values instead of strings, 9980 // but SCEV pointers will change if we drop the caches. 9981 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; 9982 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 9983 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); 9984 9985 // Gather stringified backedge taken counts for all loops using a fresh 9986 // ScalarEvolution object. 9987 ScalarEvolution SE2(F, TLI, AC, DT, LI); 9988 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 9989 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); 9990 9991 // Now compare whether they're the same with and without caches. This allows 9992 // verifying that no pass changed the cache. 9993 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && 9994 "New loops suddenly appeared!"); 9995 9996 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), 9997 OldE = BackedgeDumpsOld.end(), 9998 NewI = BackedgeDumpsNew.begin(); 9999 OldI != OldE; ++OldI, ++NewI) { 10000 assert(OldI->first == NewI->first && "Loop order changed!"); 10001 10002 // Compare the stringified SCEVs. We don't care if undef backedgetaken count 10003 // changes. 10004 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This 10005 // means that a pass is buggy or SCEV has to learn a new pattern but is 10006 // usually not harmful. 10007 if (OldI->second != NewI->second && 10008 OldI->second.find("undef") == std::string::npos && 10009 NewI->second.find("undef") == std::string::npos && 10010 OldI->second != "***COULDNOTCOMPUTE***" && 10011 NewI->second != "***COULDNOTCOMPUTE***") { 10012 dbgs() << "SCEVValidator: SCEV for loop '" 10013 << OldI->first->getHeader()->getName() 10014 << "' changed from '" << OldI->second 10015 << "' to '" << NewI->second << "'!\n"; 10016 std::abort(); 10017 } 10018 } 10019 10020 // TODO: Verify more things. 10021 } 10022 10023 bool ScalarEvolution::invalidate( 10024 Function &F, const PreservedAnalyses &PA, 10025 FunctionAnalysisManager::Invalidator &Inv) { 10026 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 10027 // of its dependencies is invalidated. 10028 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 10029 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 10030 Inv.invalidate<AssumptionAnalysis>(F, PA) || 10031 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 10032 Inv.invalidate<LoopAnalysis>(F, PA); 10033 } 10034 10035 AnalysisKey ScalarEvolutionAnalysis::Key; 10036 10037 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 10038 FunctionAnalysisManager &AM) { 10039 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 10040 AM.getResult<AssumptionAnalysis>(F), 10041 AM.getResult<DominatorTreeAnalysis>(F), 10042 AM.getResult<LoopAnalysis>(F)); 10043 } 10044 10045 PreservedAnalyses 10046 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 10047 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 10048 return PreservedAnalyses::all(); 10049 } 10050 10051 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 10052 "Scalar Evolution Analysis", false, true) 10053 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10054 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 10055 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 10056 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 10057 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 10058 "Scalar Evolution Analysis", false, true) 10059 char ScalarEvolutionWrapperPass::ID = 0; 10060 10061 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 10062 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 10063 } 10064 10065 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 10066 SE.reset(new ScalarEvolution( 10067 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 10068 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 10069 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 10070 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 10071 return false; 10072 } 10073 10074 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 10075 10076 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 10077 SE->print(OS); 10078 } 10079 10080 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 10081 if (!VerifySCEV) 10082 return; 10083 10084 SE->verify(); 10085 } 10086 10087 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 10088 AU.setPreservesAll(); 10089 AU.addRequiredTransitive<AssumptionCacheTracker>(); 10090 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 10091 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 10092 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 10093 } 10094 10095 const SCEVPredicate * 10096 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, 10097 const SCEVConstant *RHS) { 10098 FoldingSetNodeID ID; 10099 // Unique this node based on the arguments 10100 ID.AddInteger(SCEVPredicate::P_Equal); 10101 ID.AddPointer(LHS); 10102 ID.AddPointer(RHS); 10103 void *IP = nullptr; 10104 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10105 return S; 10106 SCEVEqualPredicate *Eq = new (SCEVAllocator) 10107 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 10108 UniquePreds.InsertNode(Eq, IP); 10109 return Eq; 10110 } 10111 10112 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 10113 const SCEVAddRecExpr *AR, 10114 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10115 FoldingSetNodeID ID; 10116 // Unique this node based on the arguments 10117 ID.AddInteger(SCEVPredicate::P_Wrap); 10118 ID.AddPointer(AR); 10119 ID.AddInteger(AddedFlags); 10120 void *IP = nullptr; 10121 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10122 return S; 10123 auto *OF = new (SCEVAllocator) 10124 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 10125 UniquePreds.InsertNode(OF, IP); 10126 return OF; 10127 } 10128 10129 namespace { 10130 10131 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 10132 public: 10133 /// Rewrites \p S in the context of a loop L and the SCEV predication 10134 /// infrastructure. 10135 /// 10136 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 10137 /// equivalences present in \p Pred. 10138 /// 10139 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 10140 /// \p NewPreds such that the result will be an AddRecExpr. 10141 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 10142 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10143 SCEVUnionPredicate *Pred) { 10144 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 10145 return Rewriter.visit(S); 10146 } 10147 10148 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 10149 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10150 SCEVUnionPredicate *Pred) 10151 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 10152 10153 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 10154 if (Pred) { 10155 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 10156 for (auto *Pred : ExprPreds) 10157 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 10158 if (IPred->getLHS() == Expr) 10159 return IPred->getRHS(); 10160 } 10161 10162 return Expr; 10163 } 10164 10165 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 10166 const SCEV *Operand = visit(Expr->getOperand()); 10167 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10168 if (AR && AR->getLoop() == L && AR->isAffine()) { 10169 // This couldn't be folded because the operand didn't have the nuw 10170 // flag. Add the nusw flag as an assumption that we could make. 10171 const SCEV *Step = AR->getStepRecurrence(SE); 10172 Type *Ty = Expr->getType(); 10173 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 10174 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 10175 SE.getSignExtendExpr(Step, Ty), L, 10176 AR->getNoWrapFlags()); 10177 } 10178 return SE.getZeroExtendExpr(Operand, Expr->getType()); 10179 } 10180 10181 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 10182 const SCEV *Operand = visit(Expr->getOperand()); 10183 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10184 if (AR && AR->getLoop() == L && AR->isAffine()) { 10185 // This couldn't be folded because the operand didn't have the nsw 10186 // flag. Add the nssw flag as an assumption that we could make. 10187 const SCEV *Step = AR->getStepRecurrence(SE); 10188 Type *Ty = Expr->getType(); 10189 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 10190 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 10191 SE.getSignExtendExpr(Step, Ty), L, 10192 AR->getNoWrapFlags()); 10193 } 10194 return SE.getSignExtendExpr(Operand, Expr->getType()); 10195 } 10196 10197 private: 10198 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 10199 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10200 auto *A = SE.getWrapPredicate(AR, AddedFlags); 10201 if (!NewPreds) { 10202 // Check if we've already made this assumption. 10203 return Pred && Pred->implies(A); 10204 } 10205 NewPreds->insert(A); 10206 return true; 10207 } 10208 10209 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 10210 SCEVUnionPredicate *Pred; 10211 const Loop *L; 10212 }; 10213 } // end anonymous namespace 10214 10215 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 10216 SCEVUnionPredicate &Preds) { 10217 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 10218 } 10219 10220 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 10221 const SCEV *S, const Loop *L, 10222 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 10223 10224 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 10225 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 10226 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 10227 10228 if (!AddRec) 10229 return nullptr; 10230 10231 // Since the transformation was successful, we can now transfer the SCEV 10232 // predicates. 10233 for (auto *P : TransformPreds) 10234 Preds.insert(P); 10235 10236 return AddRec; 10237 } 10238 10239 /// SCEV predicates 10240 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 10241 SCEVPredicateKind Kind) 10242 : FastID(ID), Kind(Kind) {} 10243 10244 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 10245 const SCEVUnknown *LHS, 10246 const SCEVConstant *RHS) 10247 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} 10248 10249 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 10250 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 10251 10252 if (!Op) 10253 return false; 10254 10255 return Op->LHS == LHS && Op->RHS == RHS; 10256 } 10257 10258 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 10259 10260 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 10261 10262 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 10263 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 10264 } 10265 10266 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 10267 const SCEVAddRecExpr *AR, 10268 IncrementWrapFlags Flags) 10269 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 10270 10271 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 10272 10273 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 10274 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 10275 10276 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 10277 } 10278 10279 bool SCEVWrapPredicate::isAlwaysTrue() const { 10280 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 10281 IncrementWrapFlags IFlags = Flags; 10282 10283 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 10284 IFlags = clearFlags(IFlags, IncrementNSSW); 10285 10286 return IFlags == IncrementAnyWrap; 10287 } 10288 10289 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 10290 OS.indent(Depth) << *getExpr() << " Added Flags: "; 10291 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 10292 OS << "<nusw>"; 10293 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 10294 OS << "<nssw>"; 10295 OS << "\n"; 10296 } 10297 10298 SCEVWrapPredicate::IncrementWrapFlags 10299 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 10300 ScalarEvolution &SE) { 10301 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 10302 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 10303 10304 // We can safely transfer the NSW flag as NSSW. 10305 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 10306 ImpliedFlags = IncrementNSSW; 10307 10308 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 10309 // If the increment is positive, the SCEV NUW flag will also imply the 10310 // WrapPredicate NUSW flag. 10311 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 10312 if (Step->getValue()->getValue().isNonNegative()) 10313 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 10314 } 10315 10316 return ImpliedFlags; 10317 } 10318 10319 /// Union predicates don't get cached so create a dummy set ID for it. 10320 SCEVUnionPredicate::SCEVUnionPredicate() 10321 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 10322 10323 bool SCEVUnionPredicate::isAlwaysTrue() const { 10324 return all_of(Preds, 10325 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 10326 } 10327 10328 ArrayRef<const SCEVPredicate *> 10329 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 10330 auto I = SCEVToPreds.find(Expr); 10331 if (I == SCEVToPreds.end()) 10332 return ArrayRef<const SCEVPredicate *>(); 10333 return I->second; 10334 } 10335 10336 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 10337 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 10338 return all_of(Set->Preds, 10339 [this](const SCEVPredicate *I) { return this->implies(I); }); 10340 10341 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 10342 if (ScevPredsIt == SCEVToPreds.end()) 10343 return false; 10344 auto &SCEVPreds = ScevPredsIt->second; 10345 10346 return any_of(SCEVPreds, 10347 [N](const SCEVPredicate *I) { return I->implies(N); }); 10348 } 10349 10350 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 10351 10352 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 10353 for (auto Pred : Preds) 10354 Pred->print(OS, Depth); 10355 } 10356 10357 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 10358 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 10359 for (auto Pred : Set->Preds) 10360 add(Pred); 10361 return; 10362 } 10363 10364 if (implies(N)) 10365 return; 10366 10367 const SCEV *Key = N->getExpr(); 10368 assert(Key && "Only SCEVUnionPredicate doesn't have an " 10369 " associated expression!"); 10370 10371 SCEVToPreds[Key].push_back(N); 10372 Preds.push_back(N); 10373 } 10374 10375 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 10376 Loop &L) 10377 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {} 10378 10379 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 10380 const SCEV *Expr = SE.getSCEV(V); 10381 RewriteEntry &Entry = RewriteMap[Expr]; 10382 10383 // If we already have an entry and the version matches, return it. 10384 if (Entry.second && Generation == Entry.first) 10385 return Entry.second; 10386 10387 // We found an entry but it's stale. Rewrite the stale entry 10388 // according to the current predicate. 10389 if (Entry.second) 10390 Expr = Entry.second; 10391 10392 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 10393 Entry = {Generation, NewSCEV}; 10394 10395 return NewSCEV; 10396 } 10397 10398 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 10399 if (!BackedgeCount) { 10400 SCEVUnionPredicate BackedgePred; 10401 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 10402 addPredicate(BackedgePred); 10403 } 10404 return BackedgeCount; 10405 } 10406 10407 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 10408 if (Preds.implies(&Pred)) 10409 return; 10410 Preds.add(&Pred); 10411 updateGeneration(); 10412 } 10413 10414 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 10415 return Preds; 10416 } 10417 10418 void PredicatedScalarEvolution::updateGeneration() { 10419 // If the generation number wrapped recompute everything. 10420 if (++Generation == 0) { 10421 for (auto &II : RewriteMap) { 10422 const SCEV *Rewritten = II.second.second; 10423 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 10424 } 10425 } 10426 } 10427 10428 void PredicatedScalarEvolution::setNoOverflow( 10429 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10430 const SCEV *Expr = getSCEV(V); 10431 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10432 10433 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 10434 10435 // Clear the statically implied flags. 10436 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 10437 addPredicate(*SE.getWrapPredicate(AR, Flags)); 10438 10439 auto II = FlagsMap.insert({V, Flags}); 10440 if (!II.second) 10441 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 10442 } 10443 10444 bool PredicatedScalarEvolution::hasNoOverflow( 10445 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10446 const SCEV *Expr = getSCEV(V); 10447 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10448 10449 Flags = SCEVWrapPredicate::clearFlags( 10450 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 10451 10452 auto II = FlagsMap.find(V); 10453 10454 if (II != FlagsMap.end()) 10455 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 10456 10457 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 10458 } 10459 10460 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 10461 const SCEV *Expr = this->getSCEV(V); 10462 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 10463 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 10464 10465 if (!New) 10466 return nullptr; 10467 10468 for (auto *P : NewPreds) 10469 Preds.add(P); 10470 10471 updateGeneration(); 10472 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 10473 return New; 10474 } 10475 10476 PredicatedScalarEvolution::PredicatedScalarEvolution( 10477 const PredicatedScalarEvolution &Init) 10478 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 10479 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 10480 for (const auto &I : Init.FlagsMap) 10481 FlagsMap.insert(I); 10482 } 10483 10484 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 10485 // For each block. 10486 for (auto *BB : L.getBlocks()) 10487 for (auto &I : *BB) { 10488 if (!SE.isSCEVable(I.getType())) 10489 continue; 10490 10491 auto *Expr = SE.getSCEV(&I); 10492 auto II = RewriteMap.find(Expr); 10493 10494 if (II == RewriteMap.end()) 10495 continue; 10496 10497 // Don't print things that are not interesting. 10498 if (II->second.second == Expr) 10499 continue; 10500 10501 OS.indent(Depth) << "[PSE]" << I << ":\n"; 10502 OS.indent(Depth + 2) << *Expr << "\n"; 10503 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 10504 } 10505 } 10506