1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution analysis 10 // engine, which is used primarily to analyze expressions involving induction 11 // variables in loops. 12 // 13 // There are several aspects to this library. First is the representation of 14 // scalar expressions, which are represented as subclasses of the SCEV class. 15 // These classes are used to represent certain types of subexpressions that we 16 // can handle. We only create one SCEV of a particular shape, so 17 // pointer-comparisons for equality are legal. 18 // 19 // One important aspect of the SCEV objects is that they are never cyclic, even 20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 22 // recurrence) then we represent it directly as a recurrence node, otherwise we 23 // represent it as a SCEVUnknown node. 24 // 25 // In addition to being able to represent expressions of various types, we also 26 // have folders that are used to build the *canonical* representation for a 27 // particular expression. These folders are capable of using a variety of 28 // rewrite rules to simplify the expressions. 29 // 30 // Once the folders are defined, we can implement the more interesting 31 // higher-level code, such as the code that recognizes PHI nodes of various 32 // types, computes the execution count of a loop, etc. 33 // 34 // TODO: We should use these routines and value representations to implement 35 // dependence analysis! 36 // 37 //===----------------------------------------------------------------------===// 38 // 39 // There are several good references for the techniques used in this analysis. 40 // 41 // Chains of recurrences -- a method to expedite the evaluation 42 // of closed-form functions 43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 44 // 45 // On computational properties of chains of recurrences 46 // Eugene V. Zima 47 // 48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 49 // Robert A. van Engelen 50 // 51 // Efficient Symbolic Analysis for Optimizing Compilers 52 // Robert A. van Engelen 53 // 54 // Using the chains of recurrences algebra for data dependence testing and 55 // induction variable substitution 56 // MS Thesis, Johnie Birch 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 83 #include "llvm/Analysis/TargetLibraryInfo.h" 84 #include "llvm/Analysis/ValueTracking.h" 85 #include "llvm/Config/llvm-config.h" 86 #include "llvm/IR/Argument.h" 87 #include "llvm/IR/BasicBlock.h" 88 #include "llvm/IR/CFG.h" 89 #include "llvm/IR/CallSite.h" 90 #include "llvm/IR/Constant.h" 91 #include "llvm/IR/ConstantRange.h" 92 #include "llvm/IR/Constants.h" 93 #include "llvm/IR/DataLayout.h" 94 #include "llvm/IR/DerivedTypes.h" 95 #include "llvm/IR/Dominators.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/GlobalAlias.h" 98 #include "llvm/IR/GlobalValue.h" 99 #include "llvm/IR/GlobalVariable.h" 100 #include "llvm/IR/InstIterator.h" 101 #include "llvm/IR/InstrTypes.h" 102 #include "llvm/IR/Instruction.h" 103 #include "llvm/IR/Instructions.h" 104 #include "llvm/IR/IntrinsicInst.h" 105 #include "llvm/IR/Intrinsics.h" 106 #include "llvm/IR/LLVMContext.h" 107 #include "llvm/IR/Metadata.h" 108 #include "llvm/IR/Operator.h" 109 #include "llvm/IR/PatternMatch.h" 110 #include "llvm/IR/Type.h" 111 #include "llvm/IR/Use.h" 112 #include "llvm/IR/User.h" 113 #include "llvm/IR/Value.h" 114 #include "llvm/IR/Verifier.h" 115 #include "llvm/Pass.h" 116 #include "llvm/Support/Casting.h" 117 #include "llvm/Support/CommandLine.h" 118 #include "llvm/Support/Compiler.h" 119 #include "llvm/Support/Debug.h" 120 #include "llvm/Support/ErrorHandling.h" 121 #include "llvm/Support/KnownBits.h" 122 #include "llvm/Support/SaveAndRestore.h" 123 #include "llvm/Support/raw_ostream.h" 124 #include <algorithm> 125 #include <cassert> 126 #include <climits> 127 #include <cstddef> 128 #include <cstdint> 129 #include <cstdlib> 130 #include <map> 131 #include <memory> 132 #include <tuple> 133 #include <utility> 134 #include <vector> 135 136 using namespace llvm; 137 138 #define DEBUG_TYPE "scalar-evolution" 139 140 STATISTIC(NumArrayLenItCounts, 141 "Number of trip counts computed with array length"); 142 STATISTIC(NumTripCountsComputed, 143 "Number of loops with predictable loop counts"); 144 STATISTIC(NumTripCountsNotComputed, 145 "Number of loops without predictable loop counts"); 146 STATISTIC(NumBruteForceTripCountsComputed, 147 "Number of loops with trip counts computed by force"); 148 149 static cl::opt<unsigned> 150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 151 cl::desc("Maximum number of iterations SCEV will " 152 "symbolically execute a constant " 153 "derived loop"), 154 cl::init(100)); 155 156 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 157 static cl::opt<bool> VerifySCEV( 158 "verify-scev", cl::Hidden, 159 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 160 static cl::opt<bool> 161 VerifySCEVMap("verify-scev-maps", cl::Hidden, 162 cl::desc("Verify no dangling value in ScalarEvolution's " 163 "ExprValueMap (slow)")); 164 165 static cl::opt<bool> VerifyIR( 166 "scev-verify-ir", cl::Hidden, 167 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 168 cl::init(false)); 169 170 static cl::opt<unsigned> MulOpsInlineThreshold( 171 "scev-mulops-inline-threshold", cl::Hidden, 172 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 173 cl::init(32)); 174 175 static cl::opt<unsigned> AddOpsInlineThreshold( 176 "scev-addops-inline-threshold", cl::Hidden, 177 cl::desc("Threshold for inlining addition operands into a SCEV"), 178 cl::init(500)); 179 180 static cl::opt<unsigned> MaxSCEVCompareDepth( 181 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 182 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 183 cl::init(32)); 184 185 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 186 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 187 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 188 cl::init(2)); 189 190 static cl::opt<unsigned> MaxValueCompareDepth( 191 "scalar-evolution-max-value-compare-depth", cl::Hidden, 192 cl::desc("Maximum depth of recursive value complexity comparisons"), 193 cl::init(2)); 194 195 static cl::opt<unsigned> 196 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 197 cl::desc("Maximum depth of recursive arithmetics"), 198 cl::init(32)); 199 200 static cl::opt<unsigned> MaxConstantEvolvingDepth( 201 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 202 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 203 204 static cl::opt<unsigned> 205 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 206 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 207 cl::init(8)); 208 209 static cl::opt<unsigned> 210 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 211 cl::desc("Max coefficients in AddRec during evolving"), 212 cl::init(8)); 213 214 static cl::opt<unsigned> 215 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 216 cl::desc("Size of the expression which is considered huge"), 217 cl::init(4096)); 218 219 //===----------------------------------------------------------------------===// 220 // SCEV class definitions 221 //===----------------------------------------------------------------------===// 222 223 //===----------------------------------------------------------------------===// 224 // Implementation of the SCEV class. 225 // 226 227 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 228 LLVM_DUMP_METHOD void SCEV::dump() const { 229 print(dbgs()); 230 dbgs() << '\n'; 231 } 232 #endif 233 234 void SCEV::print(raw_ostream &OS) const { 235 switch (static_cast<SCEVTypes>(getSCEVType())) { 236 case scConstant: 237 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 238 return; 239 case scTruncate: { 240 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 241 const SCEV *Op = Trunc->getOperand(); 242 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 243 << *Trunc->getType() << ")"; 244 return; 245 } 246 case scZeroExtend: { 247 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 248 const SCEV *Op = ZExt->getOperand(); 249 OS << "(zext " << *Op->getType() << " " << *Op << " to " 250 << *ZExt->getType() << ")"; 251 return; 252 } 253 case scSignExtend: { 254 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 255 const SCEV *Op = SExt->getOperand(); 256 OS << "(sext " << *Op->getType() << " " << *Op << " to " 257 << *SExt->getType() << ")"; 258 return; 259 } 260 case scAddRecExpr: { 261 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 262 OS << "{" << *AR->getOperand(0); 263 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 264 OS << ",+," << *AR->getOperand(i); 265 OS << "}<"; 266 if (AR->hasNoUnsignedWrap()) 267 OS << "nuw><"; 268 if (AR->hasNoSignedWrap()) 269 OS << "nsw><"; 270 if (AR->hasNoSelfWrap() && 271 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 272 OS << "nw><"; 273 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 274 OS << ">"; 275 return; 276 } 277 case scAddExpr: 278 case scMulExpr: 279 case scUMaxExpr: 280 case scSMaxExpr: { 281 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 282 const char *OpStr = nullptr; 283 switch (NAry->getSCEVType()) { 284 case scAddExpr: OpStr = " + "; break; 285 case scMulExpr: OpStr = " * "; break; 286 case scUMaxExpr: OpStr = " umax "; break; 287 case scSMaxExpr: OpStr = " smax "; break; 288 } 289 OS << "("; 290 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 291 I != E; ++I) { 292 OS << **I; 293 if (std::next(I) != E) 294 OS << OpStr; 295 } 296 OS << ")"; 297 switch (NAry->getSCEVType()) { 298 case scAddExpr: 299 case scMulExpr: 300 if (NAry->hasNoUnsignedWrap()) 301 OS << "<nuw>"; 302 if (NAry->hasNoSignedWrap()) 303 OS << "<nsw>"; 304 } 305 return; 306 } 307 case scUDivExpr: { 308 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 309 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 310 return; 311 } 312 case scUnknown: { 313 const SCEVUnknown *U = cast<SCEVUnknown>(this); 314 Type *AllocTy; 315 if (U->isSizeOf(AllocTy)) { 316 OS << "sizeof(" << *AllocTy << ")"; 317 return; 318 } 319 if (U->isAlignOf(AllocTy)) { 320 OS << "alignof(" << *AllocTy << ")"; 321 return; 322 } 323 324 Type *CTy; 325 Constant *FieldNo; 326 if (U->isOffsetOf(CTy, FieldNo)) { 327 OS << "offsetof(" << *CTy << ", "; 328 FieldNo->printAsOperand(OS, false); 329 OS << ")"; 330 return; 331 } 332 333 // Otherwise just print it normally. 334 U->getValue()->printAsOperand(OS, false); 335 return; 336 } 337 case scCouldNotCompute: 338 OS << "***COULDNOTCOMPUTE***"; 339 return; 340 } 341 llvm_unreachable("Unknown SCEV kind!"); 342 } 343 344 Type *SCEV::getType() const { 345 switch (static_cast<SCEVTypes>(getSCEVType())) { 346 case scConstant: 347 return cast<SCEVConstant>(this)->getType(); 348 case scTruncate: 349 case scZeroExtend: 350 case scSignExtend: 351 return cast<SCEVCastExpr>(this)->getType(); 352 case scAddRecExpr: 353 case scMulExpr: 354 case scUMaxExpr: 355 case scSMaxExpr: 356 return cast<SCEVNAryExpr>(this)->getType(); 357 case scAddExpr: 358 return cast<SCEVAddExpr>(this)->getType(); 359 case scUDivExpr: 360 return cast<SCEVUDivExpr>(this)->getType(); 361 case scUnknown: 362 return cast<SCEVUnknown>(this)->getType(); 363 case scCouldNotCompute: 364 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 365 } 366 llvm_unreachable("Unknown SCEV kind!"); 367 } 368 369 bool SCEV::isZero() const { 370 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 371 return SC->getValue()->isZero(); 372 return false; 373 } 374 375 bool SCEV::isOne() const { 376 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 377 return SC->getValue()->isOne(); 378 return false; 379 } 380 381 bool SCEV::isAllOnesValue() const { 382 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 383 return SC->getValue()->isMinusOne(); 384 return false; 385 } 386 387 bool SCEV::isNonConstantNegative() const { 388 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 389 if (!Mul) return false; 390 391 // If there is a constant factor, it will be first. 392 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 393 if (!SC) return false; 394 395 // Return true if the value is negative, this matches things like (-42 * V). 396 return SC->getAPInt().isNegative(); 397 } 398 399 SCEVCouldNotCompute::SCEVCouldNotCompute() : 400 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 401 402 bool SCEVCouldNotCompute::classof(const SCEV *S) { 403 return S->getSCEVType() == scCouldNotCompute; 404 } 405 406 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 407 FoldingSetNodeID ID; 408 ID.AddInteger(scConstant); 409 ID.AddPointer(V); 410 void *IP = nullptr; 411 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 412 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 413 UniqueSCEVs.InsertNode(S, IP); 414 return S; 415 } 416 417 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 418 return getConstant(ConstantInt::get(getContext(), Val)); 419 } 420 421 const SCEV * 422 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 423 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 424 return getConstant(ConstantInt::get(ITy, V, isSigned)); 425 } 426 427 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 428 unsigned SCEVTy, const SCEV *op, Type *ty) 429 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {} 430 431 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 432 const SCEV *op, Type *ty) 433 : SCEVCastExpr(ID, scTruncate, op, ty) { 434 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 435 "Cannot truncate non-integer value!"); 436 } 437 438 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 439 const SCEV *op, Type *ty) 440 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 441 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 442 "Cannot zero extend non-integer value!"); 443 } 444 445 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 446 const SCEV *op, Type *ty) 447 : SCEVCastExpr(ID, scSignExtend, op, ty) { 448 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 449 "Cannot sign extend non-integer value!"); 450 } 451 452 void SCEVUnknown::deleted() { 453 // Clear this SCEVUnknown from various maps. 454 SE->forgetMemoizedResults(this); 455 456 // Remove this SCEVUnknown from the uniquing map. 457 SE->UniqueSCEVs.RemoveNode(this); 458 459 // Release the value. 460 setValPtr(nullptr); 461 } 462 463 void SCEVUnknown::allUsesReplacedWith(Value *New) { 464 // Remove this SCEVUnknown from the uniquing map. 465 SE->UniqueSCEVs.RemoveNode(this); 466 467 // Update this SCEVUnknown to point to the new value. This is needed 468 // because there may still be outstanding SCEVs which still point to 469 // this SCEVUnknown. 470 setValPtr(New); 471 } 472 473 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 474 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 475 if (VCE->getOpcode() == Instruction::PtrToInt) 476 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 477 if (CE->getOpcode() == Instruction::GetElementPtr && 478 CE->getOperand(0)->isNullValue() && 479 CE->getNumOperands() == 2) 480 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 481 if (CI->isOne()) { 482 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 483 ->getElementType(); 484 return true; 485 } 486 487 return false; 488 } 489 490 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 491 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 492 if (VCE->getOpcode() == Instruction::PtrToInt) 493 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 494 if (CE->getOpcode() == Instruction::GetElementPtr && 495 CE->getOperand(0)->isNullValue()) { 496 Type *Ty = 497 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 498 if (StructType *STy = dyn_cast<StructType>(Ty)) 499 if (!STy->isPacked() && 500 CE->getNumOperands() == 3 && 501 CE->getOperand(1)->isNullValue()) { 502 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 503 if (CI->isOne() && 504 STy->getNumElements() == 2 && 505 STy->getElementType(0)->isIntegerTy(1)) { 506 AllocTy = STy->getElementType(1); 507 return true; 508 } 509 } 510 } 511 512 return false; 513 } 514 515 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 516 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 517 if (VCE->getOpcode() == Instruction::PtrToInt) 518 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 519 if (CE->getOpcode() == Instruction::GetElementPtr && 520 CE->getNumOperands() == 3 && 521 CE->getOperand(0)->isNullValue() && 522 CE->getOperand(1)->isNullValue()) { 523 Type *Ty = 524 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 525 // Ignore vector types here so that ScalarEvolutionExpander doesn't 526 // emit getelementptrs that index into vectors. 527 if (Ty->isStructTy() || Ty->isArrayTy()) { 528 CTy = Ty; 529 FieldNo = CE->getOperand(2); 530 return true; 531 } 532 } 533 534 return false; 535 } 536 537 //===----------------------------------------------------------------------===// 538 // SCEV Utilities 539 //===----------------------------------------------------------------------===// 540 541 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 542 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 543 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 544 /// have been previously deemed to be "equally complex" by this routine. It is 545 /// intended to avoid exponential time complexity in cases like: 546 /// 547 /// %a = f(%x, %y) 548 /// %b = f(%a, %a) 549 /// %c = f(%b, %b) 550 /// 551 /// %d = f(%x, %y) 552 /// %e = f(%d, %d) 553 /// %f = f(%e, %e) 554 /// 555 /// CompareValueComplexity(%f, %c) 556 /// 557 /// Since we do not continue running this routine on expression trees once we 558 /// have seen unequal values, there is no need to track them in the cache. 559 static int 560 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 561 const LoopInfo *const LI, Value *LV, Value *RV, 562 unsigned Depth) { 563 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 564 return 0; 565 566 // Order pointer values after integer values. This helps SCEVExpander form 567 // GEPs. 568 bool LIsPointer = LV->getType()->isPointerTy(), 569 RIsPointer = RV->getType()->isPointerTy(); 570 if (LIsPointer != RIsPointer) 571 return (int)LIsPointer - (int)RIsPointer; 572 573 // Compare getValueID values. 574 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 575 if (LID != RID) 576 return (int)LID - (int)RID; 577 578 // Sort arguments by their position. 579 if (const auto *LA = dyn_cast<Argument>(LV)) { 580 const auto *RA = cast<Argument>(RV); 581 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 582 return (int)LArgNo - (int)RArgNo; 583 } 584 585 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 586 const auto *RGV = cast<GlobalValue>(RV); 587 588 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 589 auto LT = GV->getLinkage(); 590 return !(GlobalValue::isPrivateLinkage(LT) || 591 GlobalValue::isInternalLinkage(LT)); 592 }; 593 594 // Use the names to distinguish the two values, but only if the 595 // names are semantically important. 596 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 597 return LGV->getName().compare(RGV->getName()); 598 } 599 600 // For instructions, compare their loop depth, and their operand count. This 601 // is pretty loose. 602 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 603 const auto *RInst = cast<Instruction>(RV); 604 605 // Compare loop depths. 606 const BasicBlock *LParent = LInst->getParent(), 607 *RParent = RInst->getParent(); 608 if (LParent != RParent) { 609 unsigned LDepth = LI->getLoopDepth(LParent), 610 RDepth = LI->getLoopDepth(RParent); 611 if (LDepth != RDepth) 612 return (int)LDepth - (int)RDepth; 613 } 614 615 // Compare the number of operands. 616 unsigned LNumOps = LInst->getNumOperands(), 617 RNumOps = RInst->getNumOperands(); 618 if (LNumOps != RNumOps) 619 return (int)LNumOps - (int)RNumOps; 620 621 for (unsigned Idx : seq(0u, LNumOps)) { 622 int Result = 623 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 624 RInst->getOperand(Idx), Depth + 1); 625 if (Result != 0) 626 return Result; 627 } 628 } 629 630 EqCacheValue.unionSets(LV, RV); 631 return 0; 632 } 633 634 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 635 // than RHS, respectively. A three-way result allows recursive comparisons to be 636 // more efficient. 637 static int CompareSCEVComplexity( 638 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 639 EquivalenceClasses<const Value *> &EqCacheValue, 640 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 641 DominatorTree &DT, unsigned Depth = 0) { 642 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 643 if (LHS == RHS) 644 return 0; 645 646 // Primarily, sort the SCEVs by their getSCEVType(). 647 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 648 if (LType != RType) 649 return (int)LType - (int)RType; 650 651 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 652 return 0; 653 // Aside from the getSCEVType() ordering, the particular ordering 654 // isn't very important except that it's beneficial to be consistent, 655 // so that (a + b) and (b + a) don't end up as different expressions. 656 switch (static_cast<SCEVTypes>(LType)) { 657 case scUnknown: { 658 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 659 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 660 661 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 662 RU->getValue(), Depth + 1); 663 if (X == 0) 664 EqCacheSCEV.unionSets(LHS, RHS); 665 return X; 666 } 667 668 case scConstant: { 669 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 670 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 671 672 // Compare constant values. 673 const APInt &LA = LC->getAPInt(); 674 const APInt &RA = RC->getAPInt(); 675 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 676 if (LBitWidth != RBitWidth) 677 return (int)LBitWidth - (int)RBitWidth; 678 return LA.ult(RA) ? -1 : 1; 679 } 680 681 case scAddRecExpr: { 682 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 683 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 684 685 // There is always a dominance between two recs that are used by one SCEV, 686 // so we can safely sort recs by loop header dominance. We require such 687 // order in getAddExpr. 688 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 689 if (LLoop != RLoop) { 690 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 691 assert(LHead != RHead && "Two loops share the same header?"); 692 if (DT.dominates(LHead, RHead)) 693 return 1; 694 else 695 assert(DT.dominates(RHead, LHead) && 696 "No dominance between recurrences used by one SCEV?"); 697 return -1; 698 } 699 700 // Addrec complexity grows with operand count. 701 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 702 if (LNumOps != RNumOps) 703 return (int)LNumOps - (int)RNumOps; 704 705 // Lexicographically compare. 706 for (unsigned i = 0; i != LNumOps; ++i) { 707 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 708 LA->getOperand(i), RA->getOperand(i), DT, 709 Depth + 1); 710 if (X != 0) 711 return X; 712 } 713 EqCacheSCEV.unionSets(LHS, RHS); 714 return 0; 715 } 716 717 case scAddExpr: 718 case scMulExpr: 719 case scSMaxExpr: 720 case scUMaxExpr: { 721 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 722 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 723 724 // Lexicographically compare n-ary expressions. 725 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 726 if (LNumOps != RNumOps) 727 return (int)LNumOps - (int)RNumOps; 728 729 for (unsigned i = 0; i != LNumOps; ++i) { 730 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 731 LC->getOperand(i), RC->getOperand(i), DT, 732 Depth + 1); 733 if (X != 0) 734 return X; 735 } 736 EqCacheSCEV.unionSets(LHS, RHS); 737 return 0; 738 } 739 740 case scUDivExpr: { 741 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 742 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 743 744 // Lexicographically compare udiv expressions. 745 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 746 RC->getLHS(), DT, Depth + 1); 747 if (X != 0) 748 return X; 749 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 750 RC->getRHS(), DT, Depth + 1); 751 if (X == 0) 752 EqCacheSCEV.unionSets(LHS, RHS); 753 return X; 754 } 755 756 case scTruncate: 757 case scZeroExtend: 758 case scSignExtend: { 759 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 760 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 761 762 // Compare cast expressions by operand. 763 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 764 LC->getOperand(), RC->getOperand(), DT, 765 Depth + 1); 766 if (X == 0) 767 EqCacheSCEV.unionSets(LHS, RHS); 768 return X; 769 } 770 771 case scCouldNotCompute: 772 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 773 } 774 llvm_unreachable("Unknown SCEV kind!"); 775 } 776 777 /// Given a list of SCEV objects, order them by their complexity, and group 778 /// objects of the same complexity together by value. When this routine is 779 /// finished, we know that any duplicates in the vector are consecutive and that 780 /// complexity is monotonically increasing. 781 /// 782 /// Note that we go take special precautions to ensure that we get deterministic 783 /// results from this routine. In other words, we don't want the results of 784 /// this to depend on where the addresses of various SCEV objects happened to 785 /// land in memory. 786 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 787 LoopInfo *LI, DominatorTree &DT) { 788 if (Ops.size() < 2) return; // Noop 789 790 EquivalenceClasses<const SCEV *> EqCacheSCEV; 791 EquivalenceClasses<const Value *> EqCacheValue; 792 if (Ops.size() == 2) { 793 // This is the common case, which also happens to be trivially simple. 794 // Special case it. 795 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 796 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 797 std::swap(LHS, RHS); 798 return; 799 } 800 801 // Do the rough sort by complexity. 802 std::stable_sort(Ops.begin(), Ops.end(), 803 [&](const SCEV *LHS, const SCEV *RHS) { 804 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 805 LHS, RHS, DT) < 0; 806 }); 807 808 // Now that we are sorted by complexity, group elements of the same 809 // complexity. Note that this is, at worst, N^2, but the vector is likely to 810 // be extremely short in practice. Note that we take this approach because we 811 // do not want to depend on the addresses of the objects we are grouping. 812 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 813 const SCEV *S = Ops[i]; 814 unsigned Complexity = S->getSCEVType(); 815 816 // If there are any objects of the same complexity and same value as this 817 // one, group them. 818 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 819 if (Ops[j] == S) { // Found a duplicate. 820 // Move it to immediately after i'th element. 821 std::swap(Ops[i+1], Ops[j]); 822 ++i; // no need to rescan it. 823 if (i == e-2) return; // Done! 824 } 825 } 826 } 827 } 828 829 // Returns the size of the SCEV S. 830 static inline int sizeOfSCEV(const SCEV *S) { 831 struct FindSCEVSize { 832 int Size = 0; 833 834 FindSCEVSize() = default; 835 836 bool follow(const SCEV *S) { 837 ++Size; 838 // Keep looking at all operands of S. 839 return true; 840 } 841 842 bool isDone() const { 843 return false; 844 } 845 }; 846 847 FindSCEVSize F; 848 SCEVTraversal<FindSCEVSize> ST(F); 849 ST.visitAll(S); 850 return F.Size; 851 } 852 853 /// Returns true if the subtree of \p S contains at least HugeExprThreshold 854 /// nodes. 855 static bool isHugeExpression(const SCEV *S) { 856 return S->getExpressionSize() >= HugeExprThreshold; 857 } 858 859 /// Returns true of \p Ops contains a huge SCEV (see definition above). 860 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 861 return any_of(Ops, isHugeExpression); 862 } 863 864 namespace { 865 866 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 867 public: 868 // Computes the Quotient and Remainder of the division of Numerator by 869 // Denominator. 870 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 871 const SCEV *Denominator, const SCEV **Quotient, 872 const SCEV **Remainder) { 873 assert(Numerator && Denominator && "Uninitialized SCEV"); 874 875 SCEVDivision D(SE, Numerator, Denominator); 876 877 // Check for the trivial case here to avoid having to check for it in the 878 // rest of the code. 879 if (Numerator == Denominator) { 880 *Quotient = D.One; 881 *Remainder = D.Zero; 882 return; 883 } 884 885 if (Numerator->isZero()) { 886 *Quotient = D.Zero; 887 *Remainder = D.Zero; 888 return; 889 } 890 891 // A simple case when N/1. The quotient is N. 892 if (Denominator->isOne()) { 893 *Quotient = Numerator; 894 *Remainder = D.Zero; 895 return; 896 } 897 898 // Split the Denominator when it is a product. 899 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 900 const SCEV *Q, *R; 901 *Quotient = Numerator; 902 for (const SCEV *Op : T->operands()) { 903 divide(SE, *Quotient, Op, &Q, &R); 904 *Quotient = Q; 905 906 // Bail out when the Numerator is not divisible by one of the terms of 907 // the Denominator. 908 if (!R->isZero()) { 909 *Quotient = D.Zero; 910 *Remainder = Numerator; 911 return; 912 } 913 } 914 *Remainder = D.Zero; 915 return; 916 } 917 918 D.visit(Numerator); 919 *Quotient = D.Quotient; 920 *Remainder = D.Remainder; 921 } 922 923 // Except in the trivial case described above, we do not know how to divide 924 // Expr by Denominator for the following functions with empty implementation. 925 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 926 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 927 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 928 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 929 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 930 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 931 void visitUnknown(const SCEVUnknown *Numerator) {} 932 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 933 934 void visitConstant(const SCEVConstant *Numerator) { 935 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 936 APInt NumeratorVal = Numerator->getAPInt(); 937 APInt DenominatorVal = D->getAPInt(); 938 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 939 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 940 941 if (NumeratorBW > DenominatorBW) 942 DenominatorVal = DenominatorVal.sext(NumeratorBW); 943 else if (NumeratorBW < DenominatorBW) 944 NumeratorVal = NumeratorVal.sext(DenominatorBW); 945 946 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 947 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 948 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 949 Quotient = SE.getConstant(QuotientVal); 950 Remainder = SE.getConstant(RemainderVal); 951 return; 952 } 953 } 954 955 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 956 const SCEV *StartQ, *StartR, *StepQ, *StepR; 957 if (!Numerator->isAffine()) 958 return cannotDivide(Numerator); 959 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 960 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 961 // Bail out if the types do not match. 962 Type *Ty = Denominator->getType(); 963 if (Ty != StartQ->getType() || Ty != StartR->getType() || 964 Ty != StepQ->getType() || Ty != StepR->getType()) 965 return cannotDivide(Numerator); 966 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 967 Numerator->getNoWrapFlags()); 968 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 969 Numerator->getNoWrapFlags()); 970 } 971 972 void visitAddExpr(const SCEVAddExpr *Numerator) { 973 SmallVector<const SCEV *, 2> Qs, Rs; 974 Type *Ty = Denominator->getType(); 975 976 for (const SCEV *Op : Numerator->operands()) { 977 const SCEV *Q, *R; 978 divide(SE, Op, Denominator, &Q, &R); 979 980 // Bail out if types do not match. 981 if (Ty != Q->getType() || Ty != R->getType()) 982 return cannotDivide(Numerator); 983 984 Qs.push_back(Q); 985 Rs.push_back(R); 986 } 987 988 if (Qs.size() == 1) { 989 Quotient = Qs[0]; 990 Remainder = Rs[0]; 991 return; 992 } 993 994 Quotient = SE.getAddExpr(Qs); 995 Remainder = SE.getAddExpr(Rs); 996 } 997 998 void visitMulExpr(const SCEVMulExpr *Numerator) { 999 SmallVector<const SCEV *, 2> Qs; 1000 Type *Ty = Denominator->getType(); 1001 1002 bool FoundDenominatorTerm = false; 1003 for (const SCEV *Op : Numerator->operands()) { 1004 // Bail out if types do not match. 1005 if (Ty != Op->getType()) 1006 return cannotDivide(Numerator); 1007 1008 if (FoundDenominatorTerm) { 1009 Qs.push_back(Op); 1010 continue; 1011 } 1012 1013 // Check whether Denominator divides one of the product operands. 1014 const SCEV *Q, *R; 1015 divide(SE, Op, Denominator, &Q, &R); 1016 if (!R->isZero()) { 1017 Qs.push_back(Op); 1018 continue; 1019 } 1020 1021 // Bail out if types do not match. 1022 if (Ty != Q->getType()) 1023 return cannotDivide(Numerator); 1024 1025 FoundDenominatorTerm = true; 1026 Qs.push_back(Q); 1027 } 1028 1029 if (FoundDenominatorTerm) { 1030 Remainder = Zero; 1031 if (Qs.size() == 1) 1032 Quotient = Qs[0]; 1033 else 1034 Quotient = SE.getMulExpr(Qs); 1035 return; 1036 } 1037 1038 if (!isa<SCEVUnknown>(Denominator)) 1039 return cannotDivide(Numerator); 1040 1041 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1042 ValueToValueMap RewriteMap; 1043 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1044 cast<SCEVConstant>(Zero)->getValue(); 1045 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1046 1047 if (Remainder->isZero()) { 1048 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1049 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1050 cast<SCEVConstant>(One)->getValue(); 1051 Quotient = 1052 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1053 return; 1054 } 1055 1056 // Quotient is (Numerator - Remainder) divided by Denominator. 1057 const SCEV *Q, *R; 1058 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1059 // This SCEV does not seem to simplify: fail the division here. 1060 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1061 return cannotDivide(Numerator); 1062 divide(SE, Diff, Denominator, &Q, &R); 1063 if (R != Zero) 1064 return cannotDivide(Numerator); 1065 Quotient = Q; 1066 } 1067 1068 private: 1069 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1070 const SCEV *Denominator) 1071 : SE(S), Denominator(Denominator) { 1072 Zero = SE.getZero(Denominator->getType()); 1073 One = SE.getOne(Denominator->getType()); 1074 1075 // We generally do not know how to divide Expr by Denominator. We 1076 // initialize the division to a "cannot divide" state to simplify the rest 1077 // of the code. 1078 cannotDivide(Numerator); 1079 } 1080 1081 // Convenience function for giving up on the division. We set the quotient to 1082 // be equal to zero and the remainder to be equal to the numerator. 1083 void cannotDivide(const SCEV *Numerator) { 1084 Quotient = Zero; 1085 Remainder = Numerator; 1086 } 1087 1088 ScalarEvolution &SE; 1089 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1090 }; 1091 1092 } // end anonymous namespace 1093 1094 //===----------------------------------------------------------------------===// 1095 // Simple SCEV method implementations 1096 //===----------------------------------------------------------------------===// 1097 1098 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1099 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1100 ScalarEvolution &SE, 1101 Type *ResultTy) { 1102 // Handle the simplest case efficiently. 1103 if (K == 1) 1104 return SE.getTruncateOrZeroExtend(It, ResultTy); 1105 1106 // We are using the following formula for BC(It, K): 1107 // 1108 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1109 // 1110 // Suppose, W is the bitwidth of the return value. We must be prepared for 1111 // overflow. Hence, we must assure that the result of our computation is 1112 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1113 // safe in modular arithmetic. 1114 // 1115 // However, this code doesn't use exactly that formula; the formula it uses 1116 // is something like the following, where T is the number of factors of 2 in 1117 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1118 // exponentiation: 1119 // 1120 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1121 // 1122 // This formula is trivially equivalent to the previous formula. However, 1123 // this formula can be implemented much more efficiently. The trick is that 1124 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1125 // arithmetic. To do exact division in modular arithmetic, all we have 1126 // to do is multiply by the inverse. Therefore, this step can be done at 1127 // width W. 1128 // 1129 // The next issue is how to safely do the division by 2^T. The way this 1130 // is done is by doing the multiplication step at a width of at least W + T 1131 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1132 // when we perform the division by 2^T (which is equivalent to a right shift 1133 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1134 // truncated out after the division by 2^T. 1135 // 1136 // In comparison to just directly using the first formula, this technique 1137 // is much more efficient; using the first formula requires W * K bits, 1138 // but this formula less than W + K bits. Also, the first formula requires 1139 // a division step, whereas this formula only requires multiplies and shifts. 1140 // 1141 // It doesn't matter whether the subtraction step is done in the calculation 1142 // width or the input iteration count's width; if the subtraction overflows, 1143 // the result must be zero anyway. We prefer here to do it in the width of 1144 // the induction variable because it helps a lot for certain cases; CodeGen 1145 // isn't smart enough to ignore the overflow, which leads to much less 1146 // efficient code if the width of the subtraction is wider than the native 1147 // register width. 1148 // 1149 // (It's possible to not widen at all by pulling out factors of 2 before 1150 // the multiplication; for example, K=2 can be calculated as 1151 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1152 // extra arithmetic, so it's not an obvious win, and it gets 1153 // much more complicated for K > 3.) 1154 1155 // Protection from insane SCEVs; this bound is conservative, 1156 // but it probably doesn't matter. 1157 if (K > 1000) 1158 return SE.getCouldNotCompute(); 1159 1160 unsigned W = SE.getTypeSizeInBits(ResultTy); 1161 1162 // Calculate K! / 2^T and T; we divide out the factors of two before 1163 // multiplying for calculating K! / 2^T to avoid overflow. 1164 // Other overflow doesn't matter because we only care about the bottom 1165 // W bits of the result. 1166 APInt OddFactorial(W, 1); 1167 unsigned T = 1; 1168 for (unsigned i = 3; i <= K; ++i) { 1169 APInt Mult(W, i); 1170 unsigned TwoFactors = Mult.countTrailingZeros(); 1171 T += TwoFactors; 1172 Mult.lshrInPlace(TwoFactors); 1173 OddFactorial *= Mult; 1174 } 1175 1176 // We need at least W + T bits for the multiplication step 1177 unsigned CalculationBits = W + T; 1178 1179 // Calculate 2^T, at width T+W. 1180 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1181 1182 // Calculate the multiplicative inverse of K! / 2^T; 1183 // this multiplication factor will perform the exact division by 1184 // K! / 2^T. 1185 APInt Mod = APInt::getSignedMinValue(W+1); 1186 APInt MultiplyFactor = OddFactorial.zext(W+1); 1187 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1188 MultiplyFactor = MultiplyFactor.trunc(W); 1189 1190 // Calculate the product, at width T+W 1191 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1192 CalculationBits); 1193 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1194 for (unsigned i = 1; i != K; ++i) { 1195 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1196 Dividend = SE.getMulExpr(Dividend, 1197 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1198 } 1199 1200 // Divide by 2^T 1201 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1202 1203 // Truncate the result, and divide by K! / 2^T. 1204 1205 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1206 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1207 } 1208 1209 /// Return the value of this chain of recurrences at the specified iteration 1210 /// number. We can evaluate this recurrence by multiplying each element in the 1211 /// chain by the binomial coefficient corresponding to it. In other words, we 1212 /// can evaluate {A,+,B,+,C,+,D} as: 1213 /// 1214 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1215 /// 1216 /// where BC(It, k) stands for binomial coefficient. 1217 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1218 ScalarEvolution &SE) const { 1219 const SCEV *Result = getStart(); 1220 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1221 // The computation is correct in the face of overflow provided that the 1222 // multiplication is performed _after_ the evaluation of the binomial 1223 // coefficient. 1224 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1225 if (isa<SCEVCouldNotCompute>(Coeff)) 1226 return Coeff; 1227 1228 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1229 } 1230 return Result; 1231 } 1232 1233 //===----------------------------------------------------------------------===// 1234 // SCEV Expression folder implementations 1235 //===----------------------------------------------------------------------===// 1236 1237 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1238 unsigned Depth) { 1239 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1240 "This is not a truncating conversion!"); 1241 assert(isSCEVable(Ty) && 1242 "This is not a conversion to a SCEVable type!"); 1243 Ty = getEffectiveSCEVType(Ty); 1244 1245 FoldingSetNodeID ID; 1246 ID.AddInteger(scTruncate); 1247 ID.AddPointer(Op); 1248 ID.AddPointer(Ty); 1249 void *IP = nullptr; 1250 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1251 1252 // Fold if the operand is constant. 1253 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1254 return getConstant( 1255 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1256 1257 // trunc(trunc(x)) --> trunc(x) 1258 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1259 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1260 1261 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1262 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1263 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1264 1265 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1266 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1267 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1268 1269 if (Depth > MaxCastDepth) { 1270 SCEV *S = 1271 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1272 UniqueSCEVs.InsertNode(S, IP); 1273 addToLoopUseLists(S); 1274 return S; 1275 } 1276 1277 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1278 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1279 // if after transforming we have at most one truncate, not counting truncates 1280 // that replace other casts. 1281 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1282 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1283 SmallVector<const SCEV *, 4> Operands; 1284 unsigned numTruncs = 0; 1285 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1286 ++i) { 1287 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1288 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1289 numTruncs++; 1290 Operands.push_back(S); 1291 } 1292 if (numTruncs < 2) { 1293 if (isa<SCEVAddExpr>(Op)) 1294 return getAddExpr(Operands); 1295 else if (isa<SCEVMulExpr>(Op)) 1296 return getMulExpr(Operands); 1297 else 1298 llvm_unreachable("Unexpected SCEV type for Op."); 1299 } 1300 // Although we checked in the beginning that ID is not in the cache, it is 1301 // possible that during recursion and different modification ID was inserted 1302 // into the cache. So if we find it, just return it. 1303 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1304 return S; 1305 } 1306 1307 // If the input value is a chrec scev, truncate the chrec's operands. 1308 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1309 SmallVector<const SCEV *, 4> Operands; 1310 for (const SCEV *Op : AddRec->operands()) 1311 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1312 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1313 } 1314 1315 // The cast wasn't folded; create an explicit cast node. We can reuse 1316 // the existing insert position since if we get here, we won't have 1317 // made any changes which would invalidate it. 1318 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1319 Op, Ty); 1320 UniqueSCEVs.InsertNode(S, IP); 1321 addToLoopUseLists(S); 1322 return S; 1323 } 1324 1325 // Get the limit of a recurrence such that incrementing by Step cannot cause 1326 // signed overflow as long as the value of the recurrence within the 1327 // loop does not exceed this limit before incrementing. 1328 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1329 ICmpInst::Predicate *Pred, 1330 ScalarEvolution *SE) { 1331 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1332 if (SE->isKnownPositive(Step)) { 1333 *Pred = ICmpInst::ICMP_SLT; 1334 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1335 SE->getSignedRangeMax(Step)); 1336 } 1337 if (SE->isKnownNegative(Step)) { 1338 *Pred = ICmpInst::ICMP_SGT; 1339 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1340 SE->getSignedRangeMin(Step)); 1341 } 1342 return nullptr; 1343 } 1344 1345 // Get the limit of a recurrence such that incrementing by Step cannot cause 1346 // unsigned overflow as long as the value of the recurrence within the loop does 1347 // not exceed this limit before incrementing. 1348 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1349 ICmpInst::Predicate *Pred, 1350 ScalarEvolution *SE) { 1351 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1352 *Pred = ICmpInst::ICMP_ULT; 1353 1354 return SE->getConstant(APInt::getMinValue(BitWidth) - 1355 SE->getUnsignedRangeMax(Step)); 1356 } 1357 1358 namespace { 1359 1360 struct ExtendOpTraitsBase { 1361 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1362 unsigned); 1363 }; 1364 1365 // Used to make code generic over signed and unsigned overflow. 1366 template <typename ExtendOp> struct ExtendOpTraits { 1367 // Members present: 1368 // 1369 // static const SCEV::NoWrapFlags WrapType; 1370 // 1371 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1372 // 1373 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1374 // ICmpInst::Predicate *Pred, 1375 // ScalarEvolution *SE); 1376 }; 1377 1378 template <> 1379 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1380 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1381 1382 static const GetExtendExprTy GetExtendExpr; 1383 1384 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1385 ICmpInst::Predicate *Pred, 1386 ScalarEvolution *SE) { 1387 return getSignedOverflowLimitForStep(Step, Pred, SE); 1388 } 1389 }; 1390 1391 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1392 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1393 1394 template <> 1395 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1396 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1397 1398 static const GetExtendExprTy GetExtendExpr; 1399 1400 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1401 ICmpInst::Predicate *Pred, 1402 ScalarEvolution *SE) { 1403 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1404 } 1405 }; 1406 1407 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1408 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1409 1410 } // end anonymous namespace 1411 1412 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1413 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1414 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1415 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1416 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1417 // expression "Step + sext/zext(PreIncAR)" is congruent with 1418 // "sext/zext(PostIncAR)" 1419 template <typename ExtendOpTy> 1420 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1421 ScalarEvolution *SE, unsigned Depth) { 1422 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1423 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1424 1425 const Loop *L = AR->getLoop(); 1426 const SCEV *Start = AR->getStart(); 1427 const SCEV *Step = AR->getStepRecurrence(*SE); 1428 1429 // Check for a simple looking step prior to loop entry. 1430 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1431 if (!SA) 1432 return nullptr; 1433 1434 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1435 // subtraction is expensive. For this purpose, perform a quick and dirty 1436 // difference, by checking for Step in the operand list. 1437 SmallVector<const SCEV *, 4> DiffOps; 1438 for (const SCEV *Op : SA->operands()) 1439 if (Op != Step) 1440 DiffOps.push_back(Op); 1441 1442 if (DiffOps.size() == SA->getNumOperands()) 1443 return nullptr; 1444 1445 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1446 // `Step`: 1447 1448 // 1. NSW/NUW flags on the step increment. 1449 auto PreStartFlags = 1450 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1451 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1452 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1453 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1454 1455 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1456 // "S+X does not sign/unsign-overflow". 1457 // 1458 1459 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1460 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1461 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1462 return PreStart; 1463 1464 // 2. Direct overflow check on the step operation's expression. 1465 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1466 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1467 const SCEV *OperandExtendedStart = 1468 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1469 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1470 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1471 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1472 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1473 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1474 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1475 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1476 } 1477 return PreStart; 1478 } 1479 1480 // 3. Loop precondition. 1481 ICmpInst::Predicate Pred; 1482 const SCEV *OverflowLimit = 1483 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1484 1485 if (OverflowLimit && 1486 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1487 return PreStart; 1488 1489 return nullptr; 1490 } 1491 1492 // Get the normalized zero or sign extended expression for this AddRec's Start. 1493 template <typename ExtendOpTy> 1494 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1495 ScalarEvolution *SE, 1496 unsigned Depth) { 1497 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1498 1499 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1500 if (!PreStart) 1501 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1502 1503 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1504 Depth), 1505 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1506 } 1507 1508 // Try to prove away overflow by looking at "nearby" add recurrences. A 1509 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1510 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1511 // 1512 // Formally: 1513 // 1514 // {S,+,X} == {S-T,+,X} + T 1515 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1516 // 1517 // If ({S-T,+,X} + T) does not overflow ... (1) 1518 // 1519 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1520 // 1521 // If {S-T,+,X} does not overflow ... (2) 1522 // 1523 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1524 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1525 // 1526 // If (S-T)+T does not overflow ... (3) 1527 // 1528 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1529 // == {Ext(S),+,Ext(X)} == LHS 1530 // 1531 // Thus, if (1), (2) and (3) are true for some T, then 1532 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1533 // 1534 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1535 // does not overflow" restricted to the 0th iteration. Therefore we only need 1536 // to check for (1) and (2). 1537 // 1538 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1539 // is `Delta` (defined below). 1540 template <typename ExtendOpTy> 1541 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1542 const SCEV *Step, 1543 const Loop *L) { 1544 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1545 1546 // We restrict `Start` to a constant to prevent SCEV from spending too much 1547 // time here. It is correct (but more expensive) to continue with a 1548 // non-constant `Start` and do a general SCEV subtraction to compute 1549 // `PreStart` below. 1550 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1551 if (!StartC) 1552 return false; 1553 1554 APInt StartAI = StartC->getAPInt(); 1555 1556 for (unsigned Delta : {-2, -1, 1, 2}) { 1557 const SCEV *PreStart = getConstant(StartAI - Delta); 1558 1559 FoldingSetNodeID ID; 1560 ID.AddInteger(scAddRecExpr); 1561 ID.AddPointer(PreStart); 1562 ID.AddPointer(Step); 1563 ID.AddPointer(L); 1564 void *IP = nullptr; 1565 const auto *PreAR = 1566 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1567 1568 // Give up if we don't already have the add recurrence we need because 1569 // actually constructing an add recurrence is relatively expensive. 1570 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1571 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1572 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1573 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1574 DeltaS, &Pred, this); 1575 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1576 return true; 1577 } 1578 } 1579 1580 return false; 1581 } 1582 1583 // Finds an integer D for an expression (C + x + y + ...) such that the top 1584 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1585 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1586 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1587 // the (C + x + y + ...) expression is \p WholeAddExpr. 1588 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1589 const SCEVConstant *ConstantTerm, 1590 const SCEVAddExpr *WholeAddExpr) { 1591 const APInt C = ConstantTerm->getAPInt(); 1592 const unsigned BitWidth = C.getBitWidth(); 1593 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1594 uint32_t TZ = BitWidth; 1595 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1596 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1597 if (TZ) { 1598 // Set D to be as many least significant bits of C as possible while still 1599 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1600 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1601 } 1602 return APInt(BitWidth, 0); 1603 } 1604 1605 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1606 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1607 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1608 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1609 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1610 const APInt &ConstantStart, 1611 const SCEV *Step) { 1612 const unsigned BitWidth = ConstantStart.getBitWidth(); 1613 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1614 if (TZ) 1615 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1616 : ConstantStart; 1617 return APInt(BitWidth, 0); 1618 } 1619 1620 const SCEV * 1621 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1622 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1623 "This is not an extending conversion!"); 1624 assert(isSCEVable(Ty) && 1625 "This is not a conversion to a SCEVable type!"); 1626 Ty = getEffectiveSCEVType(Ty); 1627 1628 // Fold if the operand is constant. 1629 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1630 return getConstant( 1631 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1632 1633 // zext(zext(x)) --> zext(x) 1634 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1635 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1636 1637 // Before doing any expensive analysis, check to see if we've already 1638 // computed a SCEV for this Op and Ty. 1639 FoldingSetNodeID ID; 1640 ID.AddInteger(scZeroExtend); 1641 ID.AddPointer(Op); 1642 ID.AddPointer(Ty); 1643 void *IP = nullptr; 1644 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1645 if (Depth > MaxCastDepth) { 1646 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1647 Op, Ty); 1648 UniqueSCEVs.InsertNode(S, IP); 1649 addToLoopUseLists(S); 1650 return S; 1651 } 1652 1653 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1654 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1655 // It's possible the bits taken off by the truncate were all zero bits. If 1656 // so, we should be able to simplify this further. 1657 const SCEV *X = ST->getOperand(); 1658 ConstantRange CR = getUnsignedRange(X); 1659 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1660 unsigned NewBits = getTypeSizeInBits(Ty); 1661 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1662 CR.zextOrTrunc(NewBits))) 1663 return getTruncateOrZeroExtend(X, Ty, Depth); 1664 } 1665 1666 // If the input value is a chrec scev, and we can prove that the value 1667 // did not overflow the old, smaller, value, we can zero extend all of the 1668 // operands (often constants). This allows analysis of something like 1669 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1670 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1671 if (AR->isAffine()) { 1672 const SCEV *Start = AR->getStart(); 1673 const SCEV *Step = AR->getStepRecurrence(*this); 1674 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1675 const Loop *L = AR->getLoop(); 1676 1677 if (!AR->hasNoUnsignedWrap()) { 1678 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1679 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1680 } 1681 1682 // If we have special knowledge that this addrec won't overflow, 1683 // we don't need to do any further analysis. 1684 if (AR->hasNoUnsignedWrap()) 1685 return getAddRecExpr( 1686 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1687 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1688 1689 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1690 // Note that this serves two purposes: It filters out loops that are 1691 // simply not analyzable, and it covers the case where this code is 1692 // being called from within backedge-taken count analysis, such that 1693 // attempting to ask for the backedge-taken count would likely result 1694 // in infinite recursion. In the later case, the analysis code will 1695 // cope with a conservative value, and it will take care to purge 1696 // that value once it has finished. 1697 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1698 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1699 // Manually compute the final value for AR, checking for 1700 // overflow. 1701 1702 // Check whether the backedge-taken count can be losslessly casted to 1703 // the addrec's type. The count is always unsigned. 1704 const SCEV *CastedMaxBECount = 1705 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1706 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1707 CastedMaxBECount, MaxBECount->getType(), Depth); 1708 if (MaxBECount == RecastedMaxBECount) { 1709 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1710 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1711 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1712 SCEV::FlagAnyWrap, Depth + 1); 1713 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1714 SCEV::FlagAnyWrap, 1715 Depth + 1), 1716 WideTy, Depth + 1); 1717 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1718 const SCEV *WideMaxBECount = 1719 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1720 const SCEV *OperandExtendedAdd = 1721 getAddExpr(WideStart, 1722 getMulExpr(WideMaxBECount, 1723 getZeroExtendExpr(Step, WideTy, Depth + 1), 1724 SCEV::FlagAnyWrap, Depth + 1), 1725 SCEV::FlagAnyWrap, Depth + 1); 1726 if (ZAdd == OperandExtendedAdd) { 1727 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1728 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1729 // Return the expression with the addrec on the outside. 1730 return getAddRecExpr( 1731 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1732 Depth + 1), 1733 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1734 AR->getNoWrapFlags()); 1735 } 1736 // Similar to above, only this time treat the step value as signed. 1737 // This covers loops that count down. 1738 OperandExtendedAdd = 1739 getAddExpr(WideStart, 1740 getMulExpr(WideMaxBECount, 1741 getSignExtendExpr(Step, WideTy, Depth + 1), 1742 SCEV::FlagAnyWrap, Depth + 1), 1743 SCEV::FlagAnyWrap, Depth + 1); 1744 if (ZAdd == OperandExtendedAdd) { 1745 // Cache knowledge of AR NW, which is propagated to this AddRec. 1746 // Negative step causes unsigned wrap, but it still can't self-wrap. 1747 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1748 // Return the expression with the addrec on the outside. 1749 return getAddRecExpr( 1750 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1751 Depth + 1), 1752 getSignExtendExpr(Step, Ty, Depth + 1), L, 1753 AR->getNoWrapFlags()); 1754 } 1755 } 1756 } 1757 1758 // Normally, in the cases we can prove no-overflow via a 1759 // backedge guarding condition, we can also compute a backedge 1760 // taken count for the loop. The exceptions are assumptions and 1761 // guards present in the loop -- SCEV is not great at exploiting 1762 // these to compute max backedge taken counts, but can still use 1763 // these to prove lack of overflow. Use this fact to avoid 1764 // doing extra work that may not pay off. 1765 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1766 !AC.assumptions().empty()) { 1767 // If the backedge is guarded by a comparison with the pre-inc 1768 // value the addrec is safe. Also, if the entry is guarded by 1769 // a comparison with the start value and the backedge is 1770 // guarded by a comparison with the post-inc value, the addrec 1771 // is safe. 1772 if (isKnownPositive(Step)) { 1773 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1774 getUnsignedRangeMax(Step)); 1775 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1776 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1777 // Cache knowledge of AR NUW, which is propagated to this 1778 // AddRec. 1779 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1780 // Return the expression with the addrec on the outside. 1781 return getAddRecExpr( 1782 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1783 Depth + 1), 1784 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1785 AR->getNoWrapFlags()); 1786 } 1787 } else if (isKnownNegative(Step)) { 1788 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1789 getSignedRangeMin(Step)); 1790 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1791 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1792 // Cache knowledge of AR NW, which is propagated to this 1793 // AddRec. Negative step causes unsigned wrap, but it 1794 // still can't self-wrap. 1795 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1796 // Return the expression with the addrec on the outside. 1797 return getAddRecExpr( 1798 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1799 Depth + 1), 1800 getSignExtendExpr(Step, Ty, Depth + 1), L, 1801 AR->getNoWrapFlags()); 1802 } 1803 } 1804 } 1805 1806 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1807 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1808 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1809 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1810 const APInt &C = SC->getAPInt(); 1811 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1812 if (D != 0) { 1813 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1814 const SCEV *SResidual = 1815 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1816 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1817 return getAddExpr(SZExtD, SZExtR, 1818 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1819 Depth + 1); 1820 } 1821 } 1822 1823 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1824 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1825 return getAddRecExpr( 1826 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1827 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1828 } 1829 } 1830 1831 // zext(A % B) --> zext(A) % zext(B) 1832 { 1833 const SCEV *LHS; 1834 const SCEV *RHS; 1835 if (matchURem(Op, LHS, RHS)) 1836 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1837 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1838 } 1839 1840 // zext(A / B) --> zext(A) / zext(B). 1841 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1842 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1843 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1844 1845 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1846 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1847 if (SA->hasNoUnsignedWrap()) { 1848 // If the addition does not unsign overflow then we can, by definition, 1849 // commute the zero extension with the addition operation. 1850 SmallVector<const SCEV *, 4> Ops; 1851 for (const auto *Op : SA->operands()) 1852 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1853 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1854 } 1855 1856 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1857 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1858 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1859 // 1860 // Often address arithmetics contain expressions like 1861 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1862 // This transformation is useful while proving that such expressions are 1863 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1864 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1865 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1866 if (D != 0) { 1867 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1868 const SCEV *SResidual = 1869 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1870 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1871 return getAddExpr(SZExtD, SZExtR, 1872 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1873 Depth + 1); 1874 } 1875 } 1876 } 1877 1878 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1879 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1880 if (SM->hasNoUnsignedWrap()) { 1881 // If the multiply does not unsign overflow then we can, by definition, 1882 // commute the zero extension with the multiply operation. 1883 SmallVector<const SCEV *, 4> Ops; 1884 for (const auto *Op : SM->operands()) 1885 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1886 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1887 } 1888 1889 // zext(2^K * (trunc X to iN)) to iM -> 1890 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1891 // 1892 // Proof: 1893 // 1894 // zext(2^K * (trunc X to iN)) to iM 1895 // = zext((trunc X to iN) << K) to iM 1896 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1897 // (because shl removes the top K bits) 1898 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1899 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1900 // 1901 if (SM->getNumOperands() == 2) 1902 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1903 if (MulLHS->getAPInt().isPowerOf2()) 1904 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1905 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1906 MulLHS->getAPInt().logBase2(); 1907 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1908 return getMulExpr( 1909 getZeroExtendExpr(MulLHS, Ty), 1910 getZeroExtendExpr( 1911 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1912 SCEV::FlagNUW, Depth + 1); 1913 } 1914 } 1915 1916 // The cast wasn't folded; create an explicit cast node. 1917 // Recompute the insert position, as it may have been invalidated. 1918 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1919 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1920 Op, Ty); 1921 UniqueSCEVs.InsertNode(S, IP); 1922 addToLoopUseLists(S); 1923 return S; 1924 } 1925 1926 const SCEV * 1927 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1928 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1929 "This is not an extending conversion!"); 1930 assert(isSCEVable(Ty) && 1931 "This is not a conversion to a SCEVable type!"); 1932 Ty = getEffectiveSCEVType(Ty); 1933 1934 // Fold if the operand is constant. 1935 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1936 return getConstant( 1937 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1938 1939 // sext(sext(x)) --> sext(x) 1940 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1941 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1942 1943 // sext(zext(x)) --> zext(x) 1944 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1945 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1946 1947 // Before doing any expensive analysis, check to see if we've already 1948 // computed a SCEV for this Op and Ty. 1949 FoldingSetNodeID ID; 1950 ID.AddInteger(scSignExtend); 1951 ID.AddPointer(Op); 1952 ID.AddPointer(Ty); 1953 void *IP = nullptr; 1954 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1955 // Limit recursion depth. 1956 if (Depth > MaxCastDepth) { 1957 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1958 Op, Ty); 1959 UniqueSCEVs.InsertNode(S, IP); 1960 addToLoopUseLists(S); 1961 return S; 1962 } 1963 1964 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1965 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1966 // It's possible the bits taken off by the truncate were all sign bits. If 1967 // so, we should be able to simplify this further. 1968 const SCEV *X = ST->getOperand(); 1969 ConstantRange CR = getSignedRange(X); 1970 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1971 unsigned NewBits = getTypeSizeInBits(Ty); 1972 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1973 CR.sextOrTrunc(NewBits))) 1974 return getTruncateOrSignExtend(X, Ty, Depth); 1975 } 1976 1977 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1978 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1979 if (SA->hasNoSignedWrap()) { 1980 // If the addition does not sign overflow then we can, by definition, 1981 // commute the sign extension with the addition operation. 1982 SmallVector<const SCEV *, 4> Ops; 1983 for (const auto *Op : SA->operands()) 1984 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1985 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1986 } 1987 1988 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1989 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1990 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1991 // 1992 // For instance, this will bring two seemingly different expressions: 1993 // 1 + sext(5 + 20 * %x + 24 * %y) and 1994 // sext(6 + 20 * %x + 24 * %y) 1995 // to the same form: 1996 // 2 + sext(4 + 20 * %x + 24 * %y) 1997 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1998 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1999 if (D != 0) { 2000 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2001 const SCEV *SResidual = 2002 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 2003 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2004 return getAddExpr(SSExtD, SSExtR, 2005 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2006 Depth + 1); 2007 } 2008 } 2009 } 2010 // If the input value is a chrec scev, and we can prove that the value 2011 // did not overflow the old, smaller, value, we can sign extend all of the 2012 // operands (often constants). This allows analysis of something like 2013 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 2014 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 2015 if (AR->isAffine()) { 2016 const SCEV *Start = AR->getStart(); 2017 const SCEV *Step = AR->getStepRecurrence(*this); 2018 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 2019 const Loop *L = AR->getLoop(); 2020 2021 if (!AR->hasNoSignedWrap()) { 2022 auto NewFlags = proveNoWrapViaConstantRanges(AR); 2023 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 2024 } 2025 2026 // If we have special knowledge that this addrec won't overflow, 2027 // we don't need to do any further analysis. 2028 if (AR->hasNoSignedWrap()) 2029 return getAddRecExpr( 2030 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2031 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 2032 2033 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2034 // Note that this serves two purposes: It filters out loops that are 2035 // simply not analyzable, and it covers the case where this code is 2036 // being called from within backedge-taken count analysis, such that 2037 // attempting to ask for the backedge-taken count would likely result 2038 // in infinite recursion. In the later case, the analysis code will 2039 // cope with a conservative value, and it will take care to purge 2040 // that value once it has finished. 2041 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 2042 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2043 // Manually compute the final value for AR, checking for 2044 // overflow. 2045 2046 // Check whether the backedge-taken count can be losslessly casted to 2047 // the addrec's type. The count is always unsigned. 2048 const SCEV *CastedMaxBECount = 2049 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2050 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2051 CastedMaxBECount, MaxBECount->getType(), Depth); 2052 if (MaxBECount == RecastedMaxBECount) { 2053 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2054 // Check whether Start+Step*MaxBECount has no signed overflow. 2055 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2056 SCEV::FlagAnyWrap, Depth + 1); 2057 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2058 SCEV::FlagAnyWrap, 2059 Depth + 1), 2060 WideTy, Depth + 1); 2061 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2062 const SCEV *WideMaxBECount = 2063 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2064 const SCEV *OperandExtendedAdd = 2065 getAddExpr(WideStart, 2066 getMulExpr(WideMaxBECount, 2067 getSignExtendExpr(Step, WideTy, Depth + 1), 2068 SCEV::FlagAnyWrap, Depth + 1), 2069 SCEV::FlagAnyWrap, Depth + 1); 2070 if (SAdd == OperandExtendedAdd) { 2071 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2072 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2073 // Return the expression with the addrec on the outside. 2074 return getAddRecExpr( 2075 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2076 Depth + 1), 2077 getSignExtendExpr(Step, Ty, Depth + 1), L, 2078 AR->getNoWrapFlags()); 2079 } 2080 // Similar to above, only this time treat the step value as unsigned. 2081 // This covers loops that count up with an unsigned step. 2082 OperandExtendedAdd = 2083 getAddExpr(WideStart, 2084 getMulExpr(WideMaxBECount, 2085 getZeroExtendExpr(Step, WideTy, Depth + 1), 2086 SCEV::FlagAnyWrap, Depth + 1), 2087 SCEV::FlagAnyWrap, Depth + 1); 2088 if (SAdd == OperandExtendedAdd) { 2089 // If AR wraps around then 2090 // 2091 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2092 // => SAdd != OperandExtendedAdd 2093 // 2094 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2095 // (SAdd == OperandExtendedAdd => AR is NW) 2096 2097 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2098 2099 // Return the expression with the addrec on the outside. 2100 return getAddRecExpr( 2101 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2102 Depth + 1), 2103 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2104 AR->getNoWrapFlags()); 2105 } 2106 } 2107 } 2108 2109 // Normally, in the cases we can prove no-overflow via a 2110 // backedge guarding condition, we can also compute a backedge 2111 // taken count for the loop. The exceptions are assumptions and 2112 // guards present in the loop -- SCEV is not great at exploiting 2113 // these to compute max backedge taken counts, but can still use 2114 // these to prove lack of overflow. Use this fact to avoid 2115 // doing extra work that may not pay off. 2116 2117 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2118 !AC.assumptions().empty()) { 2119 // If the backedge is guarded by a comparison with the pre-inc 2120 // value the addrec is safe. Also, if the entry is guarded by 2121 // a comparison with the start value and the backedge is 2122 // guarded by a comparison with the post-inc value, the addrec 2123 // is safe. 2124 ICmpInst::Predicate Pred; 2125 const SCEV *OverflowLimit = 2126 getSignedOverflowLimitForStep(Step, &Pred, this); 2127 if (OverflowLimit && 2128 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2129 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2130 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2131 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2132 return getAddRecExpr( 2133 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2134 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2135 } 2136 } 2137 2138 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2139 // if D + (C - D + Step * n) could be proven to not signed wrap 2140 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2141 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2142 const APInt &C = SC->getAPInt(); 2143 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2144 if (D != 0) { 2145 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2146 const SCEV *SResidual = 2147 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2148 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2149 return getAddExpr(SSExtD, SSExtR, 2150 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2151 Depth + 1); 2152 } 2153 } 2154 2155 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2156 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2157 return getAddRecExpr( 2158 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2159 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2160 } 2161 } 2162 2163 // If the input value is provably positive and we could not simplify 2164 // away the sext build a zext instead. 2165 if (isKnownNonNegative(Op)) 2166 return getZeroExtendExpr(Op, Ty, Depth + 1); 2167 2168 // The cast wasn't folded; create an explicit cast node. 2169 // Recompute the insert position, as it may have been invalidated. 2170 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2171 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2172 Op, Ty); 2173 UniqueSCEVs.InsertNode(S, IP); 2174 addToLoopUseLists(S); 2175 return S; 2176 } 2177 2178 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2179 /// unspecified bits out to the given type. 2180 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2181 Type *Ty) { 2182 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2183 "This is not an extending conversion!"); 2184 assert(isSCEVable(Ty) && 2185 "This is not a conversion to a SCEVable type!"); 2186 Ty = getEffectiveSCEVType(Ty); 2187 2188 // Sign-extend negative constants. 2189 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2190 if (SC->getAPInt().isNegative()) 2191 return getSignExtendExpr(Op, Ty); 2192 2193 // Peel off a truncate cast. 2194 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2195 const SCEV *NewOp = T->getOperand(); 2196 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2197 return getAnyExtendExpr(NewOp, Ty); 2198 return getTruncateOrNoop(NewOp, Ty); 2199 } 2200 2201 // Next try a zext cast. If the cast is folded, use it. 2202 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2203 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2204 return ZExt; 2205 2206 // Next try a sext cast. If the cast is folded, use it. 2207 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2208 if (!isa<SCEVSignExtendExpr>(SExt)) 2209 return SExt; 2210 2211 // Force the cast to be folded into the operands of an addrec. 2212 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2213 SmallVector<const SCEV *, 4> Ops; 2214 for (const SCEV *Op : AR->operands()) 2215 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2216 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2217 } 2218 2219 // If the expression is obviously signed, use the sext cast value. 2220 if (isa<SCEVSMaxExpr>(Op)) 2221 return SExt; 2222 2223 // Absent any other information, use the zext cast value. 2224 return ZExt; 2225 } 2226 2227 /// Process the given Ops list, which is a list of operands to be added under 2228 /// the given scale, update the given map. This is a helper function for 2229 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2230 /// that would form an add expression like this: 2231 /// 2232 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2233 /// 2234 /// where A and B are constants, update the map with these values: 2235 /// 2236 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2237 /// 2238 /// and add 13 + A*B*29 to AccumulatedConstant. 2239 /// This will allow getAddRecExpr to produce this: 2240 /// 2241 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2242 /// 2243 /// This form often exposes folding opportunities that are hidden in 2244 /// the original operand list. 2245 /// 2246 /// Return true iff it appears that any interesting folding opportunities 2247 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2248 /// the common case where no interesting opportunities are present, and 2249 /// is also used as a check to avoid infinite recursion. 2250 static bool 2251 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2252 SmallVectorImpl<const SCEV *> &NewOps, 2253 APInt &AccumulatedConstant, 2254 const SCEV *const *Ops, size_t NumOperands, 2255 const APInt &Scale, 2256 ScalarEvolution &SE) { 2257 bool Interesting = false; 2258 2259 // Iterate over the add operands. They are sorted, with constants first. 2260 unsigned i = 0; 2261 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2262 ++i; 2263 // Pull a buried constant out to the outside. 2264 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2265 Interesting = true; 2266 AccumulatedConstant += Scale * C->getAPInt(); 2267 } 2268 2269 // Next comes everything else. We're especially interested in multiplies 2270 // here, but they're in the middle, so just visit the rest with one loop. 2271 for (; i != NumOperands; ++i) { 2272 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2273 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2274 APInt NewScale = 2275 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2276 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2277 // A multiplication of a constant with another add; recurse. 2278 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2279 Interesting |= 2280 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2281 Add->op_begin(), Add->getNumOperands(), 2282 NewScale, SE); 2283 } else { 2284 // A multiplication of a constant with some other value. Update 2285 // the map. 2286 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2287 const SCEV *Key = SE.getMulExpr(MulOps); 2288 auto Pair = M.insert({Key, NewScale}); 2289 if (Pair.second) { 2290 NewOps.push_back(Pair.first->first); 2291 } else { 2292 Pair.first->second += NewScale; 2293 // The map already had an entry for this value, which may indicate 2294 // a folding opportunity. 2295 Interesting = true; 2296 } 2297 } 2298 } else { 2299 // An ordinary operand. Update the map. 2300 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2301 M.insert({Ops[i], Scale}); 2302 if (Pair.second) { 2303 NewOps.push_back(Pair.first->first); 2304 } else { 2305 Pair.first->second += Scale; 2306 // The map already had an entry for this value, which may indicate 2307 // a folding opportunity. 2308 Interesting = true; 2309 } 2310 } 2311 } 2312 2313 return Interesting; 2314 } 2315 2316 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2317 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2318 // can't-overflow flags for the operation if possible. 2319 static SCEV::NoWrapFlags 2320 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2321 const ArrayRef<const SCEV *> Ops, 2322 SCEV::NoWrapFlags Flags) { 2323 using namespace std::placeholders; 2324 2325 using OBO = OverflowingBinaryOperator; 2326 2327 bool CanAnalyze = 2328 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2329 (void)CanAnalyze; 2330 assert(CanAnalyze && "don't call from other places!"); 2331 2332 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2333 SCEV::NoWrapFlags SignOrUnsignWrap = 2334 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2335 2336 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2337 auto IsKnownNonNegative = [&](const SCEV *S) { 2338 return SE->isKnownNonNegative(S); 2339 }; 2340 2341 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2342 Flags = 2343 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2344 2345 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2346 2347 if (SignOrUnsignWrap != SignOrUnsignMask && 2348 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2349 isa<SCEVConstant>(Ops[0])) { 2350 2351 auto Opcode = [&] { 2352 switch (Type) { 2353 case scAddExpr: 2354 return Instruction::Add; 2355 case scMulExpr: 2356 return Instruction::Mul; 2357 default: 2358 llvm_unreachable("Unexpected SCEV op."); 2359 } 2360 }(); 2361 2362 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2363 2364 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2365 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2366 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2367 Opcode, C, OBO::NoSignedWrap); 2368 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2369 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2370 } 2371 2372 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2373 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2374 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2375 Opcode, C, OBO::NoUnsignedWrap); 2376 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2377 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2378 } 2379 } 2380 2381 return Flags; 2382 } 2383 2384 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2385 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2386 } 2387 2388 /// Get a canonical add expression, or something simpler if possible. 2389 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2390 SCEV::NoWrapFlags Flags, 2391 unsigned Depth) { 2392 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2393 "only nuw or nsw allowed"); 2394 assert(!Ops.empty() && "Cannot get empty add!"); 2395 if (Ops.size() == 1) return Ops[0]; 2396 #ifndef NDEBUG 2397 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2398 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2399 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2400 "SCEVAddExpr operand types don't match!"); 2401 #endif 2402 2403 // Sort by complexity, this groups all similar expression types together. 2404 GroupByComplexity(Ops, &LI, DT); 2405 2406 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2407 2408 // If there are any constants, fold them together. 2409 unsigned Idx = 0; 2410 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2411 ++Idx; 2412 assert(Idx < Ops.size()); 2413 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2414 // We found two constants, fold them together! 2415 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2416 if (Ops.size() == 2) return Ops[0]; 2417 Ops.erase(Ops.begin()+1); // Erase the folded element 2418 LHSC = cast<SCEVConstant>(Ops[0]); 2419 } 2420 2421 // If we are left with a constant zero being added, strip it off. 2422 if (LHSC->getValue()->isZero()) { 2423 Ops.erase(Ops.begin()); 2424 --Idx; 2425 } 2426 2427 if (Ops.size() == 1) return Ops[0]; 2428 } 2429 2430 // Limit recursion calls depth. 2431 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2432 return getOrCreateAddExpr(Ops, Flags); 2433 2434 // Okay, check to see if the same value occurs in the operand list more than 2435 // once. If so, merge them together into an multiply expression. Since we 2436 // sorted the list, these values are required to be adjacent. 2437 Type *Ty = Ops[0]->getType(); 2438 bool FoundMatch = false; 2439 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2440 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2441 // Scan ahead to count how many equal operands there are. 2442 unsigned Count = 2; 2443 while (i+Count != e && Ops[i+Count] == Ops[i]) 2444 ++Count; 2445 // Merge the values into a multiply. 2446 const SCEV *Scale = getConstant(Ty, Count); 2447 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2448 if (Ops.size() == Count) 2449 return Mul; 2450 Ops[i] = Mul; 2451 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2452 --i; e -= Count - 1; 2453 FoundMatch = true; 2454 } 2455 if (FoundMatch) 2456 return getAddExpr(Ops, Flags, Depth + 1); 2457 2458 // Check for truncates. If all the operands are truncated from the same 2459 // type, see if factoring out the truncate would permit the result to be 2460 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2461 // if the contents of the resulting outer trunc fold to something simple. 2462 auto FindTruncSrcType = [&]() -> Type * { 2463 // We're ultimately looking to fold an addrec of truncs and muls of only 2464 // constants and truncs, so if we find any other types of SCEV 2465 // as operands of the addrec then we bail and return nullptr here. 2466 // Otherwise, we return the type of the operand of a trunc that we find. 2467 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2468 return T->getOperand()->getType(); 2469 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2470 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2471 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2472 return T->getOperand()->getType(); 2473 } 2474 return nullptr; 2475 }; 2476 if (auto *SrcType = FindTruncSrcType()) { 2477 SmallVector<const SCEV *, 8> LargeOps; 2478 bool Ok = true; 2479 // Check all the operands to see if they can be represented in the 2480 // source type of the truncate. 2481 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2482 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2483 if (T->getOperand()->getType() != SrcType) { 2484 Ok = false; 2485 break; 2486 } 2487 LargeOps.push_back(T->getOperand()); 2488 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2489 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2490 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2491 SmallVector<const SCEV *, 8> LargeMulOps; 2492 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2493 if (const SCEVTruncateExpr *T = 2494 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2495 if (T->getOperand()->getType() != SrcType) { 2496 Ok = false; 2497 break; 2498 } 2499 LargeMulOps.push_back(T->getOperand()); 2500 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2501 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2502 } else { 2503 Ok = false; 2504 break; 2505 } 2506 } 2507 if (Ok) 2508 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2509 } else { 2510 Ok = false; 2511 break; 2512 } 2513 } 2514 if (Ok) { 2515 // Evaluate the expression in the larger type. 2516 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2517 // If it folds to something simple, use it. Otherwise, don't. 2518 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2519 return getTruncateExpr(Fold, Ty); 2520 } 2521 } 2522 2523 // Skip past any other cast SCEVs. 2524 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2525 ++Idx; 2526 2527 // If there are add operands they would be next. 2528 if (Idx < Ops.size()) { 2529 bool DeletedAdd = false; 2530 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2531 if (Ops.size() > AddOpsInlineThreshold || 2532 Add->getNumOperands() > AddOpsInlineThreshold) 2533 break; 2534 // If we have an add, expand the add operands onto the end of the operands 2535 // list. 2536 Ops.erase(Ops.begin()+Idx); 2537 Ops.append(Add->op_begin(), Add->op_end()); 2538 DeletedAdd = true; 2539 } 2540 2541 // If we deleted at least one add, we added operands to the end of the list, 2542 // and they are not necessarily sorted. Recurse to resort and resimplify 2543 // any operands we just acquired. 2544 if (DeletedAdd) 2545 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2546 } 2547 2548 // Skip over the add expression until we get to a multiply. 2549 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2550 ++Idx; 2551 2552 // Check to see if there are any folding opportunities present with 2553 // operands multiplied by constant values. 2554 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2555 uint64_t BitWidth = getTypeSizeInBits(Ty); 2556 DenseMap<const SCEV *, APInt> M; 2557 SmallVector<const SCEV *, 8> NewOps; 2558 APInt AccumulatedConstant(BitWidth, 0); 2559 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2560 Ops.data(), Ops.size(), 2561 APInt(BitWidth, 1), *this)) { 2562 struct APIntCompare { 2563 bool operator()(const APInt &LHS, const APInt &RHS) const { 2564 return LHS.ult(RHS); 2565 } 2566 }; 2567 2568 // Some interesting folding opportunity is present, so its worthwhile to 2569 // re-generate the operands list. Group the operands by constant scale, 2570 // to avoid multiplying by the same constant scale multiple times. 2571 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2572 for (const SCEV *NewOp : NewOps) 2573 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2574 // Re-generate the operands list. 2575 Ops.clear(); 2576 if (AccumulatedConstant != 0) 2577 Ops.push_back(getConstant(AccumulatedConstant)); 2578 for (auto &MulOp : MulOpLists) 2579 if (MulOp.first != 0) 2580 Ops.push_back(getMulExpr( 2581 getConstant(MulOp.first), 2582 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2583 SCEV::FlagAnyWrap, Depth + 1)); 2584 if (Ops.empty()) 2585 return getZero(Ty); 2586 if (Ops.size() == 1) 2587 return Ops[0]; 2588 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2589 } 2590 } 2591 2592 // If we are adding something to a multiply expression, make sure the 2593 // something is not already an operand of the multiply. If so, merge it into 2594 // the multiply. 2595 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2596 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2597 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2598 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2599 if (isa<SCEVConstant>(MulOpSCEV)) 2600 continue; 2601 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2602 if (MulOpSCEV == Ops[AddOp]) { 2603 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2604 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2605 if (Mul->getNumOperands() != 2) { 2606 // If the multiply has more than two operands, we must get the 2607 // Y*Z term. 2608 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2609 Mul->op_begin()+MulOp); 2610 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2611 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2612 } 2613 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2614 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2615 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2616 SCEV::FlagAnyWrap, Depth + 1); 2617 if (Ops.size() == 2) return OuterMul; 2618 if (AddOp < Idx) { 2619 Ops.erase(Ops.begin()+AddOp); 2620 Ops.erase(Ops.begin()+Idx-1); 2621 } else { 2622 Ops.erase(Ops.begin()+Idx); 2623 Ops.erase(Ops.begin()+AddOp-1); 2624 } 2625 Ops.push_back(OuterMul); 2626 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2627 } 2628 2629 // Check this multiply against other multiplies being added together. 2630 for (unsigned OtherMulIdx = Idx+1; 2631 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2632 ++OtherMulIdx) { 2633 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2634 // If MulOp occurs in OtherMul, we can fold the two multiplies 2635 // together. 2636 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2637 OMulOp != e; ++OMulOp) 2638 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2639 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2640 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2641 if (Mul->getNumOperands() != 2) { 2642 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2643 Mul->op_begin()+MulOp); 2644 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2645 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2646 } 2647 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2648 if (OtherMul->getNumOperands() != 2) { 2649 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2650 OtherMul->op_begin()+OMulOp); 2651 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2652 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2653 } 2654 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2655 const SCEV *InnerMulSum = 2656 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2657 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2658 SCEV::FlagAnyWrap, Depth + 1); 2659 if (Ops.size() == 2) return OuterMul; 2660 Ops.erase(Ops.begin()+Idx); 2661 Ops.erase(Ops.begin()+OtherMulIdx-1); 2662 Ops.push_back(OuterMul); 2663 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2664 } 2665 } 2666 } 2667 } 2668 2669 // If there are any add recurrences in the operands list, see if any other 2670 // added values are loop invariant. If so, we can fold them into the 2671 // recurrence. 2672 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2673 ++Idx; 2674 2675 // Scan over all recurrences, trying to fold loop invariants into them. 2676 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2677 // Scan all of the other operands to this add and add them to the vector if 2678 // they are loop invariant w.r.t. the recurrence. 2679 SmallVector<const SCEV *, 8> LIOps; 2680 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2681 const Loop *AddRecLoop = AddRec->getLoop(); 2682 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2683 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2684 LIOps.push_back(Ops[i]); 2685 Ops.erase(Ops.begin()+i); 2686 --i; --e; 2687 } 2688 2689 // If we found some loop invariants, fold them into the recurrence. 2690 if (!LIOps.empty()) { 2691 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2692 LIOps.push_back(AddRec->getStart()); 2693 2694 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2695 AddRec->op_end()); 2696 // This follows from the fact that the no-wrap flags on the outer add 2697 // expression are applicable on the 0th iteration, when the add recurrence 2698 // will be equal to its start value. 2699 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2700 2701 // Build the new addrec. Propagate the NUW and NSW flags if both the 2702 // outer add and the inner addrec are guaranteed to have no overflow. 2703 // Always propagate NW. 2704 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2705 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2706 2707 // If all of the other operands were loop invariant, we are done. 2708 if (Ops.size() == 1) return NewRec; 2709 2710 // Otherwise, add the folded AddRec by the non-invariant parts. 2711 for (unsigned i = 0;; ++i) 2712 if (Ops[i] == AddRec) { 2713 Ops[i] = NewRec; 2714 break; 2715 } 2716 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2717 } 2718 2719 // Okay, if there weren't any loop invariants to be folded, check to see if 2720 // there are multiple AddRec's with the same loop induction variable being 2721 // added together. If so, we can fold them. 2722 for (unsigned OtherIdx = Idx+1; 2723 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2724 ++OtherIdx) { 2725 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2726 // so that the 1st found AddRecExpr is dominated by all others. 2727 assert(DT.dominates( 2728 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2729 AddRec->getLoop()->getHeader()) && 2730 "AddRecExprs are not sorted in reverse dominance order?"); 2731 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2732 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2733 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2734 AddRec->op_end()); 2735 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2736 ++OtherIdx) { 2737 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2738 if (OtherAddRec->getLoop() == AddRecLoop) { 2739 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2740 i != e; ++i) { 2741 if (i >= AddRecOps.size()) { 2742 AddRecOps.append(OtherAddRec->op_begin()+i, 2743 OtherAddRec->op_end()); 2744 break; 2745 } 2746 SmallVector<const SCEV *, 2> TwoOps = { 2747 AddRecOps[i], OtherAddRec->getOperand(i)}; 2748 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2749 } 2750 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2751 } 2752 } 2753 // Step size has changed, so we cannot guarantee no self-wraparound. 2754 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2755 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2756 } 2757 } 2758 2759 // Otherwise couldn't fold anything into this recurrence. Move onto the 2760 // next one. 2761 } 2762 2763 // Okay, it looks like we really DO need an add expr. Check to see if we 2764 // already have one, otherwise create a new one. 2765 return getOrCreateAddExpr(Ops, Flags); 2766 } 2767 2768 const SCEV * 2769 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2770 SCEV::NoWrapFlags Flags) { 2771 FoldingSetNodeID ID; 2772 ID.AddInteger(scAddExpr); 2773 for (const SCEV *Op : Ops) 2774 ID.AddPointer(Op); 2775 void *IP = nullptr; 2776 SCEVAddExpr *S = 2777 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2778 if (!S) { 2779 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2780 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2781 S = new (SCEVAllocator) 2782 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2783 UniqueSCEVs.InsertNode(S, IP); 2784 addToLoopUseLists(S); 2785 } 2786 S->setNoWrapFlags(Flags); 2787 return S; 2788 } 2789 2790 const SCEV * 2791 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2792 const Loop *L, SCEV::NoWrapFlags Flags) { 2793 FoldingSetNodeID ID; 2794 ID.AddInteger(scAddRecExpr); 2795 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2796 ID.AddPointer(Ops[i]); 2797 ID.AddPointer(L); 2798 void *IP = nullptr; 2799 SCEVAddRecExpr *S = 2800 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2801 if (!S) { 2802 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2803 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2804 S = new (SCEVAllocator) 2805 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2806 UniqueSCEVs.InsertNode(S, IP); 2807 addToLoopUseLists(S); 2808 } 2809 S->setNoWrapFlags(Flags); 2810 return S; 2811 } 2812 2813 const SCEV * 2814 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2815 SCEV::NoWrapFlags Flags) { 2816 FoldingSetNodeID ID; 2817 ID.AddInteger(scMulExpr); 2818 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2819 ID.AddPointer(Ops[i]); 2820 void *IP = nullptr; 2821 SCEVMulExpr *S = 2822 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2823 if (!S) { 2824 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2825 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2826 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2827 O, Ops.size()); 2828 UniqueSCEVs.InsertNode(S, IP); 2829 addToLoopUseLists(S); 2830 } 2831 S->setNoWrapFlags(Flags); 2832 return S; 2833 } 2834 2835 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2836 uint64_t k = i*j; 2837 if (j > 1 && k / j != i) Overflow = true; 2838 return k; 2839 } 2840 2841 /// Compute the result of "n choose k", the binomial coefficient. If an 2842 /// intermediate computation overflows, Overflow will be set and the return will 2843 /// be garbage. Overflow is not cleared on absence of overflow. 2844 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2845 // We use the multiplicative formula: 2846 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2847 // At each iteration, we take the n-th term of the numeral and divide by the 2848 // (k-n)th term of the denominator. This division will always produce an 2849 // integral result, and helps reduce the chance of overflow in the 2850 // intermediate computations. However, we can still overflow even when the 2851 // final result would fit. 2852 2853 if (n == 0 || n == k) return 1; 2854 if (k > n) return 0; 2855 2856 if (k > n/2) 2857 k = n-k; 2858 2859 uint64_t r = 1; 2860 for (uint64_t i = 1; i <= k; ++i) { 2861 r = umul_ov(r, n-(i-1), Overflow); 2862 r /= i; 2863 } 2864 return r; 2865 } 2866 2867 /// Determine if any of the operands in this SCEV are a constant or if 2868 /// any of the add or multiply expressions in this SCEV contain a constant. 2869 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2870 struct FindConstantInAddMulChain { 2871 bool FoundConstant = false; 2872 2873 bool follow(const SCEV *S) { 2874 FoundConstant |= isa<SCEVConstant>(S); 2875 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2876 } 2877 2878 bool isDone() const { 2879 return FoundConstant; 2880 } 2881 }; 2882 2883 FindConstantInAddMulChain F; 2884 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2885 ST.visitAll(StartExpr); 2886 return F.FoundConstant; 2887 } 2888 2889 /// Get a canonical multiply expression, or something simpler if possible. 2890 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2891 SCEV::NoWrapFlags Flags, 2892 unsigned Depth) { 2893 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2894 "only nuw or nsw allowed"); 2895 assert(!Ops.empty() && "Cannot get empty mul!"); 2896 if (Ops.size() == 1) return Ops[0]; 2897 #ifndef NDEBUG 2898 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2899 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2900 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2901 "SCEVMulExpr operand types don't match!"); 2902 #endif 2903 2904 // Sort by complexity, this groups all similar expression types together. 2905 GroupByComplexity(Ops, &LI, DT); 2906 2907 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2908 2909 // Limit recursion calls depth. 2910 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2911 return getOrCreateMulExpr(Ops, Flags); 2912 2913 // If there are any constants, fold them together. 2914 unsigned Idx = 0; 2915 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2916 2917 if (Ops.size() == 2) 2918 // C1*(C2+V) -> C1*C2 + C1*V 2919 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2920 // If any of Add's ops are Adds or Muls with a constant, apply this 2921 // transformation as well. 2922 // 2923 // TODO: There are some cases where this transformation is not 2924 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2925 // this transformation should be narrowed down. 2926 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2927 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2928 SCEV::FlagAnyWrap, Depth + 1), 2929 getMulExpr(LHSC, Add->getOperand(1), 2930 SCEV::FlagAnyWrap, Depth + 1), 2931 SCEV::FlagAnyWrap, Depth + 1); 2932 2933 ++Idx; 2934 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2935 // We found two constants, fold them together! 2936 ConstantInt *Fold = 2937 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2938 Ops[0] = getConstant(Fold); 2939 Ops.erase(Ops.begin()+1); // Erase the folded element 2940 if (Ops.size() == 1) return Ops[0]; 2941 LHSC = cast<SCEVConstant>(Ops[0]); 2942 } 2943 2944 // If we are left with a constant one being multiplied, strip it off. 2945 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2946 Ops.erase(Ops.begin()); 2947 --Idx; 2948 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2949 // If we have a multiply of zero, it will always be zero. 2950 return Ops[0]; 2951 } else if (Ops[0]->isAllOnesValue()) { 2952 // If we have a mul by -1 of an add, try distributing the -1 among the 2953 // add operands. 2954 if (Ops.size() == 2) { 2955 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2956 SmallVector<const SCEV *, 4> NewOps; 2957 bool AnyFolded = false; 2958 for (const SCEV *AddOp : Add->operands()) { 2959 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2960 Depth + 1); 2961 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2962 NewOps.push_back(Mul); 2963 } 2964 if (AnyFolded) 2965 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2966 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2967 // Negation preserves a recurrence's no self-wrap property. 2968 SmallVector<const SCEV *, 4> Operands; 2969 for (const SCEV *AddRecOp : AddRec->operands()) 2970 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2971 Depth + 1)); 2972 2973 return getAddRecExpr(Operands, AddRec->getLoop(), 2974 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2975 } 2976 } 2977 } 2978 2979 if (Ops.size() == 1) 2980 return Ops[0]; 2981 } 2982 2983 // Skip over the add expression until we get to a multiply. 2984 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2985 ++Idx; 2986 2987 // If there are mul operands inline them all into this expression. 2988 if (Idx < Ops.size()) { 2989 bool DeletedMul = false; 2990 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2991 if (Ops.size() > MulOpsInlineThreshold) 2992 break; 2993 // If we have an mul, expand the mul operands onto the end of the 2994 // operands list. 2995 Ops.erase(Ops.begin()+Idx); 2996 Ops.append(Mul->op_begin(), Mul->op_end()); 2997 DeletedMul = true; 2998 } 2999 3000 // If we deleted at least one mul, we added operands to the end of the 3001 // list, and they are not necessarily sorted. Recurse to resort and 3002 // resimplify any operands we just acquired. 3003 if (DeletedMul) 3004 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3005 } 3006 3007 // If there are any add recurrences in the operands list, see if any other 3008 // added values are loop invariant. If so, we can fold them into the 3009 // recurrence. 3010 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3011 ++Idx; 3012 3013 // Scan over all recurrences, trying to fold loop invariants into them. 3014 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3015 // Scan all of the other operands to this mul and add them to the vector 3016 // if they are loop invariant w.r.t. the recurrence. 3017 SmallVector<const SCEV *, 8> LIOps; 3018 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3019 const Loop *AddRecLoop = AddRec->getLoop(); 3020 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3021 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3022 LIOps.push_back(Ops[i]); 3023 Ops.erase(Ops.begin()+i); 3024 --i; --e; 3025 } 3026 3027 // If we found some loop invariants, fold them into the recurrence. 3028 if (!LIOps.empty()) { 3029 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3030 SmallVector<const SCEV *, 4> NewOps; 3031 NewOps.reserve(AddRec->getNumOperands()); 3032 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3033 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3034 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3035 SCEV::FlagAnyWrap, Depth + 1)); 3036 3037 // Build the new addrec. Propagate the NUW and NSW flags if both the 3038 // outer mul and the inner addrec are guaranteed to have no overflow. 3039 // 3040 // No self-wrap cannot be guaranteed after changing the step size, but 3041 // will be inferred if either NUW or NSW is true. 3042 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 3043 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 3044 3045 // If all of the other operands were loop invariant, we are done. 3046 if (Ops.size() == 1) return NewRec; 3047 3048 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3049 for (unsigned i = 0;; ++i) 3050 if (Ops[i] == AddRec) { 3051 Ops[i] = NewRec; 3052 break; 3053 } 3054 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3055 } 3056 3057 // Okay, if there weren't any loop invariants to be folded, check to see 3058 // if there are multiple AddRec's with the same loop induction variable 3059 // being multiplied together. If so, we can fold them. 3060 3061 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3062 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3063 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3064 // ]]],+,...up to x=2n}. 3065 // Note that the arguments to choose() are always integers with values 3066 // known at compile time, never SCEV objects. 3067 // 3068 // The implementation avoids pointless extra computations when the two 3069 // addrec's are of different length (mathematically, it's equivalent to 3070 // an infinite stream of zeros on the right). 3071 bool OpsModified = false; 3072 for (unsigned OtherIdx = Idx+1; 3073 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3074 ++OtherIdx) { 3075 const SCEVAddRecExpr *OtherAddRec = 3076 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3077 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3078 continue; 3079 3080 // Limit max number of arguments to avoid creation of unreasonably big 3081 // SCEVAddRecs with very complex operands. 3082 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3083 MaxAddRecSize || isHugeExpression(AddRec) || 3084 isHugeExpression(OtherAddRec)) 3085 continue; 3086 3087 bool Overflow = false; 3088 Type *Ty = AddRec->getType(); 3089 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3090 SmallVector<const SCEV*, 7> AddRecOps; 3091 for (int x = 0, xe = AddRec->getNumOperands() + 3092 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3093 SmallVector <const SCEV *, 7> SumOps; 3094 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3095 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3096 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3097 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3098 z < ze && !Overflow; ++z) { 3099 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3100 uint64_t Coeff; 3101 if (LargerThan64Bits) 3102 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3103 else 3104 Coeff = Coeff1*Coeff2; 3105 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3106 const SCEV *Term1 = AddRec->getOperand(y-z); 3107 const SCEV *Term2 = OtherAddRec->getOperand(z); 3108 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3109 SCEV::FlagAnyWrap, Depth + 1)); 3110 } 3111 } 3112 if (SumOps.empty()) 3113 SumOps.push_back(getZero(Ty)); 3114 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3115 } 3116 if (!Overflow) { 3117 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3118 SCEV::FlagAnyWrap); 3119 if (Ops.size() == 2) return NewAddRec; 3120 Ops[Idx] = NewAddRec; 3121 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3122 OpsModified = true; 3123 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3124 if (!AddRec) 3125 break; 3126 } 3127 } 3128 if (OpsModified) 3129 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3130 3131 // Otherwise couldn't fold anything into this recurrence. Move onto the 3132 // next one. 3133 } 3134 3135 // Okay, it looks like we really DO need an mul expr. Check to see if we 3136 // already have one, otherwise create a new one. 3137 return getOrCreateMulExpr(Ops, Flags); 3138 } 3139 3140 /// Represents an unsigned remainder expression based on unsigned division. 3141 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3142 const SCEV *RHS) { 3143 assert(getEffectiveSCEVType(LHS->getType()) == 3144 getEffectiveSCEVType(RHS->getType()) && 3145 "SCEVURemExpr operand types don't match!"); 3146 3147 // Short-circuit easy cases 3148 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3149 // If constant is one, the result is trivial 3150 if (RHSC->getValue()->isOne()) 3151 return getZero(LHS->getType()); // X urem 1 --> 0 3152 3153 // If constant is a power of two, fold into a zext(trunc(LHS)). 3154 if (RHSC->getAPInt().isPowerOf2()) { 3155 Type *FullTy = LHS->getType(); 3156 Type *TruncTy = 3157 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3158 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3159 } 3160 } 3161 3162 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3163 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3164 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3165 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3166 } 3167 3168 /// Get a canonical unsigned division expression, or something simpler if 3169 /// possible. 3170 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3171 const SCEV *RHS) { 3172 assert(getEffectiveSCEVType(LHS->getType()) == 3173 getEffectiveSCEVType(RHS->getType()) && 3174 "SCEVUDivExpr operand types don't match!"); 3175 3176 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3177 if (RHSC->getValue()->isOne()) 3178 return LHS; // X udiv 1 --> x 3179 // If the denominator is zero, the result of the udiv is undefined. Don't 3180 // try to analyze it, because the resolution chosen here may differ from 3181 // the resolution chosen in other parts of the compiler. 3182 if (!RHSC->getValue()->isZero()) { 3183 // Determine if the division can be folded into the operands of 3184 // its operands. 3185 // TODO: Generalize this to non-constants by using known-bits information. 3186 Type *Ty = LHS->getType(); 3187 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3188 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3189 // For non-power-of-two values, effectively round the value up to the 3190 // nearest power of two. 3191 if (!RHSC->getAPInt().isPowerOf2()) 3192 ++MaxShiftAmt; 3193 IntegerType *ExtTy = 3194 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3195 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3196 if (const SCEVConstant *Step = 3197 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3198 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3199 const APInt &StepInt = Step->getAPInt(); 3200 const APInt &DivInt = RHSC->getAPInt(); 3201 if (!StepInt.urem(DivInt) && 3202 getZeroExtendExpr(AR, ExtTy) == 3203 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3204 getZeroExtendExpr(Step, ExtTy), 3205 AR->getLoop(), SCEV::FlagAnyWrap)) { 3206 SmallVector<const SCEV *, 4> Operands; 3207 for (const SCEV *Op : AR->operands()) 3208 Operands.push_back(getUDivExpr(Op, RHS)); 3209 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3210 } 3211 /// Get a canonical UDivExpr for a recurrence. 3212 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3213 // We can currently only fold X%N if X is constant. 3214 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3215 if (StartC && !DivInt.urem(StepInt) && 3216 getZeroExtendExpr(AR, ExtTy) == 3217 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3218 getZeroExtendExpr(Step, ExtTy), 3219 AR->getLoop(), SCEV::FlagAnyWrap)) { 3220 const APInt &StartInt = StartC->getAPInt(); 3221 const APInt &StartRem = StartInt.urem(StepInt); 3222 if (StartRem != 0) 3223 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3224 AR->getLoop(), SCEV::FlagNW); 3225 } 3226 } 3227 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3228 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3229 SmallVector<const SCEV *, 4> Operands; 3230 for (const SCEV *Op : M->operands()) 3231 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3232 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3233 // Find an operand that's safely divisible. 3234 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3235 const SCEV *Op = M->getOperand(i); 3236 const SCEV *Div = getUDivExpr(Op, RHSC); 3237 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3238 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3239 M->op_end()); 3240 Operands[i] = Div; 3241 return getMulExpr(Operands); 3242 } 3243 } 3244 } 3245 3246 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3247 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3248 if (auto *DivisorConstant = 3249 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3250 bool Overflow = false; 3251 APInt NewRHS = 3252 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3253 if (Overflow) { 3254 return getConstant(RHSC->getType(), 0, false); 3255 } 3256 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3257 } 3258 } 3259 3260 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3261 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3262 SmallVector<const SCEV *, 4> Operands; 3263 for (const SCEV *Op : A->operands()) 3264 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3265 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3266 Operands.clear(); 3267 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3268 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3269 if (isa<SCEVUDivExpr>(Op) || 3270 getMulExpr(Op, RHS) != A->getOperand(i)) 3271 break; 3272 Operands.push_back(Op); 3273 } 3274 if (Operands.size() == A->getNumOperands()) 3275 return getAddExpr(Operands); 3276 } 3277 } 3278 3279 // Fold if both operands are constant. 3280 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3281 Constant *LHSCV = LHSC->getValue(); 3282 Constant *RHSCV = RHSC->getValue(); 3283 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3284 RHSCV))); 3285 } 3286 } 3287 } 3288 3289 FoldingSetNodeID ID; 3290 ID.AddInteger(scUDivExpr); 3291 ID.AddPointer(LHS); 3292 ID.AddPointer(RHS); 3293 void *IP = nullptr; 3294 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3295 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3296 LHS, RHS); 3297 UniqueSCEVs.InsertNode(S, IP); 3298 addToLoopUseLists(S); 3299 return S; 3300 } 3301 3302 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3303 APInt A = C1->getAPInt().abs(); 3304 APInt B = C2->getAPInt().abs(); 3305 uint32_t ABW = A.getBitWidth(); 3306 uint32_t BBW = B.getBitWidth(); 3307 3308 if (ABW > BBW) 3309 B = B.zext(ABW); 3310 else if (ABW < BBW) 3311 A = A.zext(BBW); 3312 3313 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3314 } 3315 3316 /// Get a canonical unsigned division expression, or something simpler if 3317 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3318 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3319 /// it's not exact because the udiv may be clearing bits. 3320 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3321 const SCEV *RHS) { 3322 // TODO: we could try to find factors in all sorts of things, but for now we 3323 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3324 // end of this file for inspiration. 3325 3326 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3327 if (!Mul || !Mul->hasNoUnsignedWrap()) 3328 return getUDivExpr(LHS, RHS); 3329 3330 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3331 // If the mulexpr multiplies by a constant, then that constant must be the 3332 // first element of the mulexpr. 3333 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3334 if (LHSCst == RHSCst) { 3335 SmallVector<const SCEV *, 2> Operands; 3336 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3337 return getMulExpr(Operands); 3338 } 3339 3340 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3341 // that there's a factor provided by one of the other terms. We need to 3342 // check. 3343 APInt Factor = gcd(LHSCst, RHSCst); 3344 if (!Factor.isIntN(1)) { 3345 LHSCst = 3346 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3347 RHSCst = 3348 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3349 SmallVector<const SCEV *, 2> Operands; 3350 Operands.push_back(LHSCst); 3351 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3352 LHS = getMulExpr(Operands); 3353 RHS = RHSCst; 3354 Mul = dyn_cast<SCEVMulExpr>(LHS); 3355 if (!Mul) 3356 return getUDivExactExpr(LHS, RHS); 3357 } 3358 } 3359 } 3360 3361 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3362 if (Mul->getOperand(i) == RHS) { 3363 SmallVector<const SCEV *, 2> Operands; 3364 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3365 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3366 return getMulExpr(Operands); 3367 } 3368 } 3369 3370 return getUDivExpr(LHS, RHS); 3371 } 3372 3373 /// Get an add recurrence expression for the specified loop. Simplify the 3374 /// expression as much as possible. 3375 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3376 const Loop *L, 3377 SCEV::NoWrapFlags Flags) { 3378 SmallVector<const SCEV *, 4> Operands; 3379 Operands.push_back(Start); 3380 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3381 if (StepChrec->getLoop() == L) { 3382 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3383 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3384 } 3385 3386 Operands.push_back(Step); 3387 return getAddRecExpr(Operands, L, Flags); 3388 } 3389 3390 /// Get an add recurrence expression for the specified loop. Simplify the 3391 /// expression as much as possible. 3392 const SCEV * 3393 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3394 const Loop *L, SCEV::NoWrapFlags Flags) { 3395 if (Operands.size() == 1) return Operands[0]; 3396 #ifndef NDEBUG 3397 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3398 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3399 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3400 "SCEVAddRecExpr operand types don't match!"); 3401 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3402 assert(isLoopInvariant(Operands[i], L) && 3403 "SCEVAddRecExpr operand is not loop-invariant!"); 3404 #endif 3405 3406 if (Operands.back()->isZero()) { 3407 Operands.pop_back(); 3408 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3409 } 3410 3411 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3412 // use that information to infer NUW and NSW flags. However, computing a 3413 // BE count requires calling getAddRecExpr, so we may not yet have a 3414 // meaningful BE count at this point (and if we don't, we'd be stuck 3415 // with a SCEVCouldNotCompute as the cached BE count). 3416 3417 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3418 3419 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3420 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3421 const Loop *NestedLoop = NestedAR->getLoop(); 3422 if (L->contains(NestedLoop) 3423 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3424 : (!NestedLoop->contains(L) && 3425 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3426 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3427 NestedAR->op_end()); 3428 Operands[0] = NestedAR->getStart(); 3429 // AddRecs require their operands be loop-invariant with respect to their 3430 // loops. Don't perform this transformation if it would break this 3431 // requirement. 3432 bool AllInvariant = all_of( 3433 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3434 3435 if (AllInvariant) { 3436 // Create a recurrence for the outer loop with the same step size. 3437 // 3438 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3439 // inner recurrence has the same property. 3440 SCEV::NoWrapFlags OuterFlags = 3441 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3442 3443 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3444 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3445 return isLoopInvariant(Op, NestedLoop); 3446 }); 3447 3448 if (AllInvariant) { 3449 // Ok, both add recurrences are valid after the transformation. 3450 // 3451 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3452 // the outer recurrence has the same property. 3453 SCEV::NoWrapFlags InnerFlags = 3454 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3455 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3456 } 3457 } 3458 // Reset Operands to its original state. 3459 Operands[0] = NestedAR; 3460 } 3461 } 3462 3463 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3464 // already have one, otherwise create a new one. 3465 return getOrCreateAddRecExpr(Operands, L, Flags); 3466 } 3467 3468 const SCEV * 3469 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3470 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3471 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3472 // getSCEV(Base)->getType() has the same address space as Base->getType() 3473 // because SCEV::getType() preserves the address space. 3474 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3475 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3476 // instruction to its SCEV, because the Instruction may be guarded by control 3477 // flow and the no-overflow bits may not be valid for the expression in any 3478 // context. This can be fixed similarly to how these flags are handled for 3479 // adds. 3480 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3481 : SCEV::FlagAnyWrap; 3482 3483 const SCEV *TotalOffset = getZero(IntPtrTy); 3484 // The array size is unimportant. The first thing we do on CurTy is getting 3485 // its element type. 3486 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3487 for (const SCEV *IndexExpr : IndexExprs) { 3488 // Compute the (potentially symbolic) offset in bytes for this index. 3489 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3490 // For a struct, add the member offset. 3491 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3492 unsigned FieldNo = Index->getZExtValue(); 3493 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3494 3495 // Add the field offset to the running total offset. 3496 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3497 3498 // Update CurTy to the type of the field at Index. 3499 CurTy = STy->getTypeAtIndex(Index); 3500 } else { 3501 // Update CurTy to its element type. 3502 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3503 // For an array, add the element offset, explicitly scaled. 3504 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3505 // Getelementptr indices are signed. 3506 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3507 3508 // Multiply the index by the element size to compute the element offset. 3509 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3510 3511 // Add the element offset to the running total offset. 3512 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3513 } 3514 } 3515 3516 // Add the total offset from all the GEP indices to the base. 3517 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3518 } 3519 3520 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3521 const SCEV *RHS) { 3522 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3523 return getSMaxExpr(Ops); 3524 } 3525 3526 std::tuple<const SCEV *, FoldingSetNodeID, void *> 3527 ScalarEvolution::findExistingSCEVInCache(int SCEVType, 3528 ArrayRef<const SCEV *> Ops) { 3529 FoldingSetNodeID ID; 3530 void *IP = nullptr; 3531 ID.AddInteger(SCEVType); 3532 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3533 ID.AddPointer(Ops[i]); 3534 return std::tuple<const SCEV *, FoldingSetNodeID, void *>( 3535 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3536 } 3537 3538 const SCEV * 3539 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3540 assert(!Ops.empty() && "Cannot get empty smax!"); 3541 if (Ops.size() == 1) return Ops[0]; 3542 #ifndef NDEBUG 3543 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3544 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3545 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3546 "SCEVSMaxExpr operand types don't match!"); 3547 #endif 3548 3549 // Sort by complexity, this groups all similar expression types together. 3550 GroupByComplexity(Ops, &LI, DT); 3551 3552 // Check if we have created the same SMax expression before. 3553 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(scSMaxExpr, Ops))) { 3554 return S; 3555 } 3556 3557 // If there are any constants, fold them together. 3558 unsigned Idx = 0; 3559 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3560 ++Idx; 3561 assert(Idx < Ops.size()); 3562 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3563 // We found two constants, fold them together! 3564 ConstantInt *Fold = ConstantInt::get( 3565 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3566 Ops[0] = getConstant(Fold); 3567 Ops.erase(Ops.begin()+1); // Erase the folded element 3568 if (Ops.size() == 1) return Ops[0]; 3569 LHSC = cast<SCEVConstant>(Ops[0]); 3570 } 3571 3572 // If we are left with a constant minimum-int, strip it off. 3573 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3574 Ops.erase(Ops.begin()); 3575 --Idx; 3576 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3577 // If we have an smax with a constant maximum-int, it will always be 3578 // maximum-int. 3579 return Ops[0]; 3580 } 3581 3582 if (Ops.size() == 1) return Ops[0]; 3583 } 3584 3585 // Find the first SMax 3586 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3587 ++Idx; 3588 3589 // Check to see if one of the operands is an SMax. If so, expand its operands 3590 // onto our operand list, and recurse to simplify. 3591 if (Idx < Ops.size()) { 3592 bool DeletedSMax = false; 3593 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3594 Ops.erase(Ops.begin()+Idx); 3595 Ops.append(SMax->op_begin(), SMax->op_end()); 3596 DeletedSMax = true; 3597 } 3598 3599 if (DeletedSMax) 3600 return getSMaxExpr(Ops); 3601 } 3602 3603 // Okay, check to see if the same value occurs in the operand list twice. If 3604 // so, delete one. Since we sorted the list, these values are required to 3605 // be adjacent. 3606 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3607 // X smax Y smax Y --> X smax Y 3608 // X smax Y --> X, if X is always greater than Y 3609 if (Ops[i] == Ops[i+1] || 3610 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3611 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3612 --i; --e; 3613 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3614 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3615 --i; --e; 3616 } 3617 3618 if (Ops.size() == 1) return Ops[0]; 3619 3620 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3621 3622 // Okay, it looks like we really DO need an smax expr. Check to see if we 3623 // already have one, otherwise create a new one. 3624 const SCEV *ExistingSCEV; 3625 FoldingSetNodeID ID; 3626 void *IP; 3627 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(scSMaxExpr, Ops); 3628 if (ExistingSCEV) 3629 return ExistingSCEV; 3630 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3631 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3632 SCEV *S = 3633 new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 3634 UniqueSCEVs.InsertNode(S, IP); 3635 addToLoopUseLists(S); 3636 return S; 3637 } 3638 3639 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3640 const SCEV *RHS) { 3641 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3642 return getUMaxExpr(Ops); 3643 } 3644 3645 const SCEV * 3646 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3647 assert(!Ops.empty() && "Cannot get empty umax!"); 3648 if (Ops.size() == 1) return Ops[0]; 3649 #ifndef NDEBUG 3650 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3651 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3652 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3653 "SCEVUMaxExpr operand types don't match!"); 3654 #endif 3655 3656 // Sort by complexity, this groups all similar expression types together. 3657 GroupByComplexity(Ops, &LI, DT); 3658 3659 // Check if we have created the same UMax expression before. 3660 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(scUMaxExpr, Ops))) { 3661 return S; 3662 } 3663 3664 // If there are any constants, fold them together. 3665 unsigned Idx = 0; 3666 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3667 ++Idx; 3668 assert(Idx < Ops.size()); 3669 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3670 // We found two constants, fold them together! 3671 ConstantInt *Fold = ConstantInt::get( 3672 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3673 Ops[0] = getConstant(Fold); 3674 Ops.erase(Ops.begin()+1); // Erase the folded element 3675 if (Ops.size() == 1) return Ops[0]; 3676 LHSC = cast<SCEVConstant>(Ops[0]); 3677 } 3678 3679 // If we are left with a constant minimum-int, strip it off. 3680 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3681 Ops.erase(Ops.begin()); 3682 --Idx; 3683 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3684 // If we have an umax with a constant maximum-int, it will always be 3685 // maximum-int. 3686 return Ops[0]; 3687 } 3688 3689 if (Ops.size() == 1) return Ops[0]; 3690 } 3691 3692 // Find the first UMax 3693 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3694 ++Idx; 3695 3696 // Check to see if one of the operands is a UMax. If so, expand its operands 3697 // onto our operand list, and recurse to simplify. 3698 if (Idx < Ops.size()) { 3699 bool DeletedUMax = false; 3700 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3701 Ops.erase(Ops.begin()+Idx); 3702 Ops.append(UMax->op_begin(), UMax->op_end()); 3703 DeletedUMax = true; 3704 } 3705 3706 if (DeletedUMax) 3707 return getUMaxExpr(Ops); 3708 } 3709 3710 // Okay, check to see if the same value occurs in the operand list twice. If 3711 // so, delete one. Since we sorted the list, these values are required to 3712 // be adjacent. 3713 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3714 // X umax Y umax Y --> X umax Y 3715 // X umax Y --> X, if X is always greater than Y 3716 if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning( 3717 ICmpInst::ICMP_UGE, Ops[i], Ops[i + 1])) { 3718 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3719 --i; --e; 3720 } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, Ops[i], 3721 Ops[i + 1])) { 3722 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3723 --i; --e; 3724 } 3725 3726 if (Ops.size() == 1) return Ops[0]; 3727 3728 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3729 3730 // Okay, it looks like we really DO need a umax expr. Check to see if we 3731 // already have one, otherwise create a new one. 3732 const SCEV *ExistingSCEV; 3733 FoldingSetNodeID ID; 3734 void *IP; 3735 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(scUMaxExpr, Ops); 3736 if (ExistingSCEV) 3737 return ExistingSCEV; 3738 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3739 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3740 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3741 O, Ops.size()); 3742 UniqueSCEVs.InsertNode(S, IP); 3743 addToLoopUseLists(S); 3744 return S; 3745 } 3746 3747 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3748 const SCEV *RHS) { 3749 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3750 return getSMinExpr(Ops); 3751 } 3752 3753 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3754 // ~smax(~x, ~y, ~z) == smin(x, y, z). 3755 SmallVector<const SCEV *, 2> NotOps; 3756 for (auto *S : Ops) 3757 NotOps.push_back(getNotSCEV(S)); 3758 return getNotSCEV(getSMaxExpr(NotOps)); 3759 } 3760 3761 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3762 const SCEV *RHS) { 3763 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3764 return getUMinExpr(Ops); 3765 } 3766 3767 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3768 assert(!Ops.empty() && "At least one operand must be!"); 3769 // Trivial case. 3770 if (Ops.size() == 1) 3771 return Ops[0]; 3772 3773 // ~umax(~x, ~y, ~z) == umin(x, y, z). 3774 SmallVector<const SCEV *, 2> NotOps; 3775 for (auto *S : Ops) 3776 NotOps.push_back(getNotSCEV(S)); 3777 return getNotSCEV(getUMaxExpr(NotOps)); 3778 } 3779 3780 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3781 // We can bypass creating a target-independent 3782 // constant expression and then folding it back into a ConstantInt. 3783 // This is just a compile-time optimization. 3784 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3785 } 3786 3787 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3788 StructType *STy, 3789 unsigned FieldNo) { 3790 // We can bypass creating a target-independent 3791 // constant expression and then folding it back into a ConstantInt. 3792 // This is just a compile-time optimization. 3793 return getConstant( 3794 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3795 } 3796 3797 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3798 // Don't attempt to do anything other than create a SCEVUnknown object 3799 // here. createSCEV only calls getUnknown after checking for all other 3800 // interesting possibilities, and any other code that calls getUnknown 3801 // is doing so in order to hide a value from SCEV canonicalization. 3802 3803 FoldingSetNodeID ID; 3804 ID.AddInteger(scUnknown); 3805 ID.AddPointer(V); 3806 void *IP = nullptr; 3807 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3808 assert(cast<SCEVUnknown>(S)->getValue() == V && 3809 "Stale SCEVUnknown in uniquing map!"); 3810 return S; 3811 } 3812 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3813 FirstUnknown); 3814 FirstUnknown = cast<SCEVUnknown>(S); 3815 UniqueSCEVs.InsertNode(S, IP); 3816 return S; 3817 } 3818 3819 //===----------------------------------------------------------------------===// 3820 // Basic SCEV Analysis and PHI Idiom Recognition Code 3821 // 3822 3823 /// Test if values of the given type are analyzable within the SCEV 3824 /// framework. This primarily includes integer types, and it can optionally 3825 /// include pointer types if the ScalarEvolution class has access to 3826 /// target-specific information. 3827 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3828 // Integers and pointers are always SCEVable. 3829 return Ty->isIntOrPtrTy(); 3830 } 3831 3832 /// Return the size in bits of the specified type, for which isSCEVable must 3833 /// return true. 3834 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3835 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3836 if (Ty->isPointerTy()) 3837 return getDataLayout().getIndexTypeSizeInBits(Ty); 3838 return getDataLayout().getTypeSizeInBits(Ty); 3839 } 3840 3841 /// Return a type with the same bitwidth as the given type and which represents 3842 /// how SCEV will treat the given type, for which isSCEVable must return 3843 /// true. For pointer types, this is the pointer-sized integer type. 3844 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3845 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3846 3847 if (Ty->isIntegerTy()) 3848 return Ty; 3849 3850 // The only other support type is pointer. 3851 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3852 return getDataLayout().getIntPtrType(Ty); 3853 } 3854 3855 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3856 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3857 } 3858 3859 const SCEV *ScalarEvolution::getCouldNotCompute() { 3860 return CouldNotCompute.get(); 3861 } 3862 3863 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3864 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3865 auto *SU = dyn_cast<SCEVUnknown>(S); 3866 return SU && SU->getValue() == nullptr; 3867 }); 3868 3869 return !ContainsNulls; 3870 } 3871 3872 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3873 HasRecMapType::iterator I = HasRecMap.find(S); 3874 if (I != HasRecMap.end()) 3875 return I->second; 3876 3877 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3878 HasRecMap.insert({S, FoundAddRec}); 3879 return FoundAddRec; 3880 } 3881 3882 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3883 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3884 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3885 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3886 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3887 if (!Add) 3888 return {S, nullptr}; 3889 3890 if (Add->getNumOperands() != 2) 3891 return {S, nullptr}; 3892 3893 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3894 if (!ConstOp) 3895 return {S, nullptr}; 3896 3897 return {Add->getOperand(1), ConstOp->getValue()}; 3898 } 3899 3900 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3901 /// by the value and offset from any ValueOffsetPair in the set. 3902 SetVector<ScalarEvolution::ValueOffsetPair> * 3903 ScalarEvolution::getSCEVValues(const SCEV *S) { 3904 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3905 if (SI == ExprValueMap.end()) 3906 return nullptr; 3907 #ifndef NDEBUG 3908 if (VerifySCEVMap) { 3909 // Check there is no dangling Value in the set returned. 3910 for (const auto &VE : SI->second) 3911 assert(ValueExprMap.count(VE.first)); 3912 } 3913 #endif 3914 return &SI->second; 3915 } 3916 3917 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3918 /// cannot be used separately. eraseValueFromMap should be used to remove 3919 /// V from ValueExprMap and ExprValueMap at the same time. 3920 void ScalarEvolution::eraseValueFromMap(Value *V) { 3921 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3922 if (I != ValueExprMap.end()) { 3923 const SCEV *S = I->second; 3924 // Remove {V, 0} from the set of ExprValueMap[S] 3925 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3926 SV->remove({V, nullptr}); 3927 3928 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3929 const SCEV *Stripped; 3930 ConstantInt *Offset; 3931 std::tie(Stripped, Offset) = splitAddExpr(S); 3932 if (Offset != nullptr) { 3933 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3934 SV->remove({V, Offset}); 3935 } 3936 ValueExprMap.erase(V); 3937 } 3938 } 3939 3940 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3941 /// TODO: In reality it is better to check the poison recursively 3942 /// but this is better than nothing. 3943 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3944 if (auto *I = dyn_cast<Instruction>(V)) { 3945 if (isa<OverflowingBinaryOperator>(I)) { 3946 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3947 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3948 return true; 3949 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3950 return true; 3951 } 3952 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3953 return true; 3954 } 3955 return false; 3956 } 3957 3958 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3959 /// create a new one. 3960 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3961 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3962 3963 const SCEV *S = getExistingSCEV(V); 3964 if (S == nullptr) { 3965 S = createSCEV(V); 3966 // During PHI resolution, it is possible to create two SCEVs for the same 3967 // V, so it is needed to double check whether V->S is inserted into 3968 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3969 std::pair<ValueExprMapType::iterator, bool> Pair = 3970 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3971 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3972 ExprValueMap[S].insert({V, nullptr}); 3973 3974 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3975 // ExprValueMap. 3976 const SCEV *Stripped = S; 3977 ConstantInt *Offset = nullptr; 3978 std::tie(Stripped, Offset) = splitAddExpr(S); 3979 // If stripped is SCEVUnknown, don't bother to save 3980 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3981 // increase the complexity of the expansion code. 3982 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3983 // because it may generate add/sub instead of GEP in SCEV expansion. 3984 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3985 !isa<GetElementPtrInst>(V)) 3986 ExprValueMap[Stripped].insert({V, Offset}); 3987 } 3988 } 3989 return S; 3990 } 3991 3992 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3993 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3994 3995 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3996 if (I != ValueExprMap.end()) { 3997 const SCEV *S = I->second; 3998 if (checkValidity(S)) 3999 return S; 4000 eraseValueFromMap(V); 4001 forgetMemoizedResults(S); 4002 } 4003 return nullptr; 4004 } 4005 4006 /// Return a SCEV corresponding to -V = -1*V 4007 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4008 SCEV::NoWrapFlags Flags) { 4009 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4010 return getConstant( 4011 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4012 4013 Type *Ty = V->getType(); 4014 Ty = getEffectiveSCEVType(Ty); 4015 return getMulExpr( 4016 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 4017 } 4018 4019 /// Return a SCEV corresponding to ~V = -1-V 4020 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4021 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4022 return getConstant( 4023 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4024 4025 Type *Ty = V->getType(); 4026 Ty = getEffectiveSCEVType(Ty); 4027 const SCEV *AllOnes = 4028 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 4029 return getMinusSCEV(AllOnes, V); 4030 } 4031 4032 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4033 SCEV::NoWrapFlags Flags, 4034 unsigned Depth) { 4035 // Fast path: X - X --> 0. 4036 if (LHS == RHS) 4037 return getZero(LHS->getType()); 4038 4039 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4040 // makes it so that we cannot make much use of NUW. 4041 auto AddFlags = SCEV::FlagAnyWrap; 4042 const bool RHSIsNotMinSigned = 4043 !getSignedRangeMin(RHS).isMinSignedValue(); 4044 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4045 // Let M be the minimum representable signed value. Then (-1)*RHS 4046 // signed-wraps if and only if RHS is M. That can happen even for 4047 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4048 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4049 // (-1)*RHS, we need to prove that RHS != M. 4050 // 4051 // If LHS is non-negative and we know that LHS - RHS does not 4052 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4053 // either by proving that RHS > M or that LHS >= 0. 4054 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4055 AddFlags = SCEV::FlagNSW; 4056 } 4057 } 4058 4059 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4060 // RHS is NSW and LHS >= 0. 4061 // 4062 // The difficulty here is that the NSW flag may have been proven 4063 // relative to a loop that is to be found in a recurrence in LHS and 4064 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4065 // larger scope than intended. 4066 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4067 4068 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4069 } 4070 4071 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4072 unsigned Depth) { 4073 Type *SrcTy = V->getType(); 4074 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4075 "Cannot truncate or zero extend with non-integer arguments!"); 4076 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4077 return V; // No conversion 4078 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4079 return getTruncateExpr(V, Ty, Depth); 4080 return getZeroExtendExpr(V, Ty, Depth); 4081 } 4082 4083 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4084 unsigned Depth) { 4085 Type *SrcTy = V->getType(); 4086 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4087 "Cannot truncate or zero extend with non-integer arguments!"); 4088 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4089 return V; // No conversion 4090 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4091 return getTruncateExpr(V, Ty, Depth); 4092 return getSignExtendExpr(V, Ty, Depth); 4093 } 4094 4095 const SCEV * 4096 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4097 Type *SrcTy = V->getType(); 4098 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4099 "Cannot noop or zero extend with non-integer arguments!"); 4100 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4101 "getNoopOrZeroExtend cannot truncate!"); 4102 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4103 return V; // No conversion 4104 return getZeroExtendExpr(V, Ty); 4105 } 4106 4107 const SCEV * 4108 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4109 Type *SrcTy = V->getType(); 4110 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4111 "Cannot noop or sign extend with non-integer arguments!"); 4112 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4113 "getNoopOrSignExtend cannot truncate!"); 4114 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4115 return V; // No conversion 4116 return getSignExtendExpr(V, Ty); 4117 } 4118 4119 const SCEV * 4120 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4121 Type *SrcTy = V->getType(); 4122 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4123 "Cannot noop or any extend with non-integer arguments!"); 4124 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4125 "getNoopOrAnyExtend cannot truncate!"); 4126 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4127 return V; // No conversion 4128 return getAnyExtendExpr(V, Ty); 4129 } 4130 4131 const SCEV * 4132 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4133 Type *SrcTy = V->getType(); 4134 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4135 "Cannot truncate or noop with non-integer arguments!"); 4136 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4137 "getTruncateOrNoop cannot extend!"); 4138 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4139 return V; // No conversion 4140 return getTruncateExpr(V, Ty); 4141 } 4142 4143 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4144 const SCEV *RHS) { 4145 const SCEV *PromotedLHS = LHS; 4146 const SCEV *PromotedRHS = RHS; 4147 4148 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4149 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4150 else 4151 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4152 4153 return getUMaxExpr(PromotedLHS, PromotedRHS); 4154 } 4155 4156 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4157 const SCEV *RHS) { 4158 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4159 return getUMinFromMismatchedTypes(Ops); 4160 } 4161 4162 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4163 SmallVectorImpl<const SCEV *> &Ops) { 4164 assert(!Ops.empty() && "At least one operand must be!"); 4165 // Trivial case. 4166 if (Ops.size() == 1) 4167 return Ops[0]; 4168 4169 // Find the max type first. 4170 Type *MaxType = nullptr; 4171 for (auto *S : Ops) 4172 if (MaxType) 4173 MaxType = getWiderType(MaxType, S->getType()); 4174 else 4175 MaxType = S->getType(); 4176 4177 // Extend all ops to max type. 4178 SmallVector<const SCEV *, 2> PromotedOps; 4179 for (auto *S : Ops) 4180 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4181 4182 // Generate umin. 4183 return getUMinExpr(PromotedOps); 4184 } 4185 4186 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4187 // A pointer operand may evaluate to a nonpointer expression, such as null. 4188 if (!V->getType()->isPointerTy()) 4189 return V; 4190 4191 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4192 return getPointerBase(Cast->getOperand()); 4193 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4194 const SCEV *PtrOp = nullptr; 4195 for (const SCEV *NAryOp : NAry->operands()) { 4196 if (NAryOp->getType()->isPointerTy()) { 4197 // Cannot find the base of an expression with multiple pointer operands. 4198 if (PtrOp) 4199 return V; 4200 PtrOp = NAryOp; 4201 } 4202 } 4203 if (!PtrOp) 4204 return V; 4205 return getPointerBase(PtrOp); 4206 } 4207 return V; 4208 } 4209 4210 /// Push users of the given Instruction onto the given Worklist. 4211 static void 4212 PushDefUseChildren(Instruction *I, 4213 SmallVectorImpl<Instruction *> &Worklist) { 4214 // Push the def-use children onto the Worklist stack. 4215 for (User *U : I->users()) 4216 Worklist.push_back(cast<Instruction>(U)); 4217 } 4218 4219 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4220 SmallVector<Instruction *, 16> Worklist; 4221 PushDefUseChildren(PN, Worklist); 4222 4223 SmallPtrSet<Instruction *, 8> Visited; 4224 Visited.insert(PN); 4225 while (!Worklist.empty()) { 4226 Instruction *I = Worklist.pop_back_val(); 4227 if (!Visited.insert(I).second) 4228 continue; 4229 4230 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4231 if (It != ValueExprMap.end()) { 4232 const SCEV *Old = It->second; 4233 4234 // Short-circuit the def-use traversal if the symbolic name 4235 // ceases to appear in expressions. 4236 if (Old != SymName && !hasOperand(Old, SymName)) 4237 continue; 4238 4239 // SCEVUnknown for a PHI either means that it has an unrecognized 4240 // structure, it's a PHI that's in the progress of being computed 4241 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4242 // additional loop trip count information isn't going to change anything. 4243 // In the second case, createNodeForPHI will perform the necessary 4244 // updates on its own when it gets to that point. In the third, we do 4245 // want to forget the SCEVUnknown. 4246 if (!isa<PHINode>(I) || 4247 !isa<SCEVUnknown>(Old) || 4248 (I != PN && Old == SymName)) { 4249 eraseValueFromMap(It->first); 4250 forgetMemoizedResults(Old); 4251 } 4252 } 4253 4254 PushDefUseChildren(I, Worklist); 4255 } 4256 } 4257 4258 namespace { 4259 4260 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4261 /// expression in case its Loop is L. If it is not L then 4262 /// if IgnoreOtherLoops is true then use AddRec itself 4263 /// otherwise rewrite cannot be done. 4264 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4265 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4266 public: 4267 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4268 bool IgnoreOtherLoops = true) { 4269 SCEVInitRewriter Rewriter(L, SE); 4270 const SCEV *Result = Rewriter.visit(S); 4271 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4272 return SE.getCouldNotCompute(); 4273 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4274 ? SE.getCouldNotCompute() 4275 : Result; 4276 } 4277 4278 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4279 if (!SE.isLoopInvariant(Expr, L)) 4280 SeenLoopVariantSCEVUnknown = true; 4281 return Expr; 4282 } 4283 4284 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4285 // Only re-write AddRecExprs for this loop. 4286 if (Expr->getLoop() == L) 4287 return Expr->getStart(); 4288 SeenOtherLoops = true; 4289 return Expr; 4290 } 4291 4292 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4293 4294 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4295 4296 private: 4297 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4298 : SCEVRewriteVisitor(SE), L(L) {} 4299 4300 const Loop *L; 4301 bool SeenLoopVariantSCEVUnknown = false; 4302 bool SeenOtherLoops = false; 4303 }; 4304 4305 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4306 /// increment expression in case its Loop is L. If it is not L then 4307 /// use AddRec itself. 4308 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4309 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4310 public: 4311 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4312 SCEVPostIncRewriter Rewriter(L, SE); 4313 const SCEV *Result = Rewriter.visit(S); 4314 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4315 ? SE.getCouldNotCompute() 4316 : Result; 4317 } 4318 4319 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4320 if (!SE.isLoopInvariant(Expr, L)) 4321 SeenLoopVariantSCEVUnknown = true; 4322 return Expr; 4323 } 4324 4325 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4326 // Only re-write AddRecExprs for this loop. 4327 if (Expr->getLoop() == L) 4328 return Expr->getPostIncExpr(SE); 4329 SeenOtherLoops = true; 4330 return Expr; 4331 } 4332 4333 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4334 4335 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4336 4337 private: 4338 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4339 : SCEVRewriteVisitor(SE), L(L) {} 4340 4341 const Loop *L; 4342 bool SeenLoopVariantSCEVUnknown = false; 4343 bool SeenOtherLoops = false; 4344 }; 4345 4346 /// This class evaluates the compare condition by matching it against the 4347 /// condition of loop latch. If there is a match we assume a true value 4348 /// for the condition while building SCEV nodes. 4349 class SCEVBackedgeConditionFolder 4350 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4351 public: 4352 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4353 ScalarEvolution &SE) { 4354 bool IsPosBECond = false; 4355 Value *BECond = nullptr; 4356 if (BasicBlock *Latch = L->getLoopLatch()) { 4357 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4358 if (BI && BI->isConditional()) { 4359 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4360 "Both outgoing branches should not target same header!"); 4361 BECond = BI->getCondition(); 4362 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4363 } else { 4364 return S; 4365 } 4366 } 4367 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4368 return Rewriter.visit(S); 4369 } 4370 4371 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4372 const SCEV *Result = Expr; 4373 bool InvariantF = SE.isLoopInvariant(Expr, L); 4374 4375 if (!InvariantF) { 4376 Instruction *I = cast<Instruction>(Expr->getValue()); 4377 switch (I->getOpcode()) { 4378 case Instruction::Select: { 4379 SelectInst *SI = cast<SelectInst>(I); 4380 Optional<const SCEV *> Res = 4381 compareWithBackedgeCondition(SI->getCondition()); 4382 if (Res.hasValue()) { 4383 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4384 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4385 } 4386 break; 4387 } 4388 default: { 4389 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4390 if (Res.hasValue()) 4391 Result = Res.getValue(); 4392 break; 4393 } 4394 } 4395 } 4396 return Result; 4397 } 4398 4399 private: 4400 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4401 bool IsPosBECond, ScalarEvolution &SE) 4402 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4403 IsPositiveBECond(IsPosBECond) {} 4404 4405 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4406 4407 const Loop *L; 4408 /// Loop back condition. 4409 Value *BackedgeCond = nullptr; 4410 /// Set to true if loop back is on positive branch condition. 4411 bool IsPositiveBECond; 4412 }; 4413 4414 Optional<const SCEV *> 4415 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4416 4417 // If value matches the backedge condition for loop latch, 4418 // then return a constant evolution node based on loopback 4419 // branch taken. 4420 if (BackedgeCond == IC) 4421 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4422 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4423 return None; 4424 } 4425 4426 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4427 public: 4428 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4429 ScalarEvolution &SE) { 4430 SCEVShiftRewriter Rewriter(L, SE); 4431 const SCEV *Result = Rewriter.visit(S); 4432 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4433 } 4434 4435 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4436 // Only allow AddRecExprs for this loop. 4437 if (!SE.isLoopInvariant(Expr, L)) 4438 Valid = false; 4439 return Expr; 4440 } 4441 4442 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4443 if (Expr->getLoop() == L && Expr->isAffine()) 4444 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4445 Valid = false; 4446 return Expr; 4447 } 4448 4449 bool isValid() { return Valid; } 4450 4451 private: 4452 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4453 : SCEVRewriteVisitor(SE), L(L) {} 4454 4455 const Loop *L; 4456 bool Valid = true; 4457 }; 4458 4459 } // end anonymous namespace 4460 4461 SCEV::NoWrapFlags 4462 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4463 if (!AR->isAffine()) 4464 return SCEV::FlagAnyWrap; 4465 4466 using OBO = OverflowingBinaryOperator; 4467 4468 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4469 4470 if (!AR->hasNoSignedWrap()) { 4471 ConstantRange AddRecRange = getSignedRange(AR); 4472 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4473 4474 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4475 Instruction::Add, IncRange, OBO::NoSignedWrap); 4476 if (NSWRegion.contains(AddRecRange)) 4477 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4478 } 4479 4480 if (!AR->hasNoUnsignedWrap()) { 4481 ConstantRange AddRecRange = getUnsignedRange(AR); 4482 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4483 4484 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4485 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4486 if (NUWRegion.contains(AddRecRange)) 4487 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4488 } 4489 4490 return Result; 4491 } 4492 4493 namespace { 4494 4495 /// Represents an abstract binary operation. This may exist as a 4496 /// normal instruction or constant expression, or may have been 4497 /// derived from an expression tree. 4498 struct BinaryOp { 4499 unsigned Opcode; 4500 Value *LHS; 4501 Value *RHS; 4502 bool IsNSW = false; 4503 bool IsNUW = false; 4504 4505 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4506 /// constant expression. 4507 Operator *Op = nullptr; 4508 4509 explicit BinaryOp(Operator *Op) 4510 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4511 Op(Op) { 4512 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4513 IsNSW = OBO->hasNoSignedWrap(); 4514 IsNUW = OBO->hasNoUnsignedWrap(); 4515 } 4516 } 4517 4518 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4519 bool IsNUW = false) 4520 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4521 }; 4522 4523 } // end anonymous namespace 4524 4525 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4526 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4527 auto *Op = dyn_cast<Operator>(V); 4528 if (!Op) 4529 return None; 4530 4531 // Implementation detail: all the cleverness here should happen without 4532 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4533 // SCEV expressions when possible, and we should not break that. 4534 4535 switch (Op->getOpcode()) { 4536 case Instruction::Add: 4537 case Instruction::Sub: 4538 case Instruction::Mul: 4539 case Instruction::UDiv: 4540 case Instruction::URem: 4541 case Instruction::And: 4542 case Instruction::Or: 4543 case Instruction::AShr: 4544 case Instruction::Shl: 4545 return BinaryOp(Op); 4546 4547 case Instruction::Xor: 4548 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4549 // If the RHS of the xor is a signmask, then this is just an add. 4550 // Instcombine turns add of signmask into xor as a strength reduction step. 4551 if (RHSC->getValue().isSignMask()) 4552 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4553 return BinaryOp(Op); 4554 4555 case Instruction::LShr: 4556 // Turn logical shift right of a constant into a unsigned divide. 4557 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4558 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4559 4560 // If the shift count is not less than the bitwidth, the result of 4561 // the shift is undefined. Don't try to analyze it, because the 4562 // resolution chosen here may differ from the resolution chosen in 4563 // other parts of the compiler. 4564 if (SA->getValue().ult(BitWidth)) { 4565 Constant *X = 4566 ConstantInt::get(SA->getContext(), 4567 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4568 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4569 } 4570 } 4571 return BinaryOp(Op); 4572 4573 case Instruction::ExtractValue: { 4574 auto *EVI = cast<ExtractValueInst>(Op); 4575 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4576 break; 4577 4578 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 4579 if (!CI) 4580 break; 4581 4582 if (auto *F = CI->getCalledFunction()) 4583 switch (F->getIntrinsicID()) { 4584 case Intrinsic::sadd_with_overflow: 4585 case Intrinsic::uadd_with_overflow: 4586 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4587 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4588 CI->getArgOperand(1)); 4589 4590 // Now that we know that all uses of the arithmetic-result component of 4591 // CI are guarded by the overflow check, we can go ahead and pretend 4592 // that the arithmetic is non-overflowing. 4593 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 4594 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4595 CI->getArgOperand(1), /* IsNSW = */ true, 4596 /* IsNUW = */ false); 4597 else 4598 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4599 CI->getArgOperand(1), /* IsNSW = */ false, 4600 /* IsNUW*/ true); 4601 case Intrinsic::ssub_with_overflow: 4602 case Intrinsic::usub_with_overflow: 4603 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4604 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4605 CI->getArgOperand(1)); 4606 4607 // The same reasoning as sadd/uadd above. 4608 if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow) 4609 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4610 CI->getArgOperand(1), /* IsNSW = */ true, 4611 /* IsNUW = */ false); 4612 else 4613 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4614 CI->getArgOperand(1), /* IsNSW = */ false, 4615 /* IsNUW = */ true); 4616 case Intrinsic::smul_with_overflow: 4617 case Intrinsic::umul_with_overflow: 4618 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4619 CI->getArgOperand(1)); 4620 default: 4621 break; 4622 } 4623 break; 4624 } 4625 4626 default: 4627 break; 4628 } 4629 4630 return None; 4631 } 4632 4633 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4634 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4635 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4636 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4637 /// follows one of the following patterns: 4638 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4639 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4640 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4641 /// we return the type of the truncation operation, and indicate whether the 4642 /// truncated type should be treated as signed/unsigned by setting 4643 /// \p Signed to true/false, respectively. 4644 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4645 bool &Signed, ScalarEvolution &SE) { 4646 // The case where Op == SymbolicPHI (that is, with no type conversions on 4647 // the way) is handled by the regular add recurrence creating logic and 4648 // would have already been triggered in createAddRecForPHI. Reaching it here 4649 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4650 // because one of the other operands of the SCEVAddExpr updating this PHI is 4651 // not invariant). 4652 // 4653 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4654 // this case predicates that allow us to prove that Op == SymbolicPHI will 4655 // be added. 4656 if (Op == SymbolicPHI) 4657 return nullptr; 4658 4659 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4660 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4661 if (SourceBits != NewBits) 4662 return nullptr; 4663 4664 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4665 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4666 if (!SExt && !ZExt) 4667 return nullptr; 4668 const SCEVTruncateExpr *Trunc = 4669 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4670 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4671 if (!Trunc) 4672 return nullptr; 4673 const SCEV *X = Trunc->getOperand(); 4674 if (X != SymbolicPHI) 4675 return nullptr; 4676 Signed = SExt != nullptr; 4677 return Trunc->getType(); 4678 } 4679 4680 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4681 if (!PN->getType()->isIntegerTy()) 4682 return nullptr; 4683 const Loop *L = LI.getLoopFor(PN->getParent()); 4684 if (!L || L->getHeader() != PN->getParent()) 4685 return nullptr; 4686 return L; 4687 } 4688 4689 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4690 // computation that updates the phi follows the following pattern: 4691 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4692 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4693 // If so, try to see if it can be rewritten as an AddRecExpr under some 4694 // Predicates. If successful, return them as a pair. Also cache the results 4695 // of the analysis. 4696 // 4697 // Example usage scenario: 4698 // Say the Rewriter is called for the following SCEV: 4699 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4700 // where: 4701 // %X = phi i64 (%Start, %BEValue) 4702 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4703 // and call this function with %SymbolicPHI = %X. 4704 // 4705 // The analysis will find that the value coming around the backedge has 4706 // the following SCEV: 4707 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4708 // Upon concluding that this matches the desired pattern, the function 4709 // will return the pair {NewAddRec, SmallPredsVec} where: 4710 // NewAddRec = {%Start,+,%Step} 4711 // SmallPredsVec = {P1, P2, P3} as follows: 4712 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4713 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4714 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4715 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4716 // under the predicates {P1,P2,P3}. 4717 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4718 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4719 // 4720 // TODO's: 4721 // 4722 // 1) Extend the Induction descriptor to also support inductions that involve 4723 // casts: When needed (namely, when we are called in the context of the 4724 // vectorizer induction analysis), a Set of cast instructions will be 4725 // populated by this method, and provided back to isInductionPHI. This is 4726 // needed to allow the vectorizer to properly record them to be ignored by 4727 // the cost model and to avoid vectorizing them (otherwise these casts, 4728 // which are redundant under the runtime overflow checks, will be 4729 // vectorized, which can be costly). 4730 // 4731 // 2) Support additional induction/PHISCEV patterns: We also want to support 4732 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4733 // after the induction update operation (the induction increment): 4734 // 4735 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4736 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4737 // 4738 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4739 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4740 // 4741 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4742 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4743 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4744 SmallVector<const SCEVPredicate *, 3> Predicates; 4745 4746 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4747 // return an AddRec expression under some predicate. 4748 4749 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4750 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4751 assert(L && "Expecting an integer loop header phi"); 4752 4753 // The loop may have multiple entrances or multiple exits; we can analyze 4754 // this phi as an addrec if it has a unique entry value and a unique 4755 // backedge value. 4756 Value *BEValueV = nullptr, *StartValueV = nullptr; 4757 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4758 Value *V = PN->getIncomingValue(i); 4759 if (L->contains(PN->getIncomingBlock(i))) { 4760 if (!BEValueV) { 4761 BEValueV = V; 4762 } else if (BEValueV != V) { 4763 BEValueV = nullptr; 4764 break; 4765 } 4766 } else if (!StartValueV) { 4767 StartValueV = V; 4768 } else if (StartValueV != V) { 4769 StartValueV = nullptr; 4770 break; 4771 } 4772 } 4773 if (!BEValueV || !StartValueV) 4774 return None; 4775 4776 const SCEV *BEValue = getSCEV(BEValueV); 4777 4778 // If the value coming around the backedge is an add with the symbolic 4779 // value we just inserted, possibly with casts that we can ignore under 4780 // an appropriate runtime guard, then we found a simple induction variable! 4781 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4782 if (!Add) 4783 return None; 4784 4785 // If there is a single occurrence of the symbolic value, possibly 4786 // casted, replace it with a recurrence. 4787 unsigned FoundIndex = Add->getNumOperands(); 4788 Type *TruncTy = nullptr; 4789 bool Signed; 4790 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4791 if ((TruncTy = 4792 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4793 if (FoundIndex == e) { 4794 FoundIndex = i; 4795 break; 4796 } 4797 4798 if (FoundIndex == Add->getNumOperands()) 4799 return None; 4800 4801 // Create an add with everything but the specified operand. 4802 SmallVector<const SCEV *, 8> Ops; 4803 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4804 if (i != FoundIndex) 4805 Ops.push_back(Add->getOperand(i)); 4806 const SCEV *Accum = getAddExpr(Ops); 4807 4808 // The runtime checks will not be valid if the step amount is 4809 // varying inside the loop. 4810 if (!isLoopInvariant(Accum, L)) 4811 return None; 4812 4813 // *** Part2: Create the predicates 4814 4815 // Analysis was successful: we have a phi-with-cast pattern for which we 4816 // can return an AddRec expression under the following predicates: 4817 // 4818 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4819 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4820 // P2: An Equal predicate that guarantees that 4821 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4822 // P3: An Equal predicate that guarantees that 4823 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4824 // 4825 // As we next prove, the above predicates guarantee that: 4826 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4827 // 4828 // 4829 // More formally, we want to prove that: 4830 // Expr(i+1) = Start + (i+1) * Accum 4831 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4832 // 4833 // Given that: 4834 // 1) Expr(0) = Start 4835 // 2) Expr(1) = Start + Accum 4836 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4837 // 3) Induction hypothesis (step i): 4838 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4839 // 4840 // Proof: 4841 // Expr(i+1) = 4842 // = Start + (i+1)*Accum 4843 // = (Start + i*Accum) + Accum 4844 // = Expr(i) + Accum 4845 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4846 // :: from step i 4847 // 4848 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4849 // 4850 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4851 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4852 // + Accum :: from P3 4853 // 4854 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4855 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4856 // 4857 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4858 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4859 // 4860 // By induction, the same applies to all iterations 1<=i<n: 4861 // 4862 4863 // Create a truncated addrec for which we will add a no overflow check (P1). 4864 const SCEV *StartVal = getSCEV(StartValueV); 4865 const SCEV *PHISCEV = 4866 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4867 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4868 4869 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4870 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4871 // will be constant. 4872 // 4873 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4874 // add P1. 4875 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4876 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4877 Signed ? SCEVWrapPredicate::IncrementNSSW 4878 : SCEVWrapPredicate::IncrementNUSW; 4879 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4880 Predicates.push_back(AddRecPred); 4881 } 4882 4883 // Create the Equal Predicates P2,P3: 4884 4885 // It is possible that the predicates P2 and/or P3 are computable at 4886 // compile time due to StartVal and/or Accum being constants. 4887 // If either one is, then we can check that now and escape if either P2 4888 // or P3 is false. 4889 4890 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4891 // for each of StartVal and Accum 4892 auto getExtendedExpr = [&](const SCEV *Expr, 4893 bool CreateSignExtend) -> const SCEV * { 4894 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4895 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4896 const SCEV *ExtendedExpr = 4897 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4898 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4899 return ExtendedExpr; 4900 }; 4901 4902 // Given: 4903 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4904 // = getExtendedExpr(Expr) 4905 // Determine whether the predicate P: Expr == ExtendedExpr 4906 // is known to be false at compile time 4907 auto PredIsKnownFalse = [&](const SCEV *Expr, 4908 const SCEV *ExtendedExpr) -> bool { 4909 return Expr != ExtendedExpr && 4910 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4911 }; 4912 4913 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4914 if (PredIsKnownFalse(StartVal, StartExtended)) { 4915 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4916 return None; 4917 } 4918 4919 // The Step is always Signed (because the overflow checks are either 4920 // NSSW or NUSW) 4921 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4922 if (PredIsKnownFalse(Accum, AccumExtended)) { 4923 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4924 return None; 4925 } 4926 4927 auto AppendPredicate = [&](const SCEV *Expr, 4928 const SCEV *ExtendedExpr) -> void { 4929 if (Expr != ExtendedExpr && 4930 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4931 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4932 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4933 Predicates.push_back(Pred); 4934 } 4935 }; 4936 4937 AppendPredicate(StartVal, StartExtended); 4938 AppendPredicate(Accum, AccumExtended); 4939 4940 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4941 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4942 // into NewAR if it will also add the runtime overflow checks specified in 4943 // Predicates. 4944 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4945 4946 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4947 std::make_pair(NewAR, Predicates); 4948 // Remember the result of the analysis for this SCEV at this locayyytion. 4949 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4950 return PredRewrite; 4951 } 4952 4953 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4954 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4955 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4956 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4957 if (!L) 4958 return None; 4959 4960 // Check to see if we already analyzed this PHI. 4961 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4962 if (I != PredicatedSCEVRewrites.end()) { 4963 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4964 I->second; 4965 // Analysis was done before and failed to create an AddRec: 4966 if (Rewrite.first == SymbolicPHI) 4967 return None; 4968 // Analysis was done before and succeeded to create an AddRec under 4969 // a predicate: 4970 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4971 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4972 return Rewrite; 4973 } 4974 4975 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4976 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4977 4978 // Record in the cache that the analysis failed 4979 if (!Rewrite) { 4980 SmallVector<const SCEVPredicate *, 3> Predicates; 4981 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4982 return None; 4983 } 4984 4985 return Rewrite; 4986 } 4987 4988 // FIXME: This utility is currently required because the Rewriter currently 4989 // does not rewrite this expression: 4990 // {0, +, (sext ix (trunc iy to ix) to iy)} 4991 // into {0, +, %step}, 4992 // even when the following Equal predicate exists: 4993 // "%step == (sext ix (trunc iy to ix) to iy)". 4994 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4995 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4996 if (AR1 == AR2) 4997 return true; 4998 4999 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5000 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 5001 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 5002 return false; 5003 return true; 5004 }; 5005 5006 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5007 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5008 return false; 5009 return true; 5010 } 5011 5012 /// A helper function for createAddRecFromPHI to handle simple cases. 5013 /// 5014 /// This function tries to find an AddRec expression for the simplest (yet most 5015 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5016 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5017 /// technique for finding the AddRec expression. 5018 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5019 Value *BEValueV, 5020 Value *StartValueV) { 5021 const Loop *L = LI.getLoopFor(PN->getParent()); 5022 assert(L && L->getHeader() == PN->getParent()); 5023 assert(BEValueV && StartValueV); 5024 5025 auto BO = MatchBinaryOp(BEValueV, DT); 5026 if (!BO) 5027 return nullptr; 5028 5029 if (BO->Opcode != Instruction::Add) 5030 return nullptr; 5031 5032 const SCEV *Accum = nullptr; 5033 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5034 Accum = getSCEV(BO->RHS); 5035 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5036 Accum = getSCEV(BO->LHS); 5037 5038 if (!Accum) 5039 return nullptr; 5040 5041 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5042 if (BO->IsNUW) 5043 Flags = setFlags(Flags, SCEV::FlagNUW); 5044 if (BO->IsNSW) 5045 Flags = setFlags(Flags, SCEV::FlagNSW); 5046 5047 const SCEV *StartVal = getSCEV(StartValueV); 5048 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5049 5050 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5051 5052 // We can add Flags to the post-inc expression only if we 5053 // know that it is *undefined behavior* for BEValueV to 5054 // overflow. 5055 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5056 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5057 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5058 5059 return PHISCEV; 5060 } 5061 5062 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5063 const Loop *L = LI.getLoopFor(PN->getParent()); 5064 if (!L || L->getHeader() != PN->getParent()) 5065 return nullptr; 5066 5067 // The loop may have multiple entrances or multiple exits; we can analyze 5068 // this phi as an addrec if it has a unique entry value and a unique 5069 // backedge value. 5070 Value *BEValueV = nullptr, *StartValueV = nullptr; 5071 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5072 Value *V = PN->getIncomingValue(i); 5073 if (L->contains(PN->getIncomingBlock(i))) { 5074 if (!BEValueV) { 5075 BEValueV = V; 5076 } else if (BEValueV != V) { 5077 BEValueV = nullptr; 5078 break; 5079 } 5080 } else if (!StartValueV) { 5081 StartValueV = V; 5082 } else if (StartValueV != V) { 5083 StartValueV = nullptr; 5084 break; 5085 } 5086 } 5087 if (!BEValueV || !StartValueV) 5088 return nullptr; 5089 5090 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5091 "PHI node already processed?"); 5092 5093 // First, try to find AddRec expression without creating a fictituos symbolic 5094 // value for PN. 5095 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5096 return S; 5097 5098 // Handle PHI node value symbolically. 5099 const SCEV *SymbolicName = getUnknown(PN); 5100 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5101 5102 // Using this symbolic name for the PHI, analyze the value coming around 5103 // the back-edge. 5104 const SCEV *BEValue = getSCEV(BEValueV); 5105 5106 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5107 // has a special value for the first iteration of the loop. 5108 5109 // If the value coming around the backedge is an add with the symbolic 5110 // value we just inserted, then we found a simple induction variable! 5111 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5112 // If there is a single occurrence of the symbolic value, replace it 5113 // with a recurrence. 5114 unsigned FoundIndex = Add->getNumOperands(); 5115 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5116 if (Add->getOperand(i) == SymbolicName) 5117 if (FoundIndex == e) { 5118 FoundIndex = i; 5119 break; 5120 } 5121 5122 if (FoundIndex != Add->getNumOperands()) { 5123 // Create an add with everything but the specified operand. 5124 SmallVector<const SCEV *, 8> Ops; 5125 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5126 if (i != FoundIndex) 5127 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5128 L, *this)); 5129 const SCEV *Accum = getAddExpr(Ops); 5130 5131 // This is not a valid addrec if the step amount is varying each 5132 // loop iteration, but is not itself an addrec in this loop. 5133 if (isLoopInvariant(Accum, L) || 5134 (isa<SCEVAddRecExpr>(Accum) && 5135 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5136 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5137 5138 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5139 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5140 if (BO->IsNUW) 5141 Flags = setFlags(Flags, SCEV::FlagNUW); 5142 if (BO->IsNSW) 5143 Flags = setFlags(Flags, SCEV::FlagNSW); 5144 } 5145 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5146 // If the increment is an inbounds GEP, then we know the address 5147 // space cannot be wrapped around. We cannot make any guarantee 5148 // about signed or unsigned overflow because pointers are 5149 // unsigned but we may have a negative index from the base 5150 // pointer. We can guarantee that no unsigned wrap occurs if the 5151 // indices form a positive value. 5152 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5153 Flags = setFlags(Flags, SCEV::FlagNW); 5154 5155 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5156 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5157 Flags = setFlags(Flags, SCEV::FlagNUW); 5158 } 5159 5160 // We cannot transfer nuw and nsw flags from subtraction 5161 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5162 // for instance. 5163 } 5164 5165 const SCEV *StartVal = getSCEV(StartValueV); 5166 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5167 5168 // Okay, for the entire analysis of this edge we assumed the PHI 5169 // to be symbolic. We now need to go back and purge all of the 5170 // entries for the scalars that use the symbolic expression. 5171 forgetSymbolicName(PN, SymbolicName); 5172 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5173 5174 // We can add Flags to the post-inc expression only if we 5175 // know that it is *undefined behavior* for BEValueV to 5176 // overflow. 5177 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5178 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5179 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5180 5181 return PHISCEV; 5182 } 5183 } 5184 } else { 5185 // Otherwise, this could be a loop like this: 5186 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5187 // In this case, j = {1,+,1} and BEValue is j. 5188 // Because the other in-value of i (0) fits the evolution of BEValue 5189 // i really is an addrec evolution. 5190 // 5191 // We can generalize this saying that i is the shifted value of BEValue 5192 // by one iteration: 5193 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5194 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5195 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5196 if (Shifted != getCouldNotCompute() && 5197 Start != getCouldNotCompute()) { 5198 const SCEV *StartVal = getSCEV(StartValueV); 5199 if (Start == StartVal) { 5200 // Okay, for the entire analysis of this edge we assumed the PHI 5201 // to be symbolic. We now need to go back and purge all of the 5202 // entries for the scalars that use the symbolic expression. 5203 forgetSymbolicName(PN, SymbolicName); 5204 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5205 return Shifted; 5206 } 5207 } 5208 } 5209 5210 // Remove the temporary PHI node SCEV that has been inserted while intending 5211 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5212 // as it will prevent later (possibly simpler) SCEV expressions to be added 5213 // to the ValueExprMap. 5214 eraseValueFromMap(PN); 5215 5216 return nullptr; 5217 } 5218 5219 // Checks if the SCEV S is available at BB. S is considered available at BB 5220 // if S can be materialized at BB without introducing a fault. 5221 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5222 BasicBlock *BB) { 5223 struct CheckAvailable { 5224 bool TraversalDone = false; 5225 bool Available = true; 5226 5227 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5228 BasicBlock *BB = nullptr; 5229 DominatorTree &DT; 5230 5231 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5232 : L(L), BB(BB), DT(DT) {} 5233 5234 bool setUnavailable() { 5235 TraversalDone = true; 5236 Available = false; 5237 return false; 5238 } 5239 5240 bool follow(const SCEV *S) { 5241 switch (S->getSCEVType()) { 5242 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5243 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5244 // These expressions are available if their operand(s) is/are. 5245 return true; 5246 5247 case scAddRecExpr: { 5248 // We allow add recurrences that are on the loop BB is in, or some 5249 // outer loop. This guarantees availability because the value of the 5250 // add recurrence at BB is simply the "current" value of the induction 5251 // variable. We can relax this in the future; for instance an add 5252 // recurrence on a sibling dominating loop is also available at BB. 5253 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5254 if (L && (ARLoop == L || ARLoop->contains(L))) 5255 return true; 5256 5257 return setUnavailable(); 5258 } 5259 5260 case scUnknown: { 5261 // For SCEVUnknown, we check for simple dominance. 5262 const auto *SU = cast<SCEVUnknown>(S); 5263 Value *V = SU->getValue(); 5264 5265 if (isa<Argument>(V)) 5266 return false; 5267 5268 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5269 return false; 5270 5271 return setUnavailable(); 5272 } 5273 5274 case scUDivExpr: 5275 case scCouldNotCompute: 5276 // We do not try to smart about these at all. 5277 return setUnavailable(); 5278 } 5279 llvm_unreachable("switch should be fully covered!"); 5280 } 5281 5282 bool isDone() { return TraversalDone; } 5283 }; 5284 5285 CheckAvailable CA(L, BB, DT); 5286 SCEVTraversal<CheckAvailable> ST(CA); 5287 5288 ST.visitAll(S); 5289 return CA.Available; 5290 } 5291 5292 // Try to match a control flow sequence that branches out at BI and merges back 5293 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5294 // match. 5295 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5296 Value *&C, Value *&LHS, Value *&RHS) { 5297 C = BI->getCondition(); 5298 5299 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5300 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5301 5302 if (!LeftEdge.isSingleEdge()) 5303 return false; 5304 5305 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5306 5307 Use &LeftUse = Merge->getOperandUse(0); 5308 Use &RightUse = Merge->getOperandUse(1); 5309 5310 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5311 LHS = LeftUse; 5312 RHS = RightUse; 5313 return true; 5314 } 5315 5316 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5317 LHS = RightUse; 5318 RHS = LeftUse; 5319 return true; 5320 } 5321 5322 return false; 5323 } 5324 5325 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5326 auto IsReachable = 5327 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5328 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5329 const Loop *L = LI.getLoopFor(PN->getParent()); 5330 5331 // We don't want to break LCSSA, even in a SCEV expression tree. 5332 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5333 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5334 return nullptr; 5335 5336 // Try to match 5337 // 5338 // br %cond, label %left, label %right 5339 // left: 5340 // br label %merge 5341 // right: 5342 // br label %merge 5343 // merge: 5344 // V = phi [ %x, %left ], [ %y, %right ] 5345 // 5346 // as "select %cond, %x, %y" 5347 5348 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5349 assert(IDom && "At least the entry block should dominate PN"); 5350 5351 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5352 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5353 5354 if (BI && BI->isConditional() && 5355 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5356 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5357 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5358 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5359 } 5360 5361 return nullptr; 5362 } 5363 5364 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5365 if (const SCEV *S = createAddRecFromPHI(PN)) 5366 return S; 5367 5368 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5369 return S; 5370 5371 // If the PHI has a single incoming value, follow that value, unless the 5372 // PHI's incoming blocks are in a different loop, in which case doing so 5373 // risks breaking LCSSA form. Instcombine would normally zap these, but 5374 // it doesn't have DominatorTree information, so it may miss cases. 5375 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5376 if (LI.replacementPreservesLCSSAForm(PN, V)) 5377 return getSCEV(V); 5378 5379 // If it's not a loop phi, we can't handle it yet. 5380 return getUnknown(PN); 5381 } 5382 5383 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5384 Value *Cond, 5385 Value *TrueVal, 5386 Value *FalseVal) { 5387 // Handle "constant" branch or select. This can occur for instance when a 5388 // loop pass transforms an inner loop and moves on to process the outer loop. 5389 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5390 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5391 5392 // Try to match some simple smax or umax patterns. 5393 auto *ICI = dyn_cast<ICmpInst>(Cond); 5394 if (!ICI) 5395 return getUnknown(I); 5396 5397 Value *LHS = ICI->getOperand(0); 5398 Value *RHS = ICI->getOperand(1); 5399 5400 switch (ICI->getPredicate()) { 5401 case ICmpInst::ICMP_SLT: 5402 case ICmpInst::ICMP_SLE: 5403 std::swap(LHS, RHS); 5404 LLVM_FALLTHROUGH; 5405 case ICmpInst::ICMP_SGT: 5406 case ICmpInst::ICMP_SGE: 5407 // a >s b ? a+x : b+x -> smax(a, b)+x 5408 // a >s b ? b+x : a+x -> smin(a, b)+x 5409 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5410 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5411 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5412 const SCEV *LA = getSCEV(TrueVal); 5413 const SCEV *RA = getSCEV(FalseVal); 5414 const SCEV *LDiff = getMinusSCEV(LA, LS); 5415 const SCEV *RDiff = getMinusSCEV(RA, RS); 5416 if (LDiff == RDiff) 5417 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5418 LDiff = getMinusSCEV(LA, RS); 5419 RDiff = getMinusSCEV(RA, LS); 5420 if (LDiff == RDiff) 5421 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5422 } 5423 break; 5424 case ICmpInst::ICMP_ULT: 5425 case ICmpInst::ICMP_ULE: 5426 std::swap(LHS, RHS); 5427 LLVM_FALLTHROUGH; 5428 case ICmpInst::ICMP_UGT: 5429 case ICmpInst::ICMP_UGE: 5430 // a >u b ? a+x : b+x -> umax(a, b)+x 5431 // a >u b ? b+x : a+x -> umin(a, b)+x 5432 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5433 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5434 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5435 const SCEV *LA = getSCEV(TrueVal); 5436 const SCEV *RA = getSCEV(FalseVal); 5437 const SCEV *LDiff = getMinusSCEV(LA, LS); 5438 const SCEV *RDiff = getMinusSCEV(RA, RS); 5439 if (LDiff == RDiff) 5440 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5441 LDiff = getMinusSCEV(LA, RS); 5442 RDiff = getMinusSCEV(RA, LS); 5443 if (LDiff == RDiff) 5444 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5445 } 5446 break; 5447 case ICmpInst::ICMP_NE: 5448 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5449 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5450 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5451 const SCEV *One = getOne(I->getType()); 5452 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5453 const SCEV *LA = getSCEV(TrueVal); 5454 const SCEV *RA = getSCEV(FalseVal); 5455 const SCEV *LDiff = getMinusSCEV(LA, LS); 5456 const SCEV *RDiff = getMinusSCEV(RA, One); 5457 if (LDiff == RDiff) 5458 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5459 } 5460 break; 5461 case ICmpInst::ICMP_EQ: 5462 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5463 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5464 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5465 const SCEV *One = getOne(I->getType()); 5466 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5467 const SCEV *LA = getSCEV(TrueVal); 5468 const SCEV *RA = getSCEV(FalseVal); 5469 const SCEV *LDiff = getMinusSCEV(LA, One); 5470 const SCEV *RDiff = getMinusSCEV(RA, LS); 5471 if (LDiff == RDiff) 5472 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5473 } 5474 break; 5475 default: 5476 break; 5477 } 5478 5479 return getUnknown(I); 5480 } 5481 5482 /// Expand GEP instructions into add and multiply operations. This allows them 5483 /// to be analyzed by regular SCEV code. 5484 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5485 // Don't attempt to analyze GEPs over unsized objects. 5486 if (!GEP->getSourceElementType()->isSized()) 5487 return getUnknown(GEP); 5488 5489 SmallVector<const SCEV *, 4> IndexExprs; 5490 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5491 IndexExprs.push_back(getSCEV(*Index)); 5492 return getGEPExpr(GEP, IndexExprs); 5493 } 5494 5495 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5496 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5497 return C->getAPInt().countTrailingZeros(); 5498 5499 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5500 return std::min(GetMinTrailingZeros(T->getOperand()), 5501 (uint32_t)getTypeSizeInBits(T->getType())); 5502 5503 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5504 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5505 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5506 ? getTypeSizeInBits(E->getType()) 5507 : OpRes; 5508 } 5509 5510 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5511 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5512 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5513 ? getTypeSizeInBits(E->getType()) 5514 : OpRes; 5515 } 5516 5517 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5518 // The result is the min of all operands results. 5519 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5520 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5521 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5522 return MinOpRes; 5523 } 5524 5525 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5526 // The result is the sum of all operands results. 5527 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5528 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5529 for (unsigned i = 1, e = M->getNumOperands(); 5530 SumOpRes != BitWidth && i != e; ++i) 5531 SumOpRes = 5532 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5533 return SumOpRes; 5534 } 5535 5536 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5537 // The result is the min of all operands results. 5538 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5539 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5540 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5541 return MinOpRes; 5542 } 5543 5544 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5545 // The result is the min of all operands results. 5546 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5547 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5548 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5549 return MinOpRes; 5550 } 5551 5552 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5553 // The result is the min of all operands results. 5554 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5555 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5556 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5557 return MinOpRes; 5558 } 5559 5560 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5561 // For a SCEVUnknown, ask ValueTracking. 5562 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5563 return Known.countMinTrailingZeros(); 5564 } 5565 5566 // SCEVUDivExpr 5567 return 0; 5568 } 5569 5570 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5571 auto I = MinTrailingZerosCache.find(S); 5572 if (I != MinTrailingZerosCache.end()) 5573 return I->second; 5574 5575 uint32_t Result = GetMinTrailingZerosImpl(S); 5576 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5577 assert(InsertPair.second && "Should insert a new key"); 5578 return InsertPair.first->second; 5579 } 5580 5581 /// Helper method to assign a range to V from metadata present in the IR. 5582 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5583 if (Instruction *I = dyn_cast<Instruction>(V)) 5584 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5585 return getConstantRangeFromMetadata(*MD); 5586 5587 return None; 5588 } 5589 5590 /// Determine the range for a particular SCEV. If SignHint is 5591 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5592 /// with a "cleaner" unsigned (resp. signed) representation. 5593 const ConstantRange & 5594 ScalarEvolution::getRangeRef(const SCEV *S, 5595 ScalarEvolution::RangeSignHint SignHint) { 5596 DenseMap<const SCEV *, ConstantRange> &Cache = 5597 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5598 : SignedRanges; 5599 5600 // See if we've computed this range already. 5601 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5602 if (I != Cache.end()) 5603 return I->second; 5604 5605 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5606 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5607 5608 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5609 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5610 5611 // If the value has known zeros, the maximum value will have those known zeros 5612 // as well. 5613 uint32_t TZ = GetMinTrailingZeros(S); 5614 if (TZ != 0) { 5615 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5616 ConservativeResult = 5617 ConstantRange(APInt::getMinValue(BitWidth), 5618 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5619 else 5620 ConservativeResult = ConstantRange( 5621 APInt::getSignedMinValue(BitWidth), 5622 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5623 } 5624 5625 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5626 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5627 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5628 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5629 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 5630 } 5631 5632 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5633 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5634 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5635 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5636 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 5637 } 5638 5639 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5640 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5641 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5642 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5643 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 5644 } 5645 5646 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5647 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5648 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5649 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5650 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 5651 } 5652 5653 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5654 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5655 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5656 return setRange(UDiv, SignHint, 5657 ConservativeResult.intersectWith(X.udiv(Y))); 5658 } 5659 5660 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5661 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5662 return setRange(ZExt, SignHint, 5663 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 5664 } 5665 5666 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5667 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5668 return setRange(SExt, SignHint, 5669 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 5670 } 5671 5672 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5673 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5674 return setRange(Trunc, SignHint, 5675 ConservativeResult.intersectWith(X.truncate(BitWidth))); 5676 } 5677 5678 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5679 // If there's no unsigned wrap, the value will never be less than its 5680 // initial value. 5681 if (AddRec->hasNoUnsignedWrap()) 5682 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5683 if (!C->getValue()->isZero()) 5684 ConservativeResult = ConservativeResult.intersectWith( 5685 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 5686 5687 // If there's no signed wrap, and all the operands have the same sign or 5688 // zero, the value won't ever change sign. 5689 if (AddRec->hasNoSignedWrap()) { 5690 bool AllNonNeg = true; 5691 bool AllNonPos = true; 5692 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5693 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5694 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5695 } 5696 if (AllNonNeg) 5697 ConservativeResult = ConservativeResult.intersectWith( 5698 ConstantRange(APInt(BitWidth, 0), 5699 APInt::getSignedMinValue(BitWidth))); 5700 else if (AllNonPos) 5701 ConservativeResult = ConservativeResult.intersectWith( 5702 ConstantRange(APInt::getSignedMinValue(BitWidth), 5703 APInt(BitWidth, 1))); 5704 } 5705 5706 // TODO: non-affine addrec 5707 if (AddRec->isAffine()) { 5708 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 5709 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5710 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5711 auto RangeFromAffine = getRangeForAffineAR( 5712 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5713 BitWidth); 5714 if (!RangeFromAffine.isFullSet()) 5715 ConservativeResult = 5716 ConservativeResult.intersectWith(RangeFromAffine); 5717 5718 auto RangeFromFactoring = getRangeViaFactoring( 5719 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5720 BitWidth); 5721 if (!RangeFromFactoring.isFullSet()) 5722 ConservativeResult = 5723 ConservativeResult.intersectWith(RangeFromFactoring); 5724 } 5725 } 5726 5727 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5728 } 5729 5730 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5731 // Check if the IR explicitly contains !range metadata. 5732 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5733 if (MDRange.hasValue()) 5734 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 5735 5736 // Split here to avoid paying the compile-time cost of calling both 5737 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5738 // if needed. 5739 const DataLayout &DL = getDataLayout(); 5740 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5741 // For a SCEVUnknown, ask ValueTracking. 5742 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5743 if (Known.One != ~Known.Zero + 1) 5744 ConservativeResult = 5745 ConservativeResult.intersectWith(ConstantRange(Known.One, 5746 ~Known.Zero + 1)); 5747 } else { 5748 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5749 "generalize as needed!"); 5750 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5751 if (NS > 1) 5752 ConservativeResult = ConservativeResult.intersectWith( 5753 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5754 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 5755 } 5756 5757 // A range of Phi is a subset of union of all ranges of its input. 5758 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5759 // Make sure that we do not run over cycled Phis. 5760 if (PendingPhiRanges.insert(Phi).second) { 5761 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5762 for (auto &Op : Phi->operands()) { 5763 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5764 RangeFromOps = RangeFromOps.unionWith(OpRange); 5765 // No point to continue if we already have a full set. 5766 if (RangeFromOps.isFullSet()) 5767 break; 5768 } 5769 ConservativeResult = ConservativeResult.intersectWith(RangeFromOps); 5770 bool Erased = PendingPhiRanges.erase(Phi); 5771 assert(Erased && "Failed to erase Phi properly?"); 5772 (void) Erased; 5773 } 5774 } 5775 5776 return setRange(U, SignHint, std::move(ConservativeResult)); 5777 } 5778 5779 return setRange(S, SignHint, std::move(ConservativeResult)); 5780 } 5781 5782 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5783 // values that the expression can take. Initially, the expression has a value 5784 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5785 // argument defines if we treat Step as signed or unsigned. 5786 static ConstantRange getRangeForAffineARHelper(APInt Step, 5787 const ConstantRange &StartRange, 5788 const APInt &MaxBECount, 5789 unsigned BitWidth, bool Signed) { 5790 // If either Step or MaxBECount is 0, then the expression won't change, and we 5791 // just need to return the initial range. 5792 if (Step == 0 || MaxBECount == 0) 5793 return StartRange; 5794 5795 // If we don't know anything about the initial value (i.e. StartRange is 5796 // FullRange), then we don't know anything about the final range either. 5797 // Return FullRange. 5798 if (StartRange.isFullSet()) 5799 return ConstantRange::getFull(BitWidth); 5800 5801 // If Step is signed and negative, then we use its absolute value, but we also 5802 // note that we're moving in the opposite direction. 5803 bool Descending = Signed && Step.isNegative(); 5804 5805 if (Signed) 5806 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5807 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5808 // This equations hold true due to the well-defined wrap-around behavior of 5809 // APInt. 5810 Step = Step.abs(); 5811 5812 // Check if Offset is more than full span of BitWidth. If it is, the 5813 // expression is guaranteed to overflow. 5814 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5815 return ConstantRange::getFull(BitWidth); 5816 5817 // Offset is by how much the expression can change. Checks above guarantee no 5818 // overflow here. 5819 APInt Offset = Step * MaxBECount; 5820 5821 // Minimum value of the final range will match the minimal value of StartRange 5822 // if the expression is increasing and will be decreased by Offset otherwise. 5823 // Maximum value of the final range will match the maximal value of StartRange 5824 // if the expression is decreasing and will be increased by Offset otherwise. 5825 APInt StartLower = StartRange.getLower(); 5826 APInt StartUpper = StartRange.getUpper() - 1; 5827 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5828 : (StartUpper + std::move(Offset)); 5829 5830 // It's possible that the new minimum/maximum value will fall into the initial 5831 // range (due to wrap around). This means that the expression can take any 5832 // value in this bitwidth, and we have to return full range. 5833 if (StartRange.contains(MovedBoundary)) 5834 return ConstantRange::getFull(BitWidth); 5835 5836 APInt NewLower = 5837 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5838 APInt NewUpper = 5839 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5840 NewUpper += 1; 5841 5842 // If we end up with full range, return a proper full range. 5843 if (NewLower == NewUpper) 5844 return ConstantRange::getFull(BitWidth); 5845 5846 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5847 return ConstantRange(std::move(NewLower), std::move(NewUpper)); 5848 } 5849 5850 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5851 const SCEV *Step, 5852 const SCEV *MaxBECount, 5853 unsigned BitWidth) { 5854 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5855 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5856 "Precondition!"); 5857 5858 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5859 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5860 5861 // First, consider step signed. 5862 ConstantRange StartSRange = getSignedRange(Start); 5863 ConstantRange StepSRange = getSignedRange(Step); 5864 5865 // If Step can be both positive and negative, we need to find ranges for the 5866 // maximum absolute step values in both directions and union them. 5867 ConstantRange SR = 5868 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5869 MaxBECountValue, BitWidth, /* Signed = */ true); 5870 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5871 StartSRange, MaxBECountValue, 5872 BitWidth, /* Signed = */ true)); 5873 5874 // Next, consider step unsigned. 5875 ConstantRange UR = getRangeForAffineARHelper( 5876 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5877 MaxBECountValue, BitWidth, /* Signed = */ false); 5878 5879 // Finally, intersect signed and unsigned ranges. 5880 return SR.intersectWith(UR); 5881 } 5882 5883 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5884 const SCEV *Step, 5885 const SCEV *MaxBECount, 5886 unsigned BitWidth) { 5887 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5888 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5889 5890 struct SelectPattern { 5891 Value *Condition = nullptr; 5892 APInt TrueValue; 5893 APInt FalseValue; 5894 5895 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5896 const SCEV *S) { 5897 Optional<unsigned> CastOp; 5898 APInt Offset(BitWidth, 0); 5899 5900 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5901 "Should be!"); 5902 5903 // Peel off a constant offset: 5904 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5905 // In the future we could consider being smarter here and handle 5906 // {Start+Step,+,Step} too. 5907 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5908 return; 5909 5910 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5911 S = SA->getOperand(1); 5912 } 5913 5914 // Peel off a cast operation 5915 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5916 CastOp = SCast->getSCEVType(); 5917 S = SCast->getOperand(); 5918 } 5919 5920 using namespace llvm::PatternMatch; 5921 5922 auto *SU = dyn_cast<SCEVUnknown>(S); 5923 const APInt *TrueVal, *FalseVal; 5924 if (!SU || 5925 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5926 m_APInt(FalseVal)))) { 5927 Condition = nullptr; 5928 return; 5929 } 5930 5931 TrueValue = *TrueVal; 5932 FalseValue = *FalseVal; 5933 5934 // Re-apply the cast we peeled off earlier 5935 if (CastOp.hasValue()) 5936 switch (*CastOp) { 5937 default: 5938 llvm_unreachable("Unknown SCEV cast type!"); 5939 5940 case scTruncate: 5941 TrueValue = TrueValue.trunc(BitWidth); 5942 FalseValue = FalseValue.trunc(BitWidth); 5943 break; 5944 case scZeroExtend: 5945 TrueValue = TrueValue.zext(BitWidth); 5946 FalseValue = FalseValue.zext(BitWidth); 5947 break; 5948 case scSignExtend: 5949 TrueValue = TrueValue.sext(BitWidth); 5950 FalseValue = FalseValue.sext(BitWidth); 5951 break; 5952 } 5953 5954 // Re-apply the constant offset we peeled off earlier 5955 TrueValue += Offset; 5956 FalseValue += Offset; 5957 } 5958 5959 bool isRecognized() { return Condition != nullptr; } 5960 }; 5961 5962 SelectPattern StartPattern(*this, BitWidth, Start); 5963 if (!StartPattern.isRecognized()) 5964 return ConstantRange::getFull(BitWidth); 5965 5966 SelectPattern StepPattern(*this, BitWidth, Step); 5967 if (!StepPattern.isRecognized()) 5968 return ConstantRange::getFull(BitWidth); 5969 5970 if (StartPattern.Condition != StepPattern.Condition) { 5971 // We don't handle this case today; but we could, by considering four 5972 // possibilities below instead of two. I'm not sure if there are cases where 5973 // that will help over what getRange already does, though. 5974 return ConstantRange::getFull(BitWidth); 5975 } 5976 5977 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5978 // construct arbitrary general SCEV expressions here. This function is called 5979 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5980 // say) can end up caching a suboptimal value. 5981 5982 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5983 // C2352 and C2512 (otherwise it isn't needed). 5984 5985 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5986 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5987 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5988 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5989 5990 ConstantRange TrueRange = 5991 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5992 ConstantRange FalseRange = 5993 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5994 5995 return TrueRange.unionWith(FalseRange); 5996 } 5997 5998 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5999 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6000 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6001 6002 // Return early if there are no flags to propagate to the SCEV. 6003 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6004 if (BinOp->hasNoUnsignedWrap()) 6005 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6006 if (BinOp->hasNoSignedWrap()) 6007 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6008 if (Flags == SCEV::FlagAnyWrap) 6009 return SCEV::FlagAnyWrap; 6010 6011 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6012 } 6013 6014 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6015 // Here we check that I is in the header of the innermost loop containing I, 6016 // since we only deal with instructions in the loop header. The actual loop we 6017 // need to check later will come from an add recurrence, but getting that 6018 // requires computing the SCEV of the operands, which can be expensive. This 6019 // check we can do cheaply to rule out some cases early. 6020 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6021 if (InnermostContainingLoop == nullptr || 6022 InnermostContainingLoop->getHeader() != I->getParent()) 6023 return false; 6024 6025 // Only proceed if we can prove that I does not yield poison. 6026 if (!programUndefinedIfFullPoison(I)) 6027 return false; 6028 6029 // At this point we know that if I is executed, then it does not wrap 6030 // according to at least one of NSW or NUW. If I is not executed, then we do 6031 // not know if the calculation that I represents would wrap. Multiple 6032 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6033 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6034 // derived from other instructions that map to the same SCEV. We cannot make 6035 // that guarantee for cases where I is not executed. So we need to find the 6036 // loop that I is considered in relation to and prove that I is executed for 6037 // every iteration of that loop. That implies that the value that I 6038 // calculates does not wrap anywhere in the loop, so then we can apply the 6039 // flags to the SCEV. 6040 // 6041 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6042 // from different loops, so that we know which loop to prove that I is 6043 // executed in. 6044 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6045 // I could be an extractvalue from a call to an overflow intrinsic. 6046 // TODO: We can do better here in some cases. 6047 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6048 return false; 6049 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6050 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6051 bool AllOtherOpsLoopInvariant = true; 6052 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6053 ++OtherOpIndex) { 6054 if (OtherOpIndex != OpIndex) { 6055 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6056 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6057 AllOtherOpsLoopInvariant = false; 6058 break; 6059 } 6060 } 6061 } 6062 if (AllOtherOpsLoopInvariant && 6063 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6064 return true; 6065 } 6066 } 6067 return false; 6068 } 6069 6070 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6071 // If we know that \c I can never be poison period, then that's enough. 6072 if (isSCEVExprNeverPoison(I)) 6073 return true; 6074 6075 // For an add recurrence specifically, we assume that infinite loops without 6076 // side effects are undefined behavior, and then reason as follows: 6077 // 6078 // If the add recurrence is poison in any iteration, it is poison on all 6079 // future iterations (since incrementing poison yields poison). If the result 6080 // of the add recurrence is fed into the loop latch condition and the loop 6081 // does not contain any throws or exiting blocks other than the latch, we now 6082 // have the ability to "choose" whether the backedge is taken or not (by 6083 // choosing a sufficiently evil value for the poison feeding into the branch) 6084 // for every iteration including and after the one in which \p I first became 6085 // poison. There are two possibilities (let's call the iteration in which \p 6086 // I first became poison as K): 6087 // 6088 // 1. In the set of iterations including and after K, the loop body executes 6089 // no side effects. In this case executing the backege an infinte number 6090 // of times will yield undefined behavior. 6091 // 6092 // 2. In the set of iterations including and after K, the loop body executes 6093 // at least one side effect. In this case, that specific instance of side 6094 // effect is control dependent on poison, which also yields undefined 6095 // behavior. 6096 6097 auto *ExitingBB = L->getExitingBlock(); 6098 auto *LatchBB = L->getLoopLatch(); 6099 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6100 return false; 6101 6102 SmallPtrSet<const Instruction *, 16> Pushed; 6103 SmallVector<const Instruction *, 8> PoisonStack; 6104 6105 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6106 // things that are known to be fully poison under that assumption go on the 6107 // PoisonStack. 6108 Pushed.insert(I); 6109 PoisonStack.push_back(I); 6110 6111 bool LatchControlDependentOnPoison = false; 6112 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6113 const Instruction *Poison = PoisonStack.pop_back_val(); 6114 6115 for (auto *PoisonUser : Poison->users()) { 6116 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 6117 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6118 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6119 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6120 assert(BI->isConditional() && "Only possibility!"); 6121 if (BI->getParent() == LatchBB) { 6122 LatchControlDependentOnPoison = true; 6123 break; 6124 } 6125 } 6126 } 6127 } 6128 6129 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6130 } 6131 6132 ScalarEvolution::LoopProperties 6133 ScalarEvolution::getLoopProperties(const Loop *L) { 6134 using LoopProperties = ScalarEvolution::LoopProperties; 6135 6136 auto Itr = LoopPropertiesCache.find(L); 6137 if (Itr == LoopPropertiesCache.end()) { 6138 auto HasSideEffects = [](Instruction *I) { 6139 if (auto *SI = dyn_cast<StoreInst>(I)) 6140 return !SI->isSimple(); 6141 6142 return I->mayHaveSideEffects(); 6143 }; 6144 6145 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6146 /*HasNoSideEffects*/ true}; 6147 6148 for (auto *BB : L->getBlocks()) 6149 for (auto &I : *BB) { 6150 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6151 LP.HasNoAbnormalExits = false; 6152 if (HasSideEffects(&I)) 6153 LP.HasNoSideEffects = false; 6154 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6155 break; // We're already as pessimistic as we can get. 6156 } 6157 6158 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6159 assert(InsertPair.second && "We just checked!"); 6160 Itr = InsertPair.first; 6161 } 6162 6163 return Itr->second; 6164 } 6165 6166 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6167 if (!isSCEVable(V->getType())) 6168 return getUnknown(V); 6169 6170 if (Instruction *I = dyn_cast<Instruction>(V)) { 6171 // Don't attempt to analyze instructions in blocks that aren't 6172 // reachable. Such instructions don't matter, and they aren't required 6173 // to obey basic rules for definitions dominating uses which this 6174 // analysis depends on. 6175 if (!DT.isReachableFromEntry(I->getParent())) 6176 return getUnknown(UndefValue::get(V->getType())); 6177 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6178 return getConstant(CI); 6179 else if (isa<ConstantPointerNull>(V)) 6180 return getZero(V->getType()); 6181 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6182 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6183 else if (!isa<ConstantExpr>(V)) 6184 return getUnknown(V); 6185 6186 Operator *U = cast<Operator>(V); 6187 if (auto BO = MatchBinaryOp(U, DT)) { 6188 switch (BO->Opcode) { 6189 case Instruction::Add: { 6190 // The simple thing to do would be to just call getSCEV on both operands 6191 // and call getAddExpr with the result. However if we're looking at a 6192 // bunch of things all added together, this can be quite inefficient, 6193 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6194 // Instead, gather up all the operands and make a single getAddExpr call. 6195 // LLVM IR canonical form means we need only traverse the left operands. 6196 SmallVector<const SCEV *, 4> AddOps; 6197 do { 6198 if (BO->Op) { 6199 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6200 AddOps.push_back(OpSCEV); 6201 break; 6202 } 6203 6204 // If a NUW or NSW flag can be applied to the SCEV for this 6205 // addition, then compute the SCEV for this addition by itself 6206 // with a separate call to getAddExpr. We need to do that 6207 // instead of pushing the operands of the addition onto AddOps, 6208 // since the flags are only known to apply to this particular 6209 // addition - they may not apply to other additions that can be 6210 // formed with operands from AddOps. 6211 const SCEV *RHS = getSCEV(BO->RHS); 6212 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6213 if (Flags != SCEV::FlagAnyWrap) { 6214 const SCEV *LHS = getSCEV(BO->LHS); 6215 if (BO->Opcode == Instruction::Sub) 6216 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6217 else 6218 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6219 break; 6220 } 6221 } 6222 6223 if (BO->Opcode == Instruction::Sub) 6224 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6225 else 6226 AddOps.push_back(getSCEV(BO->RHS)); 6227 6228 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6229 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6230 NewBO->Opcode != Instruction::Sub)) { 6231 AddOps.push_back(getSCEV(BO->LHS)); 6232 break; 6233 } 6234 BO = NewBO; 6235 } while (true); 6236 6237 return getAddExpr(AddOps); 6238 } 6239 6240 case Instruction::Mul: { 6241 SmallVector<const SCEV *, 4> MulOps; 6242 do { 6243 if (BO->Op) { 6244 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6245 MulOps.push_back(OpSCEV); 6246 break; 6247 } 6248 6249 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6250 if (Flags != SCEV::FlagAnyWrap) { 6251 MulOps.push_back( 6252 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6253 break; 6254 } 6255 } 6256 6257 MulOps.push_back(getSCEV(BO->RHS)); 6258 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6259 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6260 MulOps.push_back(getSCEV(BO->LHS)); 6261 break; 6262 } 6263 BO = NewBO; 6264 } while (true); 6265 6266 return getMulExpr(MulOps); 6267 } 6268 case Instruction::UDiv: 6269 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6270 case Instruction::URem: 6271 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6272 case Instruction::Sub: { 6273 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6274 if (BO->Op) 6275 Flags = getNoWrapFlagsFromUB(BO->Op); 6276 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6277 } 6278 case Instruction::And: 6279 // For an expression like x&255 that merely masks off the high bits, 6280 // use zext(trunc(x)) as the SCEV expression. 6281 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6282 if (CI->isZero()) 6283 return getSCEV(BO->RHS); 6284 if (CI->isMinusOne()) 6285 return getSCEV(BO->LHS); 6286 const APInt &A = CI->getValue(); 6287 6288 // Instcombine's ShrinkDemandedConstant may strip bits out of 6289 // constants, obscuring what would otherwise be a low-bits mask. 6290 // Use computeKnownBits to compute what ShrinkDemandedConstant 6291 // knew about to reconstruct a low-bits mask value. 6292 unsigned LZ = A.countLeadingZeros(); 6293 unsigned TZ = A.countTrailingZeros(); 6294 unsigned BitWidth = A.getBitWidth(); 6295 KnownBits Known(BitWidth); 6296 computeKnownBits(BO->LHS, Known, getDataLayout(), 6297 0, &AC, nullptr, &DT); 6298 6299 APInt EffectiveMask = 6300 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6301 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6302 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6303 const SCEV *LHS = getSCEV(BO->LHS); 6304 const SCEV *ShiftedLHS = nullptr; 6305 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6306 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6307 // For an expression like (x * 8) & 8, simplify the multiply. 6308 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6309 unsigned GCD = std::min(MulZeros, TZ); 6310 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6311 SmallVector<const SCEV*, 4> MulOps; 6312 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6313 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6314 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6315 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6316 } 6317 } 6318 if (!ShiftedLHS) 6319 ShiftedLHS = getUDivExpr(LHS, MulCount); 6320 return getMulExpr( 6321 getZeroExtendExpr( 6322 getTruncateExpr(ShiftedLHS, 6323 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6324 BO->LHS->getType()), 6325 MulCount); 6326 } 6327 } 6328 break; 6329 6330 case Instruction::Or: 6331 // If the RHS of the Or is a constant, we may have something like: 6332 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6333 // optimizations will transparently handle this case. 6334 // 6335 // In order for this transformation to be safe, the LHS must be of the 6336 // form X*(2^n) and the Or constant must be less than 2^n. 6337 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6338 const SCEV *LHS = getSCEV(BO->LHS); 6339 const APInt &CIVal = CI->getValue(); 6340 if (GetMinTrailingZeros(LHS) >= 6341 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6342 // Build a plain add SCEV. 6343 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6344 // If the LHS of the add was an addrec and it has no-wrap flags, 6345 // transfer the no-wrap flags, since an or won't introduce a wrap. 6346 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6347 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6348 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6349 OldAR->getNoWrapFlags()); 6350 } 6351 return S; 6352 } 6353 } 6354 break; 6355 6356 case Instruction::Xor: 6357 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6358 // If the RHS of xor is -1, then this is a not operation. 6359 if (CI->isMinusOne()) 6360 return getNotSCEV(getSCEV(BO->LHS)); 6361 6362 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6363 // This is a variant of the check for xor with -1, and it handles 6364 // the case where instcombine has trimmed non-demanded bits out 6365 // of an xor with -1. 6366 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6367 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6368 if (LBO->getOpcode() == Instruction::And && 6369 LCI->getValue() == CI->getValue()) 6370 if (const SCEVZeroExtendExpr *Z = 6371 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6372 Type *UTy = BO->LHS->getType(); 6373 const SCEV *Z0 = Z->getOperand(); 6374 Type *Z0Ty = Z0->getType(); 6375 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6376 6377 // If C is a low-bits mask, the zero extend is serving to 6378 // mask off the high bits. Complement the operand and 6379 // re-apply the zext. 6380 if (CI->getValue().isMask(Z0TySize)) 6381 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6382 6383 // If C is a single bit, it may be in the sign-bit position 6384 // before the zero-extend. In this case, represent the xor 6385 // using an add, which is equivalent, and re-apply the zext. 6386 APInt Trunc = CI->getValue().trunc(Z0TySize); 6387 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6388 Trunc.isSignMask()) 6389 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6390 UTy); 6391 } 6392 } 6393 break; 6394 6395 case Instruction::Shl: 6396 // Turn shift left of a constant amount into a multiply. 6397 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6398 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6399 6400 // If the shift count is not less than the bitwidth, the result of 6401 // the shift is undefined. Don't try to analyze it, because the 6402 // resolution chosen here may differ from the resolution chosen in 6403 // other parts of the compiler. 6404 if (SA->getValue().uge(BitWidth)) 6405 break; 6406 6407 // It is currently not resolved how to interpret NSW for left 6408 // shift by BitWidth - 1, so we avoid applying flags in that 6409 // case. Remove this check (or this comment) once the situation 6410 // is resolved. See 6411 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6412 // and http://reviews.llvm.org/D8890 . 6413 auto Flags = SCEV::FlagAnyWrap; 6414 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6415 Flags = getNoWrapFlagsFromUB(BO->Op); 6416 6417 Constant *X = ConstantInt::get( 6418 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6419 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6420 } 6421 break; 6422 6423 case Instruction::AShr: { 6424 // AShr X, C, where C is a constant. 6425 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6426 if (!CI) 6427 break; 6428 6429 Type *OuterTy = BO->LHS->getType(); 6430 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6431 // If the shift count is not less than the bitwidth, the result of 6432 // the shift is undefined. Don't try to analyze it, because the 6433 // resolution chosen here may differ from the resolution chosen in 6434 // other parts of the compiler. 6435 if (CI->getValue().uge(BitWidth)) 6436 break; 6437 6438 if (CI->isZero()) 6439 return getSCEV(BO->LHS); // shift by zero --> noop 6440 6441 uint64_t AShrAmt = CI->getZExtValue(); 6442 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6443 6444 Operator *L = dyn_cast<Operator>(BO->LHS); 6445 if (L && L->getOpcode() == Instruction::Shl) { 6446 // X = Shl A, n 6447 // Y = AShr X, m 6448 // Both n and m are constant. 6449 6450 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6451 if (L->getOperand(1) == BO->RHS) 6452 // For a two-shift sext-inreg, i.e. n = m, 6453 // use sext(trunc(x)) as the SCEV expression. 6454 return getSignExtendExpr( 6455 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6456 6457 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6458 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6459 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6460 if (ShlAmt > AShrAmt) { 6461 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6462 // expression. We already checked that ShlAmt < BitWidth, so 6463 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6464 // ShlAmt - AShrAmt < Amt. 6465 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6466 ShlAmt - AShrAmt); 6467 return getSignExtendExpr( 6468 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6469 getConstant(Mul)), OuterTy); 6470 } 6471 } 6472 } 6473 break; 6474 } 6475 } 6476 } 6477 6478 switch (U->getOpcode()) { 6479 case Instruction::Trunc: 6480 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6481 6482 case Instruction::ZExt: 6483 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6484 6485 case Instruction::SExt: 6486 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6487 // The NSW flag of a subtract does not always survive the conversion to 6488 // A + (-1)*B. By pushing sign extension onto its operands we are much 6489 // more likely to preserve NSW and allow later AddRec optimisations. 6490 // 6491 // NOTE: This is effectively duplicating this logic from getSignExtend: 6492 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6493 // but by that point the NSW information has potentially been lost. 6494 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6495 Type *Ty = U->getType(); 6496 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6497 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6498 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6499 } 6500 } 6501 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6502 6503 case Instruction::BitCast: 6504 // BitCasts are no-op casts so we just eliminate the cast. 6505 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6506 return getSCEV(U->getOperand(0)); 6507 break; 6508 6509 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6510 // lead to pointer expressions which cannot safely be expanded to GEPs, 6511 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6512 // simplifying integer expressions. 6513 6514 case Instruction::GetElementPtr: 6515 return createNodeForGEP(cast<GEPOperator>(U)); 6516 6517 case Instruction::PHI: 6518 return createNodeForPHI(cast<PHINode>(U)); 6519 6520 case Instruction::Select: 6521 // U can also be a select constant expr, which let fall through. Since 6522 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6523 // constant expressions cannot have instructions as operands, we'd have 6524 // returned getUnknown for a select constant expressions anyway. 6525 if (isa<Instruction>(U)) 6526 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6527 U->getOperand(1), U->getOperand(2)); 6528 break; 6529 6530 case Instruction::Call: 6531 case Instruction::Invoke: 6532 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6533 return getSCEV(RV); 6534 break; 6535 } 6536 6537 return getUnknown(V); 6538 } 6539 6540 //===----------------------------------------------------------------------===// 6541 // Iteration Count Computation Code 6542 // 6543 6544 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6545 if (!ExitCount) 6546 return 0; 6547 6548 ConstantInt *ExitConst = ExitCount->getValue(); 6549 6550 // Guard against huge trip counts. 6551 if (ExitConst->getValue().getActiveBits() > 32) 6552 return 0; 6553 6554 // In case of integer overflow, this returns 0, which is correct. 6555 return ((unsigned)ExitConst->getZExtValue()) + 1; 6556 } 6557 6558 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6559 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6560 return getSmallConstantTripCount(L, ExitingBB); 6561 6562 // No trip count information for multiple exits. 6563 return 0; 6564 } 6565 6566 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6567 BasicBlock *ExitingBlock) { 6568 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6569 assert(L->isLoopExiting(ExitingBlock) && 6570 "Exiting block must actually branch out of the loop!"); 6571 const SCEVConstant *ExitCount = 6572 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6573 return getConstantTripCount(ExitCount); 6574 } 6575 6576 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6577 const auto *MaxExitCount = 6578 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 6579 return getConstantTripCount(MaxExitCount); 6580 } 6581 6582 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6583 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6584 return getSmallConstantTripMultiple(L, ExitingBB); 6585 6586 // No trip multiple information for multiple exits. 6587 return 0; 6588 } 6589 6590 /// Returns the largest constant divisor of the trip count of this loop as a 6591 /// normal unsigned value, if possible. This means that the actual trip count is 6592 /// always a multiple of the returned value (don't forget the trip count could 6593 /// very well be zero as well!). 6594 /// 6595 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6596 /// multiple of a constant (which is also the case if the trip count is simply 6597 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6598 /// if the trip count is very large (>= 2^32). 6599 /// 6600 /// As explained in the comments for getSmallConstantTripCount, this assumes 6601 /// that control exits the loop via ExitingBlock. 6602 unsigned 6603 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6604 BasicBlock *ExitingBlock) { 6605 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6606 assert(L->isLoopExiting(ExitingBlock) && 6607 "Exiting block must actually branch out of the loop!"); 6608 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6609 if (ExitCount == getCouldNotCompute()) 6610 return 1; 6611 6612 // Get the trip count from the BE count by adding 1. 6613 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6614 6615 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6616 if (!TC) 6617 // Attempt to factor more general cases. Returns the greatest power of 6618 // two divisor. If overflow happens, the trip count expression is still 6619 // divisible by the greatest power of 2 divisor returned. 6620 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6621 6622 ConstantInt *Result = TC->getValue(); 6623 6624 // Guard against huge trip counts (this requires checking 6625 // for zero to handle the case where the trip count == -1 and the 6626 // addition wraps). 6627 if (!Result || Result->getValue().getActiveBits() > 32 || 6628 Result->getValue().getActiveBits() == 0) 6629 return 1; 6630 6631 return (unsigned)Result->getZExtValue(); 6632 } 6633 6634 /// Get the expression for the number of loop iterations for which this loop is 6635 /// guaranteed not to exit via ExitingBlock. Otherwise return 6636 /// SCEVCouldNotCompute. 6637 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6638 BasicBlock *ExitingBlock) { 6639 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6640 } 6641 6642 const SCEV * 6643 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6644 SCEVUnionPredicate &Preds) { 6645 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6646 } 6647 6648 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6649 return getBackedgeTakenInfo(L).getExact(L, this); 6650 } 6651 6652 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6653 /// known never to be less than the actual backedge taken count. 6654 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 6655 return getBackedgeTakenInfo(L).getMax(this); 6656 } 6657 6658 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6659 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6660 } 6661 6662 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6663 static void 6664 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6665 BasicBlock *Header = L->getHeader(); 6666 6667 // Push all Loop-header PHIs onto the Worklist stack. 6668 for (PHINode &PN : Header->phis()) 6669 Worklist.push_back(&PN); 6670 } 6671 6672 const ScalarEvolution::BackedgeTakenInfo & 6673 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6674 auto &BTI = getBackedgeTakenInfo(L); 6675 if (BTI.hasFullInfo()) 6676 return BTI; 6677 6678 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6679 6680 if (!Pair.second) 6681 return Pair.first->second; 6682 6683 BackedgeTakenInfo Result = 6684 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6685 6686 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6687 } 6688 6689 const ScalarEvolution::BackedgeTakenInfo & 6690 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6691 // Initially insert an invalid entry for this loop. If the insertion 6692 // succeeds, proceed to actually compute a backedge-taken count and 6693 // update the value. The temporary CouldNotCompute value tells SCEV 6694 // code elsewhere that it shouldn't attempt to request a new 6695 // backedge-taken count, which could result in infinite recursion. 6696 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6697 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6698 if (!Pair.second) 6699 return Pair.first->second; 6700 6701 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6702 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6703 // must be cleared in this scope. 6704 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6705 6706 // In product build, there are no usage of statistic. 6707 (void)NumTripCountsComputed; 6708 (void)NumTripCountsNotComputed; 6709 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6710 const SCEV *BEExact = Result.getExact(L, this); 6711 if (BEExact != getCouldNotCompute()) { 6712 assert(isLoopInvariant(BEExact, L) && 6713 isLoopInvariant(Result.getMax(this), L) && 6714 "Computed backedge-taken count isn't loop invariant for loop!"); 6715 ++NumTripCountsComputed; 6716 } 6717 else if (Result.getMax(this) == getCouldNotCompute() && 6718 isa<PHINode>(L->getHeader()->begin())) { 6719 // Only count loops that have phi nodes as not being computable. 6720 ++NumTripCountsNotComputed; 6721 } 6722 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6723 6724 // Now that we know more about the trip count for this loop, forget any 6725 // existing SCEV values for PHI nodes in this loop since they are only 6726 // conservative estimates made without the benefit of trip count 6727 // information. This is similar to the code in forgetLoop, except that 6728 // it handles SCEVUnknown PHI nodes specially. 6729 if (Result.hasAnyInfo()) { 6730 SmallVector<Instruction *, 16> Worklist; 6731 PushLoopPHIs(L, Worklist); 6732 6733 SmallPtrSet<Instruction *, 8> Discovered; 6734 while (!Worklist.empty()) { 6735 Instruction *I = Worklist.pop_back_val(); 6736 6737 ValueExprMapType::iterator It = 6738 ValueExprMap.find_as(static_cast<Value *>(I)); 6739 if (It != ValueExprMap.end()) { 6740 const SCEV *Old = It->second; 6741 6742 // SCEVUnknown for a PHI either means that it has an unrecognized 6743 // structure, or it's a PHI that's in the progress of being computed 6744 // by createNodeForPHI. In the former case, additional loop trip 6745 // count information isn't going to change anything. In the later 6746 // case, createNodeForPHI will perform the necessary updates on its 6747 // own when it gets to that point. 6748 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6749 eraseValueFromMap(It->first); 6750 forgetMemoizedResults(Old); 6751 } 6752 if (PHINode *PN = dyn_cast<PHINode>(I)) 6753 ConstantEvolutionLoopExitValue.erase(PN); 6754 } 6755 6756 // Since we don't need to invalidate anything for correctness and we're 6757 // only invalidating to make SCEV's results more precise, we get to stop 6758 // early to avoid invalidating too much. This is especially important in 6759 // cases like: 6760 // 6761 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6762 // loop0: 6763 // %pn0 = phi 6764 // ... 6765 // loop1: 6766 // %pn1 = phi 6767 // ... 6768 // 6769 // where both loop0 and loop1's backedge taken count uses the SCEV 6770 // expression for %v. If we don't have the early stop below then in cases 6771 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6772 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6773 // count for loop1, effectively nullifying SCEV's trip count cache. 6774 for (auto *U : I->users()) 6775 if (auto *I = dyn_cast<Instruction>(U)) { 6776 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6777 if (LoopForUser && L->contains(LoopForUser) && 6778 Discovered.insert(I).second) 6779 Worklist.push_back(I); 6780 } 6781 } 6782 } 6783 6784 // Re-lookup the insert position, since the call to 6785 // computeBackedgeTakenCount above could result in a 6786 // recusive call to getBackedgeTakenInfo (on a different 6787 // loop), which would invalidate the iterator computed 6788 // earlier. 6789 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6790 } 6791 6792 void ScalarEvolution::forgetLoop(const Loop *L) { 6793 // Drop any stored trip count value. 6794 auto RemoveLoopFromBackedgeMap = 6795 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6796 auto BTCPos = Map.find(L); 6797 if (BTCPos != Map.end()) { 6798 BTCPos->second.clear(); 6799 Map.erase(BTCPos); 6800 } 6801 }; 6802 6803 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6804 SmallVector<Instruction *, 32> Worklist; 6805 SmallPtrSet<Instruction *, 16> Visited; 6806 6807 // Iterate over all the loops and sub-loops to drop SCEV information. 6808 while (!LoopWorklist.empty()) { 6809 auto *CurrL = LoopWorklist.pop_back_val(); 6810 6811 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6812 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6813 6814 // Drop information about predicated SCEV rewrites for this loop. 6815 for (auto I = PredicatedSCEVRewrites.begin(); 6816 I != PredicatedSCEVRewrites.end();) { 6817 std::pair<const SCEV *, const Loop *> Entry = I->first; 6818 if (Entry.second == CurrL) 6819 PredicatedSCEVRewrites.erase(I++); 6820 else 6821 ++I; 6822 } 6823 6824 auto LoopUsersItr = LoopUsers.find(CurrL); 6825 if (LoopUsersItr != LoopUsers.end()) { 6826 for (auto *S : LoopUsersItr->second) 6827 forgetMemoizedResults(S); 6828 LoopUsers.erase(LoopUsersItr); 6829 } 6830 6831 // Drop information about expressions based on loop-header PHIs. 6832 PushLoopPHIs(CurrL, Worklist); 6833 6834 while (!Worklist.empty()) { 6835 Instruction *I = Worklist.pop_back_val(); 6836 if (!Visited.insert(I).second) 6837 continue; 6838 6839 ValueExprMapType::iterator It = 6840 ValueExprMap.find_as(static_cast<Value *>(I)); 6841 if (It != ValueExprMap.end()) { 6842 eraseValueFromMap(It->first); 6843 forgetMemoizedResults(It->second); 6844 if (PHINode *PN = dyn_cast<PHINode>(I)) 6845 ConstantEvolutionLoopExitValue.erase(PN); 6846 } 6847 6848 PushDefUseChildren(I, Worklist); 6849 } 6850 6851 LoopPropertiesCache.erase(CurrL); 6852 // Forget all contained loops too, to avoid dangling entries in the 6853 // ValuesAtScopes map. 6854 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6855 } 6856 } 6857 6858 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6859 while (Loop *Parent = L->getParentLoop()) 6860 L = Parent; 6861 forgetLoop(L); 6862 } 6863 6864 void ScalarEvolution::forgetValue(Value *V) { 6865 Instruction *I = dyn_cast<Instruction>(V); 6866 if (!I) return; 6867 6868 // Drop information about expressions based on loop-header PHIs. 6869 SmallVector<Instruction *, 16> Worklist; 6870 Worklist.push_back(I); 6871 6872 SmallPtrSet<Instruction *, 8> Visited; 6873 while (!Worklist.empty()) { 6874 I = Worklist.pop_back_val(); 6875 if (!Visited.insert(I).second) 6876 continue; 6877 6878 ValueExprMapType::iterator It = 6879 ValueExprMap.find_as(static_cast<Value *>(I)); 6880 if (It != ValueExprMap.end()) { 6881 eraseValueFromMap(It->first); 6882 forgetMemoizedResults(It->second); 6883 if (PHINode *PN = dyn_cast<PHINode>(I)) 6884 ConstantEvolutionLoopExitValue.erase(PN); 6885 } 6886 6887 PushDefUseChildren(I, Worklist); 6888 } 6889 } 6890 6891 /// Get the exact loop backedge taken count considering all loop exits. A 6892 /// computable result can only be returned for loops with all exiting blocks 6893 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6894 /// is never skipped. This is a valid assumption as long as the loop exits via 6895 /// that test. For precise results, it is the caller's responsibility to specify 6896 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6897 const SCEV * 6898 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6899 SCEVUnionPredicate *Preds) const { 6900 // If any exits were not computable, the loop is not computable. 6901 if (!isComplete() || ExitNotTaken.empty()) 6902 return SE->getCouldNotCompute(); 6903 6904 const BasicBlock *Latch = L->getLoopLatch(); 6905 // All exiting blocks we have collected must dominate the only backedge. 6906 if (!Latch) 6907 return SE->getCouldNotCompute(); 6908 6909 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6910 // count is simply a minimum out of all these calculated exit counts. 6911 SmallVector<const SCEV *, 2> Ops; 6912 for (auto &ENT : ExitNotTaken) { 6913 const SCEV *BECount = ENT.ExactNotTaken; 6914 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6915 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6916 "We should only have known counts for exiting blocks that dominate " 6917 "latch!"); 6918 6919 Ops.push_back(BECount); 6920 6921 if (Preds && !ENT.hasAlwaysTruePredicate()) 6922 Preds->add(ENT.Predicate.get()); 6923 6924 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6925 "Predicate should be always true!"); 6926 } 6927 6928 return SE->getUMinFromMismatchedTypes(Ops); 6929 } 6930 6931 /// Get the exact not taken count for this loop exit. 6932 const SCEV * 6933 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6934 ScalarEvolution *SE) const { 6935 for (auto &ENT : ExitNotTaken) 6936 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6937 return ENT.ExactNotTaken; 6938 6939 return SE->getCouldNotCompute(); 6940 } 6941 6942 /// getMax - Get the max backedge taken count for the loop. 6943 const SCEV * 6944 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6945 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6946 return !ENT.hasAlwaysTruePredicate(); 6947 }; 6948 6949 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6950 return SE->getCouldNotCompute(); 6951 6952 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6953 "No point in having a non-constant max backedge taken count!"); 6954 return getMax(); 6955 } 6956 6957 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6958 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6959 return !ENT.hasAlwaysTruePredicate(); 6960 }; 6961 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6962 } 6963 6964 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6965 ScalarEvolution *SE) const { 6966 if (getMax() && getMax() != SE->getCouldNotCompute() && 6967 SE->hasOperand(getMax(), S)) 6968 return true; 6969 6970 for (auto &ENT : ExitNotTaken) 6971 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6972 SE->hasOperand(ENT.ExactNotTaken, S)) 6973 return true; 6974 6975 return false; 6976 } 6977 6978 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6979 : ExactNotTaken(E), MaxNotTaken(E) { 6980 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6981 isa<SCEVConstant>(MaxNotTaken)) && 6982 "No point in having a non-constant max backedge taken count!"); 6983 } 6984 6985 ScalarEvolution::ExitLimit::ExitLimit( 6986 const SCEV *E, const SCEV *M, bool MaxOrZero, 6987 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6988 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6989 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6990 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6991 "Exact is not allowed to be less precise than Max"); 6992 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6993 isa<SCEVConstant>(MaxNotTaken)) && 6994 "No point in having a non-constant max backedge taken count!"); 6995 for (auto *PredSet : PredSetList) 6996 for (auto *P : *PredSet) 6997 addPredicate(P); 6998 } 6999 7000 ScalarEvolution::ExitLimit::ExitLimit( 7001 const SCEV *E, const SCEV *M, bool MaxOrZero, 7002 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7003 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7004 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7005 isa<SCEVConstant>(MaxNotTaken)) && 7006 "No point in having a non-constant max backedge taken count!"); 7007 } 7008 7009 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7010 bool MaxOrZero) 7011 : ExitLimit(E, M, MaxOrZero, None) { 7012 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7013 isa<SCEVConstant>(MaxNotTaken)) && 7014 "No point in having a non-constant max backedge taken count!"); 7015 } 7016 7017 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7018 /// computable exit into a persistent ExitNotTakenInfo array. 7019 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7020 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 7021 ExitCounts, 7022 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 7023 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 7024 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7025 7026 ExitNotTaken.reserve(ExitCounts.size()); 7027 std::transform( 7028 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7029 [&](const EdgeExitInfo &EEI) { 7030 BasicBlock *ExitBB = EEI.first; 7031 const ExitLimit &EL = EEI.second; 7032 if (EL.Predicates.empty()) 7033 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 7034 7035 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7036 for (auto *Pred : EL.Predicates) 7037 Predicate->add(Pred); 7038 7039 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 7040 }); 7041 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 7042 "No point in having a non-constant max backedge taken count!"); 7043 } 7044 7045 /// Invalidate this result and free the ExitNotTakenInfo array. 7046 void ScalarEvolution::BackedgeTakenInfo::clear() { 7047 ExitNotTaken.clear(); 7048 } 7049 7050 /// Compute the number of times the backedge of the specified loop will execute. 7051 ScalarEvolution::BackedgeTakenInfo 7052 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7053 bool AllowPredicates) { 7054 SmallVector<BasicBlock *, 8> ExitingBlocks; 7055 L->getExitingBlocks(ExitingBlocks); 7056 7057 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7058 7059 SmallVector<EdgeExitInfo, 4> ExitCounts; 7060 bool CouldComputeBECount = true; 7061 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7062 const SCEV *MustExitMaxBECount = nullptr; 7063 const SCEV *MayExitMaxBECount = nullptr; 7064 bool MustExitMaxOrZero = false; 7065 7066 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7067 // and compute maxBECount. 7068 // Do a union of all the predicates here. 7069 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7070 BasicBlock *ExitBB = ExitingBlocks[i]; 7071 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7072 7073 assert((AllowPredicates || EL.Predicates.empty()) && 7074 "Predicated exit limit when predicates are not allowed!"); 7075 7076 // 1. For each exit that can be computed, add an entry to ExitCounts. 7077 // CouldComputeBECount is true only if all exits can be computed. 7078 if (EL.ExactNotTaken == getCouldNotCompute()) 7079 // We couldn't compute an exact value for this exit, so 7080 // we won't be able to compute an exact value for the loop. 7081 CouldComputeBECount = false; 7082 else 7083 ExitCounts.emplace_back(ExitBB, EL); 7084 7085 // 2. Derive the loop's MaxBECount from each exit's max number of 7086 // non-exiting iterations. Partition the loop exits into two kinds: 7087 // LoopMustExits and LoopMayExits. 7088 // 7089 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7090 // is a LoopMayExit. If any computable LoopMustExit is found, then 7091 // MaxBECount is the minimum EL.MaxNotTaken of computable 7092 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7093 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7094 // computable EL.MaxNotTaken. 7095 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7096 DT.dominates(ExitBB, Latch)) { 7097 if (!MustExitMaxBECount) { 7098 MustExitMaxBECount = EL.MaxNotTaken; 7099 MustExitMaxOrZero = EL.MaxOrZero; 7100 } else { 7101 MustExitMaxBECount = 7102 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7103 } 7104 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7105 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7106 MayExitMaxBECount = EL.MaxNotTaken; 7107 else { 7108 MayExitMaxBECount = 7109 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7110 } 7111 } 7112 } 7113 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7114 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7115 // The loop backedge will be taken the maximum or zero times if there's 7116 // a single exit that must be taken the maximum or zero times. 7117 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7118 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7119 MaxBECount, MaxOrZero); 7120 } 7121 7122 ScalarEvolution::ExitLimit 7123 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7124 bool AllowPredicates) { 7125 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7126 // If our exiting block does not dominate the latch, then its connection with 7127 // loop's exit limit may be far from trivial. 7128 const BasicBlock *Latch = L->getLoopLatch(); 7129 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7130 return getCouldNotCompute(); 7131 7132 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7133 Instruction *Term = ExitingBlock->getTerminator(); 7134 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7135 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7136 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7137 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7138 "It should have one successor in loop and one exit block!"); 7139 // Proceed to the next level to examine the exit condition expression. 7140 return computeExitLimitFromCond( 7141 L, BI->getCondition(), ExitIfTrue, 7142 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7143 } 7144 7145 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7146 // For switch, make sure that there is a single exit from the loop. 7147 BasicBlock *Exit = nullptr; 7148 for (auto *SBB : successors(ExitingBlock)) 7149 if (!L->contains(SBB)) { 7150 if (Exit) // Multiple exit successors. 7151 return getCouldNotCompute(); 7152 Exit = SBB; 7153 } 7154 assert(Exit && "Exiting block must have at least one exit"); 7155 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7156 /*ControlsExit=*/IsOnlyExit); 7157 } 7158 7159 return getCouldNotCompute(); 7160 } 7161 7162 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7163 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7164 bool ControlsExit, bool AllowPredicates) { 7165 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7166 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7167 ControlsExit, AllowPredicates); 7168 } 7169 7170 Optional<ScalarEvolution::ExitLimit> 7171 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7172 bool ExitIfTrue, bool ControlsExit, 7173 bool AllowPredicates) { 7174 (void)this->L; 7175 (void)this->ExitIfTrue; 7176 (void)this->AllowPredicates; 7177 7178 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7179 this->AllowPredicates == AllowPredicates && 7180 "Variance in assumed invariant key components!"); 7181 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7182 if (Itr == TripCountMap.end()) 7183 return None; 7184 return Itr->second; 7185 } 7186 7187 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7188 bool ExitIfTrue, 7189 bool ControlsExit, 7190 bool AllowPredicates, 7191 const ExitLimit &EL) { 7192 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7193 this->AllowPredicates == AllowPredicates && 7194 "Variance in assumed invariant key components!"); 7195 7196 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7197 assert(InsertResult.second && "Expected successful insertion!"); 7198 (void)InsertResult; 7199 (void)ExitIfTrue; 7200 } 7201 7202 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7203 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7204 bool ControlsExit, bool AllowPredicates) { 7205 7206 if (auto MaybeEL = 7207 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7208 return *MaybeEL; 7209 7210 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7211 ControlsExit, AllowPredicates); 7212 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7213 return EL; 7214 } 7215 7216 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7217 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7218 bool ControlsExit, bool AllowPredicates) { 7219 // Check if the controlling expression for this loop is an And or Or. 7220 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7221 if (BO->getOpcode() == Instruction::And) { 7222 // Recurse on the operands of the and. 7223 bool EitherMayExit = !ExitIfTrue; 7224 ExitLimit EL0 = computeExitLimitFromCondCached( 7225 Cache, L, BO->getOperand(0), ExitIfTrue, 7226 ControlsExit && !EitherMayExit, AllowPredicates); 7227 ExitLimit EL1 = computeExitLimitFromCondCached( 7228 Cache, L, BO->getOperand(1), ExitIfTrue, 7229 ControlsExit && !EitherMayExit, AllowPredicates); 7230 const SCEV *BECount = getCouldNotCompute(); 7231 const SCEV *MaxBECount = getCouldNotCompute(); 7232 if (EitherMayExit) { 7233 // Both conditions must be true for the loop to continue executing. 7234 // Choose the less conservative count. 7235 if (EL0.ExactNotTaken == getCouldNotCompute() || 7236 EL1.ExactNotTaken == getCouldNotCompute()) 7237 BECount = getCouldNotCompute(); 7238 else 7239 BECount = 7240 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7241 if (EL0.MaxNotTaken == getCouldNotCompute()) 7242 MaxBECount = EL1.MaxNotTaken; 7243 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7244 MaxBECount = EL0.MaxNotTaken; 7245 else 7246 MaxBECount = 7247 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7248 } else { 7249 // Both conditions must be true at the same time for the loop to exit. 7250 // For now, be conservative. 7251 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7252 MaxBECount = EL0.MaxNotTaken; 7253 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7254 BECount = EL0.ExactNotTaken; 7255 } 7256 7257 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7258 // to be more aggressive when computing BECount than when computing 7259 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7260 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7261 // to not. 7262 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7263 !isa<SCEVCouldNotCompute>(BECount)) 7264 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7265 7266 return ExitLimit(BECount, MaxBECount, false, 7267 {&EL0.Predicates, &EL1.Predicates}); 7268 } 7269 if (BO->getOpcode() == Instruction::Or) { 7270 // Recurse on the operands of the or. 7271 bool EitherMayExit = ExitIfTrue; 7272 ExitLimit EL0 = computeExitLimitFromCondCached( 7273 Cache, L, BO->getOperand(0), ExitIfTrue, 7274 ControlsExit && !EitherMayExit, AllowPredicates); 7275 ExitLimit EL1 = computeExitLimitFromCondCached( 7276 Cache, L, BO->getOperand(1), ExitIfTrue, 7277 ControlsExit && !EitherMayExit, AllowPredicates); 7278 const SCEV *BECount = getCouldNotCompute(); 7279 const SCEV *MaxBECount = getCouldNotCompute(); 7280 if (EitherMayExit) { 7281 // Both conditions must be false for the loop to continue executing. 7282 // Choose the less conservative count. 7283 if (EL0.ExactNotTaken == getCouldNotCompute() || 7284 EL1.ExactNotTaken == getCouldNotCompute()) 7285 BECount = getCouldNotCompute(); 7286 else 7287 BECount = 7288 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7289 if (EL0.MaxNotTaken == getCouldNotCompute()) 7290 MaxBECount = EL1.MaxNotTaken; 7291 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7292 MaxBECount = EL0.MaxNotTaken; 7293 else 7294 MaxBECount = 7295 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7296 } else { 7297 // Both conditions must be false at the same time for the loop to exit. 7298 // For now, be conservative. 7299 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7300 MaxBECount = EL0.MaxNotTaken; 7301 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7302 BECount = EL0.ExactNotTaken; 7303 } 7304 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7305 // to be more aggressive when computing BECount than when computing 7306 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7307 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7308 // to not. 7309 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7310 !isa<SCEVCouldNotCompute>(BECount)) 7311 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7312 7313 return ExitLimit(BECount, MaxBECount, false, 7314 {&EL0.Predicates, &EL1.Predicates}); 7315 } 7316 } 7317 7318 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7319 // Proceed to the next level to examine the icmp. 7320 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7321 ExitLimit EL = 7322 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7323 if (EL.hasFullInfo() || !AllowPredicates) 7324 return EL; 7325 7326 // Try again, but use SCEV predicates this time. 7327 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7328 /*AllowPredicates=*/true); 7329 } 7330 7331 // Check for a constant condition. These are normally stripped out by 7332 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7333 // preserve the CFG and is temporarily leaving constant conditions 7334 // in place. 7335 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7336 if (ExitIfTrue == !CI->getZExtValue()) 7337 // The backedge is always taken. 7338 return getCouldNotCompute(); 7339 else 7340 // The backedge is never taken. 7341 return getZero(CI->getType()); 7342 } 7343 7344 // If it's not an integer or pointer comparison then compute it the hard way. 7345 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7346 } 7347 7348 ScalarEvolution::ExitLimit 7349 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7350 ICmpInst *ExitCond, 7351 bool ExitIfTrue, 7352 bool ControlsExit, 7353 bool AllowPredicates) { 7354 // If the condition was exit on true, convert the condition to exit on false 7355 ICmpInst::Predicate Pred; 7356 if (!ExitIfTrue) 7357 Pred = ExitCond->getPredicate(); 7358 else 7359 Pred = ExitCond->getInversePredicate(); 7360 const ICmpInst::Predicate OriginalPred = Pred; 7361 7362 // Handle common loops like: for (X = "string"; *X; ++X) 7363 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7364 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7365 ExitLimit ItCnt = 7366 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7367 if (ItCnt.hasAnyInfo()) 7368 return ItCnt; 7369 } 7370 7371 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7372 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7373 7374 // Try to evaluate any dependencies out of the loop. 7375 LHS = getSCEVAtScope(LHS, L); 7376 RHS = getSCEVAtScope(RHS, L); 7377 7378 // At this point, we would like to compute how many iterations of the 7379 // loop the predicate will return true for these inputs. 7380 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7381 // If there is a loop-invariant, force it into the RHS. 7382 std::swap(LHS, RHS); 7383 Pred = ICmpInst::getSwappedPredicate(Pred); 7384 } 7385 7386 // Simplify the operands before analyzing them. 7387 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7388 7389 // If we have a comparison of a chrec against a constant, try to use value 7390 // ranges to answer this query. 7391 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7392 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7393 if (AddRec->getLoop() == L) { 7394 // Form the constant range. 7395 ConstantRange CompRange = 7396 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7397 7398 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7399 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7400 } 7401 7402 switch (Pred) { 7403 case ICmpInst::ICMP_NE: { // while (X != Y) 7404 // Convert to: while (X-Y != 0) 7405 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7406 AllowPredicates); 7407 if (EL.hasAnyInfo()) return EL; 7408 break; 7409 } 7410 case ICmpInst::ICMP_EQ: { // while (X == Y) 7411 // Convert to: while (X-Y == 0) 7412 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7413 if (EL.hasAnyInfo()) return EL; 7414 break; 7415 } 7416 case ICmpInst::ICMP_SLT: 7417 case ICmpInst::ICMP_ULT: { // while (X < Y) 7418 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7419 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7420 AllowPredicates); 7421 if (EL.hasAnyInfo()) return EL; 7422 break; 7423 } 7424 case ICmpInst::ICMP_SGT: 7425 case ICmpInst::ICMP_UGT: { // while (X > Y) 7426 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7427 ExitLimit EL = 7428 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7429 AllowPredicates); 7430 if (EL.hasAnyInfo()) return EL; 7431 break; 7432 } 7433 default: 7434 break; 7435 } 7436 7437 auto *ExhaustiveCount = 7438 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7439 7440 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7441 return ExhaustiveCount; 7442 7443 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7444 ExitCond->getOperand(1), L, OriginalPred); 7445 } 7446 7447 ScalarEvolution::ExitLimit 7448 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7449 SwitchInst *Switch, 7450 BasicBlock *ExitingBlock, 7451 bool ControlsExit) { 7452 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7453 7454 // Give up if the exit is the default dest of a switch. 7455 if (Switch->getDefaultDest() == ExitingBlock) 7456 return getCouldNotCompute(); 7457 7458 assert(L->contains(Switch->getDefaultDest()) && 7459 "Default case must not exit the loop!"); 7460 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7461 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7462 7463 // while (X != Y) --> while (X-Y != 0) 7464 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7465 if (EL.hasAnyInfo()) 7466 return EL; 7467 7468 return getCouldNotCompute(); 7469 } 7470 7471 static ConstantInt * 7472 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7473 ScalarEvolution &SE) { 7474 const SCEV *InVal = SE.getConstant(C); 7475 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7476 assert(isa<SCEVConstant>(Val) && 7477 "Evaluation of SCEV at constant didn't fold correctly?"); 7478 return cast<SCEVConstant>(Val)->getValue(); 7479 } 7480 7481 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7482 /// compute the backedge execution count. 7483 ScalarEvolution::ExitLimit 7484 ScalarEvolution::computeLoadConstantCompareExitLimit( 7485 LoadInst *LI, 7486 Constant *RHS, 7487 const Loop *L, 7488 ICmpInst::Predicate predicate) { 7489 if (LI->isVolatile()) return getCouldNotCompute(); 7490 7491 // Check to see if the loaded pointer is a getelementptr of a global. 7492 // TODO: Use SCEV instead of manually grubbing with GEPs. 7493 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7494 if (!GEP) return getCouldNotCompute(); 7495 7496 // Make sure that it is really a constant global we are gepping, with an 7497 // initializer, and make sure the first IDX is really 0. 7498 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7499 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7500 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7501 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7502 return getCouldNotCompute(); 7503 7504 // Okay, we allow one non-constant index into the GEP instruction. 7505 Value *VarIdx = nullptr; 7506 std::vector<Constant*> Indexes; 7507 unsigned VarIdxNum = 0; 7508 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7509 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7510 Indexes.push_back(CI); 7511 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7512 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7513 VarIdx = GEP->getOperand(i); 7514 VarIdxNum = i-2; 7515 Indexes.push_back(nullptr); 7516 } 7517 7518 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7519 if (!VarIdx) 7520 return getCouldNotCompute(); 7521 7522 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7523 // Check to see if X is a loop variant variable value now. 7524 const SCEV *Idx = getSCEV(VarIdx); 7525 Idx = getSCEVAtScope(Idx, L); 7526 7527 // We can only recognize very limited forms of loop index expressions, in 7528 // particular, only affine AddRec's like {C1,+,C2}. 7529 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7530 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7531 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7532 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7533 return getCouldNotCompute(); 7534 7535 unsigned MaxSteps = MaxBruteForceIterations; 7536 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7537 ConstantInt *ItCst = ConstantInt::get( 7538 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7539 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7540 7541 // Form the GEP offset. 7542 Indexes[VarIdxNum] = Val; 7543 7544 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7545 Indexes); 7546 if (!Result) break; // Cannot compute! 7547 7548 // Evaluate the condition for this iteration. 7549 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7550 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7551 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7552 ++NumArrayLenItCounts; 7553 return getConstant(ItCst); // Found terminating iteration! 7554 } 7555 } 7556 return getCouldNotCompute(); 7557 } 7558 7559 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7560 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7561 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7562 if (!RHS) 7563 return getCouldNotCompute(); 7564 7565 const BasicBlock *Latch = L->getLoopLatch(); 7566 if (!Latch) 7567 return getCouldNotCompute(); 7568 7569 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7570 if (!Predecessor) 7571 return getCouldNotCompute(); 7572 7573 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7574 // Return LHS in OutLHS and shift_opt in OutOpCode. 7575 auto MatchPositiveShift = 7576 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7577 7578 using namespace PatternMatch; 7579 7580 ConstantInt *ShiftAmt; 7581 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7582 OutOpCode = Instruction::LShr; 7583 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7584 OutOpCode = Instruction::AShr; 7585 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7586 OutOpCode = Instruction::Shl; 7587 else 7588 return false; 7589 7590 return ShiftAmt->getValue().isStrictlyPositive(); 7591 }; 7592 7593 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7594 // 7595 // loop: 7596 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7597 // %iv.shifted = lshr i32 %iv, <positive constant> 7598 // 7599 // Return true on a successful match. Return the corresponding PHI node (%iv 7600 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7601 auto MatchShiftRecurrence = 7602 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7603 Optional<Instruction::BinaryOps> PostShiftOpCode; 7604 7605 { 7606 Instruction::BinaryOps OpC; 7607 Value *V; 7608 7609 // If we encounter a shift instruction, "peel off" the shift operation, 7610 // and remember that we did so. Later when we inspect %iv's backedge 7611 // value, we will make sure that the backedge value uses the same 7612 // operation. 7613 // 7614 // Note: the peeled shift operation does not have to be the same 7615 // instruction as the one feeding into the PHI's backedge value. We only 7616 // really care about it being the same *kind* of shift instruction -- 7617 // that's all that is required for our later inferences to hold. 7618 if (MatchPositiveShift(LHS, V, OpC)) { 7619 PostShiftOpCode = OpC; 7620 LHS = V; 7621 } 7622 } 7623 7624 PNOut = dyn_cast<PHINode>(LHS); 7625 if (!PNOut || PNOut->getParent() != L->getHeader()) 7626 return false; 7627 7628 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7629 Value *OpLHS; 7630 7631 return 7632 // The backedge value for the PHI node must be a shift by a positive 7633 // amount 7634 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7635 7636 // of the PHI node itself 7637 OpLHS == PNOut && 7638 7639 // and the kind of shift should be match the kind of shift we peeled 7640 // off, if any. 7641 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7642 }; 7643 7644 PHINode *PN; 7645 Instruction::BinaryOps OpCode; 7646 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7647 return getCouldNotCompute(); 7648 7649 const DataLayout &DL = getDataLayout(); 7650 7651 // The key rationale for this optimization is that for some kinds of shift 7652 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7653 // within a finite number of iterations. If the condition guarding the 7654 // backedge (in the sense that the backedge is taken if the condition is true) 7655 // is false for the value the shift recurrence stabilizes to, then we know 7656 // that the backedge is taken only a finite number of times. 7657 7658 ConstantInt *StableValue = nullptr; 7659 switch (OpCode) { 7660 default: 7661 llvm_unreachable("Impossible case!"); 7662 7663 case Instruction::AShr: { 7664 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7665 // bitwidth(K) iterations. 7666 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7667 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7668 Predecessor->getTerminator(), &DT); 7669 auto *Ty = cast<IntegerType>(RHS->getType()); 7670 if (Known.isNonNegative()) 7671 StableValue = ConstantInt::get(Ty, 0); 7672 else if (Known.isNegative()) 7673 StableValue = ConstantInt::get(Ty, -1, true); 7674 else 7675 return getCouldNotCompute(); 7676 7677 break; 7678 } 7679 case Instruction::LShr: 7680 case Instruction::Shl: 7681 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7682 // stabilize to 0 in at most bitwidth(K) iterations. 7683 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7684 break; 7685 } 7686 7687 auto *Result = 7688 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7689 assert(Result->getType()->isIntegerTy(1) && 7690 "Otherwise cannot be an operand to a branch instruction"); 7691 7692 if (Result->isZeroValue()) { 7693 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7694 const SCEV *UpperBound = 7695 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7696 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7697 } 7698 7699 return getCouldNotCompute(); 7700 } 7701 7702 /// Return true if we can constant fold an instruction of the specified type, 7703 /// assuming that all operands were constants. 7704 static bool CanConstantFold(const Instruction *I) { 7705 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7706 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7707 isa<LoadInst>(I)) 7708 return true; 7709 7710 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7711 if (const Function *F = CI->getCalledFunction()) 7712 return canConstantFoldCallTo(CI, F); 7713 return false; 7714 } 7715 7716 /// Determine whether this instruction can constant evolve within this loop 7717 /// assuming its operands can all constant evolve. 7718 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7719 // An instruction outside of the loop can't be derived from a loop PHI. 7720 if (!L->contains(I)) return false; 7721 7722 if (isa<PHINode>(I)) { 7723 // We don't currently keep track of the control flow needed to evaluate 7724 // PHIs, so we cannot handle PHIs inside of loops. 7725 return L->getHeader() == I->getParent(); 7726 } 7727 7728 // If we won't be able to constant fold this expression even if the operands 7729 // are constants, bail early. 7730 return CanConstantFold(I); 7731 } 7732 7733 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7734 /// recursing through each instruction operand until reaching a loop header phi. 7735 static PHINode * 7736 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7737 DenseMap<Instruction *, PHINode *> &PHIMap, 7738 unsigned Depth) { 7739 if (Depth > MaxConstantEvolvingDepth) 7740 return nullptr; 7741 7742 // Otherwise, we can evaluate this instruction if all of its operands are 7743 // constant or derived from a PHI node themselves. 7744 PHINode *PHI = nullptr; 7745 for (Value *Op : UseInst->operands()) { 7746 if (isa<Constant>(Op)) continue; 7747 7748 Instruction *OpInst = dyn_cast<Instruction>(Op); 7749 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7750 7751 PHINode *P = dyn_cast<PHINode>(OpInst); 7752 if (!P) 7753 // If this operand is already visited, reuse the prior result. 7754 // We may have P != PHI if this is the deepest point at which the 7755 // inconsistent paths meet. 7756 P = PHIMap.lookup(OpInst); 7757 if (!P) { 7758 // Recurse and memoize the results, whether a phi is found or not. 7759 // This recursive call invalidates pointers into PHIMap. 7760 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7761 PHIMap[OpInst] = P; 7762 } 7763 if (!P) 7764 return nullptr; // Not evolving from PHI 7765 if (PHI && PHI != P) 7766 return nullptr; // Evolving from multiple different PHIs. 7767 PHI = P; 7768 } 7769 // This is a expression evolving from a constant PHI! 7770 return PHI; 7771 } 7772 7773 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7774 /// in the loop that V is derived from. We allow arbitrary operations along the 7775 /// way, but the operands of an operation must either be constants or a value 7776 /// derived from a constant PHI. If this expression does not fit with these 7777 /// constraints, return null. 7778 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7779 Instruction *I = dyn_cast<Instruction>(V); 7780 if (!I || !canConstantEvolve(I, L)) return nullptr; 7781 7782 if (PHINode *PN = dyn_cast<PHINode>(I)) 7783 return PN; 7784 7785 // Record non-constant instructions contained by the loop. 7786 DenseMap<Instruction *, PHINode *> PHIMap; 7787 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7788 } 7789 7790 /// EvaluateExpression - Given an expression that passes the 7791 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7792 /// in the loop has the value PHIVal. If we can't fold this expression for some 7793 /// reason, return null. 7794 static Constant *EvaluateExpression(Value *V, const Loop *L, 7795 DenseMap<Instruction *, Constant *> &Vals, 7796 const DataLayout &DL, 7797 const TargetLibraryInfo *TLI) { 7798 // Convenient constant check, but redundant for recursive calls. 7799 if (Constant *C = dyn_cast<Constant>(V)) return C; 7800 Instruction *I = dyn_cast<Instruction>(V); 7801 if (!I) return nullptr; 7802 7803 if (Constant *C = Vals.lookup(I)) return C; 7804 7805 // An instruction inside the loop depends on a value outside the loop that we 7806 // weren't given a mapping for, or a value such as a call inside the loop. 7807 if (!canConstantEvolve(I, L)) return nullptr; 7808 7809 // An unmapped PHI can be due to a branch or another loop inside this loop, 7810 // or due to this not being the initial iteration through a loop where we 7811 // couldn't compute the evolution of this particular PHI last time. 7812 if (isa<PHINode>(I)) return nullptr; 7813 7814 std::vector<Constant*> Operands(I->getNumOperands()); 7815 7816 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7817 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7818 if (!Operand) { 7819 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7820 if (!Operands[i]) return nullptr; 7821 continue; 7822 } 7823 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7824 Vals[Operand] = C; 7825 if (!C) return nullptr; 7826 Operands[i] = C; 7827 } 7828 7829 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7830 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7831 Operands[1], DL, TLI); 7832 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7833 if (!LI->isVolatile()) 7834 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7835 } 7836 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7837 } 7838 7839 7840 // If every incoming value to PN except the one for BB is a specific Constant, 7841 // return that, else return nullptr. 7842 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7843 Constant *IncomingVal = nullptr; 7844 7845 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7846 if (PN->getIncomingBlock(i) == BB) 7847 continue; 7848 7849 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7850 if (!CurrentVal) 7851 return nullptr; 7852 7853 if (IncomingVal != CurrentVal) { 7854 if (IncomingVal) 7855 return nullptr; 7856 IncomingVal = CurrentVal; 7857 } 7858 } 7859 7860 return IncomingVal; 7861 } 7862 7863 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7864 /// in the header of its containing loop, we know the loop executes a 7865 /// constant number of times, and the PHI node is just a recurrence 7866 /// involving constants, fold it. 7867 Constant * 7868 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7869 const APInt &BEs, 7870 const Loop *L) { 7871 auto I = ConstantEvolutionLoopExitValue.find(PN); 7872 if (I != ConstantEvolutionLoopExitValue.end()) 7873 return I->second; 7874 7875 if (BEs.ugt(MaxBruteForceIterations)) 7876 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7877 7878 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7879 7880 DenseMap<Instruction *, Constant *> CurrentIterVals; 7881 BasicBlock *Header = L->getHeader(); 7882 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7883 7884 BasicBlock *Latch = L->getLoopLatch(); 7885 if (!Latch) 7886 return nullptr; 7887 7888 for (PHINode &PHI : Header->phis()) { 7889 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7890 CurrentIterVals[&PHI] = StartCST; 7891 } 7892 if (!CurrentIterVals.count(PN)) 7893 return RetVal = nullptr; 7894 7895 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7896 7897 // Execute the loop symbolically to determine the exit value. 7898 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7899 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7900 7901 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7902 unsigned IterationNum = 0; 7903 const DataLayout &DL = getDataLayout(); 7904 for (; ; ++IterationNum) { 7905 if (IterationNum == NumIterations) 7906 return RetVal = CurrentIterVals[PN]; // Got exit value! 7907 7908 // Compute the value of the PHIs for the next iteration. 7909 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7910 DenseMap<Instruction *, Constant *> NextIterVals; 7911 Constant *NextPHI = 7912 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7913 if (!NextPHI) 7914 return nullptr; // Couldn't evaluate! 7915 NextIterVals[PN] = NextPHI; 7916 7917 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7918 7919 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7920 // cease to be able to evaluate one of them or if they stop evolving, 7921 // because that doesn't necessarily prevent us from computing PN. 7922 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7923 for (const auto &I : CurrentIterVals) { 7924 PHINode *PHI = dyn_cast<PHINode>(I.first); 7925 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7926 PHIsToCompute.emplace_back(PHI, I.second); 7927 } 7928 // We use two distinct loops because EvaluateExpression may invalidate any 7929 // iterators into CurrentIterVals. 7930 for (const auto &I : PHIsToCompute) { 7931 PHINode *PHI = I.first; 7932 Constant *&NextPHI = NextIterVals[PHI]; 7933 if (!NextPHI) { // Not already computed. 7934 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7935 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7936 } 7937 if (NextPHI != I.second) 7938 StoppedEvolving = false; 7939 } 7940 7941 // If all entries in CurrentIterVals == NextIterVals then we can stop 7942 // iterating, the loop can't continue to change. 7943 if (StoppedEvolving) 7944 return RetVal = CurrentIterVals[PN]; 7945 7946 CurrentIterVals.swap(NextIterVals); 7947 } 7948 } 7949 7950 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7951 Value *Cond, 7952 bool ExitWhen) { 7953 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7954 if (!PN) return getCouldNotCompute(); 7955 7956 // If the loop is canonicalized, the PHI will have exactly two entries. 7957 // That's the only form we support here. 7958 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7959 7960 DenseMap<Instruction *, Constant *> CurrentIterVals; 7961 BasicBlock *Header = L->getHeader(); 7962 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7963 7964 BasicBlock *Latch = L->getLoopLatch(); 7965 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7966 7967 for (PHINode &PHI : Header->phis()) { 7968 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7969 CurrentIterVals[&PHI] = StartCST; 7970 } 7971 if (!CurrentIterVals.count(PN)) 7972 return getCouldNotCompute(); 7973 7974 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7975 // the loop symbolically to determine when the condition gets a value of 7976 // "ExitWhen". 7977 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7978 const DataLayout &DL = getDataLayout(); 7979 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7980 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7981 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7982 7983 // Couldn't symbolically evaluate. 7984 if (!CondVal) return getCouldNotCompute(); 7985 7986 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7987 ++NumBruteForceTripCountsComputed; 7988 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7989 } 7990 7991 // Update all the PHI nodes for the next iteration. 7992 DenseMap<Instruction *, Constant *> NextIterVals; 7993 7994 // Create a list of which PHIs we need to compute. We want to do this before 7995 // calling EvaluateExpression on them because that may invalidate iterators 7996 // into CurrentIterVals. 7997 SmallVector<PHINode *, 8> PHIsToCompute; 7998 for (const auto &I : CurrentIterVals) { 7999 PHINode *PHI = dyn_cast<PHINode>(I.first); 8000 if (!PHI || PHI->getParent() != Header) continue; 8001 PHIsToCompute.push_back(PHI); 8002 } 8003 for (PHINode *PHI : PHIsToCompute) { 8004 Constant *&NextPHI = NextIterVals[PHI]; 8005 if (NextPHI) continue; // Already computed! 8006 8007 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8008 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8009 } 8010 CurrentIterVals.swap(NextIterVals); 8011 } 8012 8013 // Too many iterations were needed to evaluate. 8014 return getCouldNotCompute(); 8015 } 8016 8017 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8018 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8019 ValuesAtScopes[V]; 8020 // Check to see if we've folded this expression at this loop before. 8021 for (auto &LS : Values) 8022 if (LS.first == L) 8023 return LS.second ? LS.second : V; 8024 8025 Values.emplace_back(L, nullptr); 8026 8027 // Otherwise compute it. 8028 const SCEV *C = computeSCEVAtScope(V, L); 8029 for (auto &LS : reverse(ValuesAtScopes[V])) 8030 if (LS.first == L) { 8031 LS.second = C; 8032 break; 8033 } 8034 return C; 8035 } 8036 8037 /// This builds up a Constant using the ConstantExpr interface. That way, we 8038 /// will return Constants for objects which aren't represented by a 8039 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8040 /// Returns NULL if the SCEV isn't representable as a Constant. 8041 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8042 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 8043 case scCouldNotCompute: 8044 case scAddRecExpr: 8045 break; 8046 case scConstant: 8047 return cast<SCEVConstant>(V)->getValue(); 8048 case scUnknown: 8049 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8050 case scSignExtend: { 8051 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8052 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8053 return ConstantExpr::getSExt(CastOp, SS->getType()); 8054 break; 8055 } 8056 case scZeroExtend: { 8057 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8058 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8059 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8060 break; 8061 } 8062 case scTruncate: { 8063 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8064 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8065 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8066 break; 8067 } 8068 case scAddExpr: { 8069 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8070 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8071 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8072 unsigned AS = PTy->getAddressSpace(); 8073 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8074 C = ConstantExpr::getBitCast(C, DestPtrTy); 8075 } 8076 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8077 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8078 if (!C2) return nullptr; 8079 8080 // First pointer! 8081 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8082 unsigned AS = C2->getType()->getPointerAddressSpace(); 8083 std::swap(C, C2); 8084 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8085 // The offsets have been converted to bytes. We can add bytes to an 8086 // i8* by GEP with the byte count in the first index. 8087 C = ConstantExpr::getBitCast(C, DestPtrTy); 8088 } 8089 8090 // Don't bother trying to sum two pointers. We probably can't 8091 // statically compute a load that results from it anyway. 8092 if (C2->getType()->isPointerTy()) 8093 return nullptr; 8094 8095 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8096 if (PTy->getElementType()->isStructTy()) 8097 C2 = ConstantExpr::getIntegerCast( 8098 C2, Type::getInt32Ty(C->getContext()), true); 8099 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8100 } else 8101 C = ConstantExpr::getAdd(C, C2); 8102 } 8103 return C; 8104 } 8105 break; 8106 } 8107 case scMulExpr: { 8108 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8109 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8110 // Don't bother with pointers at all. 8111 if (C->getType()->isPointerTy()) return nullptr; 8112 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8113 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8114 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8115 C = ConstantExpr::getMul(C, C2); 8116 } 8117 return C; 8118 } 8119 break; 8120 } 8121 case scUDivExpr: { 8122 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8123 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8124 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8125 if (LHS->getType() == RHS->getType()) 8126 return ConstantExpr::getUDiv(LHS, RHS); 8127 break; 8128 } 8129 case scSMaxExpr: 8130 case scUMaxExpr: 8131 break; // TODO: smax, umax. 8132 } 8133 return nullptr; 8134 } 8135 8136 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8137 if (isa<SCEVConstant>(V)) return V; 8138 8139 // If this instruction is evolved from a constant-evolving PHI, compute the 8140 // exit value from the loop without using SCEVs. 8141 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8142 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8143 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8144 const Loop *LI = this->LI[I->getParent()]; 8145 // Looking for loop exit value. 8146 if (LI && LI->getParentLoop() == L && 8147 PN->getParent() == LI->getHeader()) { 8148 // Okay, there is no closed form solution for the PHI node. Check 8149 // to see if the loop that contains it has a known backedge-taken 8150 // count. If so, we may be able to force computation of the exit 8151 // value. 8152 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8153 if (const SCEVConstant *BTCC = 8154 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8155 8156 // This trivial case can show up in some degenerate cases where 8157 // the incoming IR has not yet been fully simplified. 8158 if (BTCC->getValue()->isZero()) { 8159 Value *InitValue = nullptr; 8160 bool MultipleInitValues = false; 8161 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8162 if (!LI->contains(PN->getIncomingBlock(i))) { 8163 if (!InitValue) 8164 InitValue = PN->getIncomingValue(i); 8165 else if (InitValue != PN->getIncomingValue(i)) { 8166 MultipleInitValues = true; 8167 break; 8168 } 8169 } 8170 if (!MultipleInitValues && InitValue) 8171 return getSCEV(InitValue); 8172 } 8173 } 8174 // Okay, we know how many times the containing loop executes. If 8175 // this is a constant evolving PHI node, get the final value at 8176 // the specified iteration number. 8177 Constant *RV = 8178 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8179 if (RV) return getSCEV(RV); 8180 } 8181 } 8182 } 8183 8184 // Okay, this is an expression that we cannot symbolically evaluate 8185 // into a SCEV. Check to see if it's possible to symbolically evaluate 8186 // the arguments into constants, and if so, try to constant propagate the 8187 // result. This is particularly useful for computing loop exit values. 8188 if (CanConstantFold(I)) { 8189 SmallVector<Constant *, 4> Operands; 8190 bool MadeImprovement = false; 8191 for (Value *Op : I->operands()) { 8192 if (Constant *C = dyn_cast<Constant>(Op)) { 8193 Operands.push_back(C); 8194 continue; 8195 } 8196 8197 // If any of the operands is non-constant and if they are 8198 // non-integer and non-pointer, don't even try to analyze them 8199 // with scev techniques. 8200 if (!isSCEVable(Op->getType())) 8201 return V; 8202 8203 const SCEV *OrigV = getSCEV(Op); 8204 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8205 MadeImprovement |= OrigV != OpV; 8206 8207 Constant *C = BuildConstantFromSCEV(OpV); 8208 if (!C) return V; 8209 if (C->getType() != Op->getType()) 8210 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8211 Op->getType(), 8212 false), 8213 C, Op->getType()); 8214 Operands.push_back(C); 8215 } 8216 8217 // Check to see if getSCEVAtScope actually made an improvement. 8218 if (MadeImprovement) { 8219 Constant *C = nullptr; 8220 const DataLayout &DL = getDataLayout(); 8221 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8222 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8223 Operands[1], DL, &TLI); 8224 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8225 if (!LI->isVolatile()) 8226 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8227 } else 8228 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8229 if (!C) return V; 8230 return getSCEV(C); 8231 } 8232 } 8233 } 8234 8235 // This is some other type of SCEVUnknown, just return it. 8236 return V; 8237 } 8238 8239 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8240 // Avoid performing the look-up in the common case where the specified 8241 // expression has no loop-variant portions. 8242 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8243 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8244 if (OpAtScope != Comm->getOperand(i)) { 8245 // Okay, at least one of these operands is loop variant but might be 8246 // foldable. Build a new instance of the folded commutative expression. 8247 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8248 Comm->op_begin()+i); 8249 NewOps.push_back(OpAtScope); 8250 8251 for (++i; i != e; ++i) { 8252 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8253 NewOps.push_back(OpAtScope); 8254 } 8255 if (isa<SCEVAddExpr>(Comm)) 8256 return getAddExpr(NewOps); 8257 if (isa<SCEVMulExpr>(Comm)) 8258 return getMulExpr(NewOps); 8259 if (isa<SCEVSMaxExpr>(Comm)) 8260 return getSMaxExpr(NewOps); 8261 if (isa<SCEVUMaxExpr>(Comm)) 8262 return getUMaxExpr(NewOps); 8263 llvm_unreachable("Unknown commutative SCEV type!"); 8264 } 8265 } 8266 // If we got here, all operands are loop invariant. 8267 return Comm; 8268 } 8269 8270 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8271 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8272 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8273 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8274 return Div; // must be loop invariant 8275 return getUDivExpr(LHS, RHS); 8276 } 8277 8278 // If this is a loop recurrence for a loop that does not contain L, then we 8279 // are dealing with the final value computed by the loop. 8280 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8281 // First, attempt to evaluate each operand. 8282 // Avoid performing the look-up in the common case where the specified 8283 // expression has no loop-variant portions. 8284 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8285 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8286 if (OpAtScope == AddRec->getOperand(i)) 8287 continue; 8288 8289 // Okay, at least one of these operands is loop variant but might be 8290 // foldable. Build a new instance of the folded commutative expression. 8291 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8292 AddRec->op_begin()+i); 8293 NewOps.push_back(OpAtScope); 8294 for (++i; i != e; ++i) 8295 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8296 8297 const SCEV *FoldedRec = 8298 getAddRecExpr(NewOps, AddRec->getLoop(), 8299 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8300 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8301 // The addrec may be folded to a nonrecurrence, for example, if the 8302 // induction variable is multiplied by zero after constant folding. Go 8303 // ahead and return the folded value. 8304 if (!AddRec) 8305 return FoldedRec; 8306 break; 8307 } 8308 8309 // If the scope is outside the addrec's loop, evaluate it by using the 8310 // loop exit value of the addrec. 8311 if (!AddRec->getLoop()->contains(L)) { 8312 // To evaluate this recurrence, we need to know how many times the AddRec 8313 // loop iterates. Compute this now. 8314 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8315 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8316 8317 // Then, evaluate the AddRec. 8318 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8319 } 8320 8321 return AddRec; 8322 } 8323 8324 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8325 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8326 if (Op == Cast->getOperand()) 8327 return Cast; // must be loop invariant 8328 return getZeroExtendExpr(Op, Cast->getType()); 8329 } 8330 8331 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8332 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8333 if (Op == Cast->getOperand()) 8334 return Cast; // must be loop invariant 8335 return getSignExtendExpr(Op, Cast->getType()); 8336 } 8337 8338 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8339 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8340 if (Op == Cast->getOperand()) 8341 return Cast; // must be loop invariant 8342 return getTruncateExpr(Op, Cast->getType()); 8343 } 8344 8345 llvm_unreachable("Unknown SCEV type!"); 8346 } 8347 8348 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8349 return getSCEVAtScope(getSCEV(V), L); 8350 } 8351 8352 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8353 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8354 return stripInjectiveFunctions(ZExt->getOperand()); 8355 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8356 return stripInjectiveFunctions(SExt->getOperand()); 8357 return S; 8358 } 8359 8360 /// Finds the minimum unsigned root of the following equation: 8361 /// 8362 /// A * X = B (mod N) 8363 /// 8364 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8365 /// A and B isn't important. 8366 /// 8367 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8368 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8369 ScalarEvolution &SE) { 8370 uint32_t BW = A.getBitWidth(); 8371 assert(BW == SE.getTypeSizeInBits(B->getType())); 8372 assert(A != 0 && "A must be non-zero."); 8373 8374 // 1. D = gcd(A, N) 8375 // 8376 // The gcd of A and N may have only one prime factor: 2. The number of 8377 // trailing zeros in A is its multiplicity 8378 uint32_t Mult2 = A.countTrailingZeros(); 8379 // D = 2^Mult2 8380 8381 // 2. Check if B is divisible by D. 8382 // 8383 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8384 // is not less than multiplicity of this prime factor for D. 8385 if (SE.GetMinTrailingZeros(B) < Mult2) 8386 return SE.getCouldNotCompute(); 8387 8388 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8389 // modulo (N / D). 8390 // 8391 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8392 // (N / D) in general. The inverse itself always fits into BW bits, though, 8393 // so we immediately truncate it. 8394 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8395 APInt Mod(BW + 1, 0); 8396 Mod.setBit(BW - Mult2); // Mod = N / D 8397 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8398 8399 // 4. Compute the minimum unsigned root of the equation: 8400 // I * (B / D) mod (N / D) 8401 // To simplify the computation, we factor out the divide by D: 8402 // (I * B mod N) / D 8403 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8404 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8405 } 8406 8407 /// For a given quadratic addrec, generate coefficients of the corresponding 8408 /// quadratic equation, multiplied by a common value to ensure that they are 8409 /// integers. 8410 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8411 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8412 /// were multiplied by, and BitWidth is the bit width of the original addrec 8413 /// coefficients. 8414 /// This function returns None if the addrec coefficients are not compile- 8415 /// time constants. 8416 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8417 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8418 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8419 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8420 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8421 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8422 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8423 << *AddRec << '\n'); 8424 8425 // We currently can only solve this if the coefficients are constants. 8426 if (!LC || !MC || !NC) { 8427 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8428 return None; 8429 } 8430 8431 APInt L = LC->getAPInt(); 8432 APInt M = MC->getAPInt(); 8433 APInt N = NC->getAPInt(); 8434 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8435 8436 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8437 unsigned NewWidth = BitWidth + 1; 8438 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8439 << BitWidth << '\n'); 8440 // The sign-extension (as opposed to a zero-extension) here matches the 8441 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8442 N = N.sext(NewWidth); 8443 M = M.sext(NewWidth); 8444 L = L.sext(NewWidth); 8445 8446 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8447 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8448 // L+M, L+2M+N, L+3M+3N, ... 8449 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8450 // 8451 // The equation Acc = 0 is then 8452 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8453 // In a quadratic form it becomes: 8454 // N n^2 + (2M-N) n + 2L = 0. 8455 8456 APInt A = N; 8457 APInt B = 2 * M - A; 8458 APInt C = 2 * L; 8459 APInt T = APInt(NewWidth, 2); 8460 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8461 << "x + " << C << ", coeff bw: " << NewWidth 8462 << ", multiplied by " << T << '\n'); 8463 return std::make_tuple(A, B, C, T, BitWidth); 8464 } 8465 8466 /// Helper function to compare optional APInts: 8467 /// (a) if X and Y both exist, return min(X, Y), 8468 /// (b) if neither X nor Y exist, return None, 8469 /// (c) if exactly one of X and Y exists, return that value. 8470 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8471 if (X.hasValue() && Y.hasValue()) { 8472 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8473 APInt XW = X->sextOrSelf(W); 8474 APInt YW = Y->sextOrSelf(W); 8475 return XW.slt(YW) ? *X : *Y; 8476 } 8477 if (!X.hasValue() && !Y.hasValue()) 8478 return None; 8479 return X.hasValue() ? *X : *Y; 8480 } 8481 8482 /// Helper function to truncate an optional APInt to a given BitWidth. 8483 /// When solving addrec-related equations, it is preferable to return a value 8484 /// that has the same bit width as the original addrec's coefficients. If the 8485 /// solution fits in the original bit width, truncate it (except for i1). 8486 /// Returning a value of a different bit width may inhibit some optimizations. 8487 /// 8488 /// In general, a solution to a quadratic equation generated from an addrec 8489 /// may require BW+1 bits, where BW is the bit width of the addrec's 8490 /// coefficients. The reason is that the coefficients of the quadratic 8491 /// equation are BW+1 bits wide (to avoid truncation when converting from 8492 /// the addrec to the equation). 8493 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8494 if (!X.hasValue()) 8495 return None; 8496 unsigned W = X->getBitWidth(); 8497 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8498 return X->trunc(BitWidth); 8499 return X; 8500 } 8501 8502 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8503 /// iterations. The values L, M, N are assumed to be signed, and they 8504 /// should all have the same bit widths. 8505 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8506 /// where BW is the bit width of the addrec's coefficients. 8507 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8508 /// returned as such, otherwise the bit width of the returned value may 8509 /// be greater than BW. 8510 /// 8511 /// This function returns None if 8512 /// (a) the addrec coefficients are not constant, or 8513 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8514 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8515 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8516 static Optional<APInt> 8517 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8518 APInt A, B, C, M; 8519 unsigned BitWidth; 8520 auto T = GetQuadraticEquation(AddRec); 8521 if (!T.hasValue()) 8522 return None; 8523 8524 std::tie(A, B, C, M, BitWidth) = *T; 8525 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8526 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8527 if (!X.hasValue()) 8528 return None; 8529 8530 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8531 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8532 if (!V->isZero()) 8533 return None; 8534 8535 return TruncIfPossible(X, BitWidth); 8536 } 8537 8538 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8539 /// iterations. The values M, N are assumed to be signed, and they 8540 /// should all have the same bit widths. 8541 /// Find the least n such that c(n) does not belong to the given range, 8542 /// while c(n-1) does. 8543 /// 8544 /// This function returns None if 8545 /// (a) the addrec coefficients are not constant, or 8546 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8547 /// bounds of the range. 8548 static Optional<APInt> 8549 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8550 const ConstantRange &Range, ScalarEvolution &SE) { 8551 assert(AddRec->getOperand(0)->isZero() && 8552 "Starting value of addrec should be 0"); 8553 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8554 << Range << ", addrec " << *AddRec << '\n'); 8555 // This case is handled in getNumIterationsInRange. Here we can assume that 8556 // we start in the range. 8557 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8558 "Addrec's initial value should be in range"); 8559 8560 APInt A, B, C, M; 8561 unsigned BitWidth; 8562 auto T = GetQuadraticEquation(AddRec); 8563 if (!T.hasValue()) 8564 return None; 8565 8566 // Be careful about the return value: there can be two reasons for not 8567 // returning an actual number. First, if no solutions to the equations 8568 // were found, and second, if the solutions don't leave the given range. 8569 // The first case means that the actual solution is "unknown", the second 8570 // means that it's known, but not valid. If the solution is unknown, we 8571 // cannot make any conclusions. 8572 // Return a pair: the optional solution and a flag indicating if the 8573 // solution was found. 8574 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8575 // Solve for signed overflow and unsigned overflow, pick the lower 8576 // solution. 8577 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8578 << Bound << " (before multiplying by " << M << ")\n"); 8579 Bound *= M; // The quadratic equation multiplier. 8580 8581 Optional<APInt> SO = None; 8582 if (BitWidth > 1) { 8583 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8584 "signed overflow\n"); 8585 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8586 } 8587 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8588 "unsigned overflow\n"); 8589 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8590 BitWidth+1); 8591 8592 auto LeavesRange = [&] (const APInt &X) { 8593 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8594 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8595 if (Range.contains(V0->getValue())) 8596 return false; 8597 // X should be at least 1, so X-1 is non-negative. 8598 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8599 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8600 if (Range.contains(V1->getValue())) 8601 return true; 8602 return false; 8603 }; 8604 8605 // If SolveQuadraticEquationWrap returns None, it means that there can 8606 // be a solution, but the function failed to find it. We cannot treat it 8607 // as "no solution". 8608 if (!SO.hasValue() || !UO.hasValue()) 8609 return { None, false }; 8610 8611 // Check the smaller value first to see if it leaves the range. 8612 // At this point, both SO and UO must have values. 8613 Optional<APInt> Min = MinOptional(SO, UO); 8614 if (LeavesRange(*Min)) 8615 return { Min, true }; 8616 Optional<APInt> Max = Min == SO ? UO : SO; 8617 if (LeavesRange(*Max)) 8618 return { Max, true }; 8619 8620 // Solutions were found, but were eliminated, hence the "true". 8621 return { None, true }; 8622 }; 8623 8624 std::tie(A, B, C, M, BitWidth) = *T; 8625 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8626 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8627 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8628 auto SL = SolveForBoundary(Lower); 8629 auto SU = SolveForBoundary(Upper); 8630 // If any of the solutions was unknown, no meaninigful conclusions can 8631 // be made. 8632 if (!SL.second || !SU.second) 8633 return None; 8634 8635 // Claim: The correct solution is not some value between Min and Max. 8636 // 8637 // Justification: Assuming that Min and Max are different values, one of 8638 // them is when the first signed overflow happens, the other is when the 8639 // first unsigned overflow happens. Crossing the range boundary is only 8640 // possible via an overflow (treating 0 as a special case of it, modeling 8641 // an overflow as crossing k*2^W for some k). 8642 // 8643 // The interesting case here is when Min was eliminated as an invalid 8644 // solution, but Max was not. The argument is that if there was another 8645 // overflow between Min and Max, it would also have been eliminated if 8646 // it was considered. 8647 // 8648 // For a given boundary, it is possible to have two overflows of the same 8649 // type (signed/unsigned) without having the other type in between: this 8650 // can happen when the vertex of the parabola is between the iterations 8651 // corresponding to the overflows. This is only possible when the two 8652 // overflows cross k*2^W for the same k. In such case, if the second one 8653 // left the range (and was the first one to do so), the first overflow 8654 // would have to enter the range, which would mean that either we had left 8655 // the range before or that we started outside of it. Both of these cases 8656 // are contradictions. 8657 // 8658 // Claim: In the case where SolveForBoundary returns None, the correct 8659 // solution is not some value between the Max for this boundary and the 8660 // Min of the other boundary. 8661 // 8662 // Justification: Assume that we had such Max_A and Min_B corresponding 8663 // to range boundaries A and B and such that Max_A < Min_B. If there was 8664 // a solution between Max_A and Min_B, it would have to be caused by an 8665 // overflow corresponding to either A or B. It cannot correspond to B, 8666 // since Min_B is the first occurrence of such an overflow. If it 8667 // corresponded to A, it would have to be either a signed or an unsigned 8668 // overflow that is larger than both eliminated overflows for A. But 8669 // between the eliminated overflows and this overflow, the values would 8670 // cover the entire value space, thus crossing the other boundary, which 8671 // is a contradiction. 8672 8673 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8674 } 8675 8676 ScalarEvolution::ExitLimit 8677 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8678 bool AllowPredicates) { 8679 8680 // This is only used for loops with a "x != y" exit test. The exit condition 8681 // is now expressed as a single expression, V = x-y. So the exit test is 8682 // effectively V != 0. We know and take advantage of the fact that this 8683 // expression only being used in a comparison by zero context. 8684 8685 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8686 // If the value is a constant 8687 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8688 // If the value is already zero, the branch will execute zero times. 8689 if (C->getValue()->isZero()) return C; 8690 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8691 } 8692 8693 const SCEVAddRecExpr *AddRec = 8694 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8695 8696 if (!AddRec && AllowPredicates) 8697 // Try to make this an AddRec using runtime tests, in the first X 8698 // iterations of this loop, where X is the SCEV expression found by the 8699 // algorithm below. 8700 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8701 8702 if (!AddRec || AddRec->getLoop() != L) 8703 return getCouldNotCompute(); 8704 8705 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8706 // the quadratic equation to solve it. 8707 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8708 // We can only use this value if the chrec ends up with an exact zero 8709 // value at this index. When solving for "X*X != 5", for example, we 8710 // should not accept a root of 2. 8711 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8712 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8713 return ExitLimit(R, R, false, Predicates); 8714 } 8715 return getCouldNotCompute(); 8716 } 8717 8718 // Otherwise we can only handle this if it is affine. 8719 if (!AddRec->isAffine()) 8720 return getCouldNotCompute(); 8721 8722 // If this is an affine expression, the execution count of this branch is 8723 // the minimum unsigned root of the following equation: 8724 // 8725 // Start + Step*N = 0 (mod 2^BW) 8726 // 8727 // equivalent to: 8728 // 8729 // Step*N = -Start (mod 2^BW) 8730 // 8731 // where BW is the common bit width of Start and Step. 8732 8733 // Get the initial value for the loop. 8734 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8735 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8736 8737 // For now we handle only constant steps. 8738 // 8739 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8740 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8741 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8742 // We have not yet seen any such cases. 8743 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8744 if (!StepC || StepC->getValue()->isZero()) 8745 return getCouldNotCompute(); 8746 8747 // For positive steps (counting up until unsigned overflow): 8748 // N = -Start/Step (as unsigned) 8749 // For negative steps (counting down to zero): 8750 // N = Start/-Step 8751 // First compute the unsigned distance from zero in the direction of Step. 8752 bool CountDown = StepC->getAPInt().isNegative(); 8753 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8754 8755 // Handle unitary steps, which cannot wraparound. 8756 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8757 // N = Distance (as unsigned) 8758 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8759 APInt MaxBECount = getUnsignedRangeMax(Distance); 8760 8761 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8762 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8763 // case, and see if we can improve the bound. 8764 // 8765 // Explicitly handling this here is necessary because getUnsignedRange 8766 // isn't context-sensitive; it doesn't know that we only care about the 8767 // range inside the loop. 8768 const SCEV *Zero = getZero(Distance->getType()); 8769 const SCEV *One = getOne(Distance->getType()); 8770 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8771 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8772 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8773 // as "unsigned_max(Distance + 1) - 1". 8774 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8775 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8776 } 8777 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8778 } 8779 8780 // If the condition controls loop exit (the loop exits only if the expression 8781 // is true) and the addition is no-wrap we can use unsigned divide to 8782 // compute the backedge count. In this case, the step may not divide the 8783 // distance, but we don't care because if the condition is "missed" the loop 8784 // will have undefined behavior due to wrapping. 8785 if (ControlsExit && AddRec->hasNoSelfWrap() && 8786 loopHasNoAbnormalExits(AddRec->getLoop())) { 8787 const SCEV *Exact = 8788 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8789 const SCEV *Max = 8790 Exact == getCouldNotCompute() 8791 ? Exact 8792 : getConstant(getUnsignedRangeMax(Exact)); 8793 return ExitLimit(Exact, Max, false, Predicates); 8794 } 8795 8796 // Solve the general equation. 8797 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8798 getNegativeSCEV(Start), *this); 8799 const SCEV *M = E == getCouldNotCompute() 8800 ? E 8801 : getConstant(getUnsignedRangeMax(E)); 8802 return ExitLimit(E, M, false, Predicates); 8803 } 8804 8805 ScalarEvolution::ExitLimit 8806 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8807 // Loops that look like: while (X == 0) are very strange indeed. We don't 8808 // handle them yet except for the trivial case. This could be expanded in the 8809 // future as needed. 8810 8811 // If the value is a constant, check to see if it is known to be non-zero 8812 // already. If so, the backedge will execute zero times. 8813 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8814 if (!C->getValue()->isZero()) 8815 return getZero(C->getType()); 8816 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8817 } 8818 8819 // We could implement others, but I really doubt anyone writes loops like 8820 // this, and if they did, they would already be constant folded. 8821 return getCouldNotCompute(); 8822 } 8823 8824 std::pair<BasicBlock *, BasicBlock *> 8825 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8826 // If the block has a unique predecessor, then there is no path from the 8827 // predecessor to the block that does not go through the direct edge 8828 // from the predecessor to the block. 8829 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8830 return {Pred, BB}; 8831 8832 // A loop's header is defined to be a block that dominates the loop. 8833 // If the header has a unique predecessor outside the loop, it must be 8834 // a block that has exactly one successor that can reach the loop. 8835 if (Loop *L = LI.getLoopFor(BB)) 8836 return {L->getLoopPredecessor(), L->getHeader()}; 8837 8838 return {nullptr, nullptr}; 8839 } 8840 8841 /// SCEV structural equivalence is usually sufficient for testing whether two 8842 /// expressions are equal, however for the purposes of looking for a condition 8843 /// guarding a loop, it can be useful to be a little more general, since a 8844 /// front-end may have replicated the controlling expression. 8845 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8846 // Quick check to see if they are the same SCEV. 8847 if (A == B) return true; 8848 8849 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8850 // Not all instructions that are "identical" compute the same value. For 8851 // instance, two distinct alloca instructions allocating the same type are 8852 // identical and do not read memory; but compute distinct values. 8853 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8854 }; 8855 8856 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8857 // two different instructions with the same value. Check for this case. 8858 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8859 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8860 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8861 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8862 if (ComputesEqualValues(AI, BI)) 8863 return true; 8864 8865 // Otherwise assume they may have a different value. 8866 return false; 8867 } 8868 8869 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8870 const SCEV *&LHS, const SCEV *&RHS, 8871 unsigned Depth) { 8872 bool Changed = false; 8873 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8874 // '0 != 0'. 8875 auto TrivialCase = [&](bool TriviallyTrue) { 8876 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8877 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8878 return true; 8879 }; 8880 // If we hit the max recursion limit bail out. 8881 if (Depth >= 3) 8882 return false; 8883 8884 // Canonicalize a constant to the right side. 8885 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8886 // Check for both operands constant. 8887 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8888 if (ConstantExpr::getICmp(Pred, 8889 LHSC->getValue(), 8890 RHSC->getValue())->isNullValue()) 8891 return TrivialCase(false); 8892 else 8893 return TrivialCase(true); 8894 } 8895 // Otherwise swap the operands to put the constant on the right. 8896 std::swap(LHS, RHS); 8897 Pred = ICmpInst::getSwappedPredicate(Pred); 8898 Changed = true; 8899 } 8900 8901 // If we're comparing an addrec with a value which is loop-invariant in the 8902 // addrec's loop, put the addrec on the left. Also make a dominance check, 8903 // as both operands could be addrecs loop-invariant in each other's loop. 8904 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8905 const Loop *L = AR->getLoop(); 8906 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8907 std::swap(LHS, RHS); 8908 Pred = ICmpInst::getSwappedPredicate(Pred); 8909 Changed = true; 8910 } 8911 } 8912 8913 // If there's a constant operand, canonicalize comparisons with boundary 8914 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8915 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8916 const APInt &RA = RC->getAPInt(); 8917 8918 bool SimplifiedByConstantRange = false; 8919 8920 if (!ICmpInst::isEquality(Pred)) { 8921 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8922 if (ExactCR.isFullSet()) 8923 return TrivialCase(true); 8924 else if (ExactCR.isEmptySet()) 8925 return TrivialCase(false); 8926 8927 APInt NewRHS; 8928 CmpInst::Predicate NewPred; 8929 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8930 ICmpInst::isEquality(NewPred)) { 8931 // We were able to convert an inequality to an equality. 8932 Pred = NewPred; 8933 RHS = getConstant(NewRHS); 8934 Changed = SimplifiedByConstantRange = true; 8935 } 8936 } 8937 8938 if (!SimplifiedByConstantRange) { 8939 switch (Pred) { 8940 default: 8941 break; 8942 case ICmpInst::ICMP_EQ: 8943 case ICmpInst::ICMP_NE: 8944 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8945 if (!RA) 8946 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8947 if (const SCEVMulExpr *ME = 8948 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8949 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8950 ME->getOperand(0)->isAllOnesValue()) { 8951 RHS = AE->getOperand(1); 8952 LHS = ME->getOperand(1); 8953 Changed = true; 8954 } 8955 break; 8956 8957 8958 // The "Should have been caught earlier!" messages refer to the fact 8959 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8960 // should have fired on the corresponding cases, and canonicalized the 8961 // check to trivial case. 8962 8963 case ICmpInst::ICMP_UGE: 8964 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8965 Pred = ICmpInst::ICMP_UGT; 8966 RHS = getConstant(RA - 1); 8967 Changed = true; 8968 break; 8969 case ICmpInst::ICMP_ULE: 8970 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8971 Pred = ICmpInst::ICMP_ULT; 8972 RHS = getConstant(RA + 1); 8973 Changed = true; 8974 break; 8975 case ICmpInst::ICMP_SGE: 8976 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8977 Pred = ICmpInst::ICMP_SGT; 8978 RHS = getConstant(RA - 1); 8979 Changed = true; 8980 break; 8981 case ICmpInst::ICMP_SLE: 8982 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8983 Pred = ICmpInst::ICMP_SLT; 8984 RHS = getConstant(RA + 1); 8985 Changed = true; 8986 break; 8987 } 8988 } 8989 } 8990 8991 // Check for obvious equality. 8992 if (HasSameValue(LHS, RHS)) { 8993 if (ICmpInst::isTrueWhenEqual(Pred)) 8994 return TrivialCase(true); 8995 if (ICmpInst::isFalseWhenEqual(Pred)) 8996 return TrivialCase(false); 8997 } 8998 8999 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9000 // adding or subtracting 1 from one of the operands. 9001 switch (Pred) { 9002 case ICmpInst::ICMP_SLE: 9003 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9004 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9005 SCEV::FlagNSW); 9006 Pred = ICmpInst::ICMP_SLT; 9007 Changed = true; 9008 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9009 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9010 SCEV::FlagNSW); 9011 Pred = ICmpInst::ICMP_SLT; 9012 Changed = true; 9013 } 9014 break; 9015 case ICmpInst::ICMP_SGE: 9016 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9017 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9018 SCEV::FlagNSW); 9019 Pred = ICmpInst::ICMP_SGT; 9020 Changed = true; 9021 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9022 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9023 SCEV::FlagNSW); 9024 Pred = ICmpInst::ICMP_SGT; 9025 Changed = true; 9026 } 9027 break; 9028 case ICmpInst::ICMP_ULE: 9029 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9030 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9031 SCEV::FlagNUW); 9032 Pred = ICmpInst::ICMP_ULT; 9033 Changed = true; 9034 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9035 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9036 Pred = ICmpInst::ICMP_ULT; 9037 Changed = true; 9038 } 9039 break; 9040 case ICmpInst::ICMP_UGE: 9041 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9042 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9043 Pred = ICmpInst::ICMP_UGT; 9044 Changed = true; 9045 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9046 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9047 SCEV::FlagNUW); 9048 Pred = ICmpInst::ICMP_UGT; 9049 Changed = true; 9050 } 9051 break; 9052 default: 9053 break; 9054 } 9055 9056 // TODO: More simplifications are possible here. 9057 9058 // Recursively simplify until we either hit a recursion limit or nothing 9059 // changes. 9060 if (Changed) 9061 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9062 9063 return Changed; 9064 } 9065 9066 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9067 return getSignedRangeMax(S).isNegative(); 9068 } 9069 9070 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9071 return getSignedRangeMin(S).isStrictlyPositive(); 9072 } 9073 9074 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9075 return !getSignedRangeMin(S).isNegative(); 9076 } 9077 9078 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9079 return !getSignedRangeMax(S).isStrictlyPositive(); 9080 } 9081 9082 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9083 return isKnownNegative(S) || isKnownPositive(S); 9084 } 9085 9086 std::pair<const SCEV *, const SCEV *> 9087 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9088 // Compute SCEV on entry of loop L. 9089 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9090 if (Start == getCouldNotCompute()) 9091 return { Start, Start }; 9092 // Compute post increment SCEV for loop L. 9093 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9094 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9095 return { Start, PostInc }; 9096 } 9097 9098 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9099 const SCEV *LHS, const SCEV *RHS) { 9100 // First collect all loops. 9101 SmallPtrSet<const Loop *, 8> LoopsUsed; 9102 getUsedLoops(LHS, LoopsUsed); 9103 getUsedLoops(RHS, LoopsUsed); 9104 9105 if (LoopsUsed.empty()) 9106 return false; 9107 9108 // Domination relationship must be a linear order on collected loops. 9109 #ifndef NDEBUG 9110 for (auto *L1 : LoopsUsed) 9111 for (auto *L2 : LoopsUsed) 9112 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9113 DT.dominates(L2->getHeader(), L1->getHeader())) && 9114 "Domination relationship is not a linear order"); 9115 #endif 9116 9117 const Loop *MDL = 9118 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9119 [&](const Loop *L1, const Loop *L2) { 9120 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9121 }); 9122 9123 // Get init and post increment value for LHS. 9124 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9125 // if LHS contains unknown non-invariant SCEV then bail out. 9126 if (SplitLHS.first == getCouldNotCompute()) 9127 return false; 9128 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9129 // Get init and post increment value for RHS. 9130 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9131 // if RHS contains unknown non-invariant SCEV then bail out. 9132 if (SplitRHS.first == getCouldNotCompute()) 9133 return false; 9134 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9135 // It is possible that init SCEV contains an invariant load but it does 9136 // not dominate MDL and is not available at MDL loop entry, so we should 9137 // check it here. 9138 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9139 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9140 return false; 9141 9142 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 9143 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9144 SplitRHS.second); 9145 } 9146 9147 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9148 const SCEV *LHS, const SCEV *RHS) { 9149 // Canonicalize the inputs first. 9150 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9151 9152 if (isKnownViaInduction(Pred, LHS, RHS)) 9153 return true; 9154 9155 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9156 return true; 9157 9158 // Otherwise see what can be done with some simple reasoning. 9159 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9160 } 9161 9162 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9163 const SCEVAddRecExpr *LHS, 9164 const SCEV *RHS) { 9165 const Loop *L = LHS->getLoop(); 9166 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9167 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9168 } 9169 9170 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9171 ICmpInst::Predicate Pred, 9172 bool &Increasing) { 9173 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9174 9175 #ifndef NDEBUG 9176 // Verify an invariant: inverting the predicate should turn a monotonically 9177 // increasing change to a monotonically decreasing one, and vice versa. 9178 bool IncreasingSwapped; 9179 bool ResultSwapped = isMonotonicPredicateImpl( 9180 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9181 9182 assert(Result == ResultSwapped && "should be able to analyze both!"); 9183 if (ResultSwapped) 9184 assert(Increasing == !IncreasingSwapped && 9185 "monotonicity should flip as we flip the predicate"); 9186 #endif 9187 9188 return Result; 9189 } 9190 9191 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9192 ICmpInst::Predicate Pred, 9193 bool &Increasing) { 9194 9195 // A zero step value for LHS means the induction variable is essentially a 9196 // loop invariant value. We don't really depend on the predicate actually 9197 // flipping from false to true (for increasing predicates, and the other way 9198 // around for decreasing predicates), all we care about is that *if* the 9199 // predicate changes then it only changes from false to true. 9200 // 9201 // A zero step value in itself is not very useful, but there may be places 9202 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9203 // as general as possible. 9204 9205 switch (Pred) { 9206 default: 9207 return false; // Conservative answer 9208 9209 case ICmpInst::ICMP_UGT: 9210 case ICmpInst::ICMP_UGE: 9211 case ICmpInst::ICMP_ULT: 9212 case ICmpInst::ICMP_ULE: 9213 if (!LHS->hasNoUnsignedWrap()) 9214 return false; 9215 9216 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9217 return true; 9218 9219 case ICmpInst::ICMP_SGT: 9220 case ICmpInst::ICMP_SGE: 9221 case ICmpInst::ICMP_SLT: 9222 case ICmpInst::ICMP_SLE: { 9223 if (!LHS->hasNoSignedWrap()) 9224 return false; 9225 9226 const SCEV *Step = LHS->getStepRecurrence(*this); 9227 9228 if (isKnownNonNegative(Step)) { 9229 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9230 return true; 9231 } 9232 9233 if (isKnownNonPositive(Step)) { 9234 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9235 return true; 9236 } 9237 9238 return false; 9239 } 9240 9241 } 9242 9243 llvm_unreachable("switch has default clause!"); 9244 } 9245 9246 bool ScalarEvolution::isLoopInvariantPredicate( 9247 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9248 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9249 const SCEV *&InvariantRHS) { 9250 9251 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9252 if (!isLoopInvariant(RHS, L)) { 9253 if (!isLoopInvariant(LHS, L)) 9254 return false; 9255 9256 std::swap(LHS, RHS); 9257 Pred = ICmpInst::getSwappedPredicate(Pred); 9258 } 9259 9260 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9261 if (!ArLHS || ArLHS->getLoop() != L) 9262 return false; 9263 9264 bool Increasing; 9265 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9266 return false; 9267 9268 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9269 // true as the loop iterates, and the backedge is control dependent on 9270 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9271 // 9272 // * if the predicate was false in the first iteration then the predicate 9273 // is never evaluated again, since the loop exits without taking the 9274 // backedge. 9275 // * if the predicate was true in the first iteration then it will 9276 // continue to be true for all future iterations since it is 9277 // monotonically increasing. 9278 // 9279 // For both the above possibilities, we can replace the loop varying 9280 // predicate with its value on the first iteration of the loop (which is 9281 // loop invariant). 9282 // 9283 // A similar reasoning applies for a monotonically decreasing predicate, by 9284 // replacing true with false and false with true in the above two bullets. 9285 9286 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9287 9288 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9289 return false; 9290 9291 InvariantPred = Pred; 9292 InvariantLHS = ArLHS->getStart(); 9293 InvariantRHS = RHS; 9294 return true; 9295 } 9296 9297 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9298 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9299 if (HasSameValue(LHS, RHS)) 9300 return ICmpInst::isTrueWhenEqual(Pred); 9301 9302 // This code is split out from isKnownPredicate because it is called from 9303 // within isLoopEntryGuardedByCond. 9304 9305 auto CheckRanges = 9306 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9307 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9308 .contains(RangeLHS); 9309 }; 9310 9311 // The check at the top of the function catches the case where the values are 9312 // known to be equal. 9313 if (Pred == CmpInst::ICMP_EQ) 9314 return false; 9315 9316 if (Pred == CmpInst::ICMP_NE) 9317 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9318 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9319 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9320 9321 if (CmpInst::isSigned(Pred)) 9322 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9323 9324 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9325 } 9326 9327 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9328 const SCEV *LHS, 9329 const SCEV *RHS) { 9330 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9331 // Return Y via OutY. 9332 auto MatchBinaryAddToConst = 9333 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9334 SCEV::NoWrapFlags ExpectedFlags) { 9335 const SCEV *NonConstOp, *ConstOp; 9336 SCEV::NoWrapFlags FlagsPresent; 9337 9338 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9339 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9340 return false; 9341 9342 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9343 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9344 }; 9345 9346 APInt C; 9347 9348 switch (Pred) { 9349 default: 9350 break; 9351 9352 case ICmpInst::ICMP_SGE: 9353 std::swap(LHS, RHS); 9354 LLVM_FALLTHROUGH; 9355 case ICmpInst::ICMP_SLE: 9356 // X s<= (X + C)<nsw> if C >= 0 9357 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9358 return true; 9359 9360 // (X + C)<nsw> s<= X if C <= 0 9361 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9362 !C.isStrictlyPositive()) 9363 return true; 9364 break; 9365 9366 case ICmpInst::ICMP_SGT: 9367 std::swap(LHS, RHS); 9368 LLVM_FALLTHROUGH; 9369 case ICmpInst::ICMP_SLT: 9370 // X s< (X + C)<nsw> if C > 0 9371 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9372 C.isStrictlyPositive()) 9373 return true; 9374 9375 // (X + C)<nsw> s< X if C < 0 9376 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9377 return true; 9378 break; 9379 } 9380 9381 return false; 9382 } 9383 9384 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9385 const SCEV *LHS, 9386 const SCEV *RHS) { 9387 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9388 return false; 9389 9390 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9391 // the stack can result in exponential time complexity. 9392 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9393 9394 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9395 // 9396 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9397 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9398 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9399 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9400 // use isKnownPredicate later if needed. 9401 return isKnownNonNegative(RHS) && 9402 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9403 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9404 } 9405 9406 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9407 ICmpInst::Predicate Pred, 9408 const SCEV *LHS, const SCEV *RHS) { 9409 // No need to even try if we know the module has no guards. 9410 if (!HasGuards) 9411 return false; 9412 9413 return any_of(*BB, [&](Instruction &I) { 9414 using namespace llvm::PatternMatch; 9415 9416 Value *Condition; 9417 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9418 m_Value(Condition))) && 9419 isImpliedCond(Pred, LHS, RHS, Condition, false); 9420 }); 9421 } 9422 9423 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9424 /// protected by a conditional between LHS and RHS. This is used to 9425 /// to eliminate casts. 9426 bool 9427 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9428 ICmpInst::Predicate Pred, 9429 const SCEV *LHS, const SCEV *RHS) { 9430 // Interpret a null as meaning no loop, where there is obviously no guard 9431 // (interprocedural conditions notwithstanding). 9432 if (!L) return true; 9433 9434 if (VerifyIR) 9435 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9436 "This cannot be done on broken IR!"); 9437 9438 9439 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9440 return true; 9441 9442 BasicBlock *Latch = L->getLoopLatch(); 9443 if (!Latch) 9444 return false; 9445 9446 BranchInst *LoopContinuePredicate = 9447 dyn_cast<BranchInst>(Latch->getTerminator()); 9448 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9449 isImpliedCond(Pred, LHS, RHS, 9450 LoopContinuePredicate->getCondition(), 9451 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9452 return true; 9453 9454 // We don't want more than one activation of the following loops on the stack 9455 // -- that can lead to O(n!) time complexity. 9456 if (WalkingBEDominatingConds) 9457 return false; 9458 9459 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9460 9461 // See if we can exploit a trip count to prove the predicate. 9462 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9463 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9464 if (LatchBECount != getCouldNotCompute()) { 9465 // We know that Latch branches back to the loop header exactly 9466 // LatchBECount times. This means the backdege condition at Latch is 9467 // equivalent to "{0,+,1} u< LatchBECount". 9468 Type *Ty = LatchBECount->getType(); 9469 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9470 const SCEV *LoopCounter = 9471 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9472 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9473 LatchBECount)) 9474 return true; 9475 } 9476 9477 // Check conditions due to any @llvm.assume intrinsics. 9478 for (auto &AssumeVH : AC.assumptions()) { 9479 if (!AssumeVH) 9480 continue; 9481 auto *CI = cast<CallInst>(AssumeVH); 9482 if (!DT.dominates(CI, Latch->getTerminator())) 9483 continue; 9484 9485 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9486 return true; 9487 } 9488 9489 // If the loop is not reachable from the entry block, we risk running into an 9490 // infinite loop as we walk up into the dom tree. These loops do not matter 9491 // anyway, so we just return a conservative answer when we see them. 9492 if (!DT.isReachableFromEntry(L->getHeader())) 9493 return false; 9494 9495 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9496 return true; 9497 9498 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9499 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9500 assert(DTN && "should reach the loop header before reaching the root!"); 9501 9502 BasicBlock *BB = DTN->getBlock(); 9503 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9504 return true; 9505 9506 BasicBlock *PBB = BB->getSinglePredecessor(); 9507 if (!PBB) 9508 continue; 9509 9510 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9511 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9512 continue; 9513 9514 Value *Condition = ContinuePredicate->getCondition(); 9515 9516 // If we have an edge `E` within the loop body that dominates the only 9517 // latch, the condition guarding `E` also guards the backedge. This 9518 // reasoning works only for loops with a single latch. 9519 9520 BasicBlockEdge DominatingEdge(PBB, BB); 9521 if (DominatingEdge.isSingleEdge()) { 9522 // We're constructively (and conservatively) enumerating edges within the 9523 // loop body that dominate the latch. The dominator tree better agree 9524 // with us on this: 9525 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9526 9527 if (isImpliedCond(Pred, LHS, RHS, Condition, 9528 BB != ContinuePredicate->getSuccessor(0))) 9529 return true; 9530 } 9531 } 9532 9533 return false; 9534 } 9535 9536 bool 9537 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9538 ICmpInst::Predicate Pred, 9539 const SCEV *LHS, const SCEV *RHS) { 9540 // Interpret a null as meaning no loop, where there is obviously no guard 9541 // (interprocedural conditions notwithstanding). 9542 if (!L) return false; 9543 9544 if (VerifyIR) 9545 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9546 "This cannot be done on broken IR!"); 9547 9548 // Both LHS and RHS must be available at loop entry. 9549 assert(isAvailableAtLoopEntry(LHS, L) && 9550 "LHS is not available at Loop Entry"); 9551 assert(isAvailableAtLoopEntry(RHS, L) && 9552 "RHS is not available at Loop Entry"); 9553 9554 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9555 return true; 9556 9557 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9558 // the facts (a >= b && a != b) separately. A typical situation is when the 9559 // non-strict comparison is known from ranges and non-equality is known from 9560 // dominating predicates. If we are proving strict comparison, we always try 9561 // to prove non-equality and non-strict comparison separately. 9562 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9563 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9564 bool ProvedNonStrictComparison = false; 9565 bool ProvedNonEquality = false; 9566 9567 if (ProvingStrictComparison) { 9568 ProvedNonStrictComparison = 9569 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9570 ProvedNonEquality = 9571 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9572 if (ProvedNonStrictComparison && ProvedNonEquality) 9573 return true; 9574 } 9575 9576 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9577 auto ProveViaGuard = [&](BasicBlock *Block) { 9578 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9579 return true; 9580 if (ProvingStrictComparison) { 9581 if (!ProvedNonStrictComparison) 9582 ProvedNonStrictComparison = 9583 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9584 if (!ProvedNonEquality) 9585 ProvedNonEquality = 9586 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9587 if (ProvedNonStrictComparison && ProvedNonEquality) 9588 return true; 9589 } 9590 return false; 9591 }; 9592 9593 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9594 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9595 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9596 return true; 9597 if (ProvingStrictComparison) { 9598 if (!ProvedNonStrictComparison) 9599 ProvedNonStrictComparison = 9600 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9601 if (!ProvedNonEquality) 9602 ProvedNonEquality = 9603 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9604 if (ProvedNonStrictComparison && ProvedNonEquality) 9605 return true; 9606 } 9607 return false; 9608 }; 9609 9610 // Starting at the loop predecessor, climb up the predecessor chain, as long 9611 // as there are predecessors that can be found that have unique successors 9612 // leading to the original header. 9613 for (std::pair<BasicBlock *, BasicBlock *> 9614 Pair(L->getLoopPredecessor(), L->getHeader()); 9615 Pair.first; 9616 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9617 9618 if (ProveViaGuard(Pair.first)) 9619 return true; 9620 9621 BranchInst *LoopEntryPredicate = 9622 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9623 if (!LoopEntryPredicate || 9624 LoopEntryPredicate->isUnconditional()) 9625 continue; 9626 9627 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9628 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9629 return true; 9630 } 9631 9632 // Check conditions due to any @llvm.assume intrinsics. 9633 for (auto &AssumeVH : AC.assumptions()) { 9634 if (!AssumeVH) 9635 continue; 9636 auto *CI = cast<CallInst>(AssumeVH); 9637 if (!DT.dominates(CI, L->getHeader())) 9638 continue; 9639 9640 if (ProveViaCond(CI->getArgOperand(0), false)) 9641 return true; 9642 } 9643 9644 return false; 9645 } 9646 9647 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9648 const SCEV *LHS, const SCEV *RHS, 9649 Value *FoundCondValue, 9650 bool Inverse) { 9651 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9652 return false; 9653 9654 auto ClearOnExit = 9655 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9656 9657 // Recursively handle And and Or conditions. 9658 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9659 if (BO->getOpcode() == Instruction::And) { 9660 if (!Inverse) 9661 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9662 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9663 } else if (BO->getOpcode() == Instruction::Or) { 9664 if (Inverse) 9665 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9666 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9667 } 9668 } 9669 9670 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9671 if (!ICI) return false; 9672 9673 // Now that we found a conditional branch that dominates the loop or controls 9674 // the loop latch. Check to see if it is the comparison we are looking for. 9675 ICmpInst::Predicate FoundPred; 9676 if (Inverse) 9677 FoundPred = ICI->getInversePredicate(); 9678 else 9679 FoundPred = ICI->getPredicate(); 9680 9681 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9682 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9683 9684 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9685 } 9686 9687 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9688 const SCEV *RHS, 9689 ICmpInst::Predicate FoundPred, 9690 const SCEV *FoundLHS, 9691 const SCEV *FoundRHS) { 9692 // Balance the types. 9693 if (getTypeSizeInBits(LHS->getType()) < 9694 getTypeSizeInBits(FoundLHS->getType())) { 9695 if (CmpInst::isSigned(Pred)) { 9696 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9697 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9698 } else { 9699 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9700 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9701 } 9702 } else if (getTypeSizeInBits(LHS->getType()) > 9703 getTypeSizeInBits(FoundLHS->getType())) { 9704 if (CmpInst::isSigned(FoundPred)) { 9705 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9706 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9707 } else { 9708 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9709 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9710 } 9711 } 9712 9713 // Canonicalize the query to match the way instcombine will have 9714 // canonicalized the comparison. 9715 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9716 if (LHS == RHS) 9717 return CmpInst::isTrueWhenEqual(Pred); 9718 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9719 if (FoundLHS == FoundRHS) 9720 return CmpInst::isFalseWhenEqual(FoundPred); 9721 9722 // Check to see if we can make the LHS or RHS match. 9723 if (LHS == FoundRHS || RHS == FoundLHS) { 9724 if (isa<SCEVConstant>(RHS)) { 9725 std::swap(FoundLHS, FoundRHS); 9726 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9727 } else { 9728 std::swap(LHS, RHS); 9729 Pred = ICmpInst::getSwappedPredicate(Pred); 9730 } 9731 } 9732 9733 // Check whether the found predicate is the same as the desired predicate. 9734 if (FoundPred == Pred) 9735 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9736 9737 // Check whether swapping the found predicate makes it the same as the 9738 // desired predicate. 9739 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9740 if (isa<SCEVConstant>(RHS)) 9741 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9742 else 9743 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9744 RHS, LHS, FoundLHS, FoundRHS); 9745 } 9746 9747 // Unsigned comparison is the same as signed comparison when both the operands 9748 // are non-negative. 9749 if (CmpInst::isUnsigned(FoundPred) && 9750 CmpInst::getSignedPredicate(FoundPred) == Pred && 9751 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9752 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9753 9754 // Check if we can make progress by sharpening ranges. 9755 if (FoundPred == ICmpInst::ICMP_NE && 9756 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9757 9758 const SCEVConstant *C = nullptr; 9759 const SCEV *V = nullptr; 9760 9761 if (isa<SCEVConstant>(FoundLHS)) { 9762 C = cast<SCEVConstant>(FoundLHS); 9763 V = FoundRHS; 9764 } else { 9765 C = cast<SCEVConstant>(FoundRHS); 9766 V = FoundLHS; 9767 } 9768 9769 // The guarding predicate tells us that C != V. If the known range 9770 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9771 // range we consider has to correspond to same signedness as the 9772 // predicate we're interested in folding. 9773 9774 APInt Min = ICmpInst::isSigned(Pred) ? 9775 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9776 9777 if (Min == C->getAPInt()) { 9778 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9779 // This is true even if (Min + 1) wraps around -- in case of 9780 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9781 9782 APInt SharperMin = Min + 1; 9783 9784 switch (Pred) { 9785 case ICmpInst::ICMP_SGE: 9786 case ICmpInst::ICMP_UGE: 9787 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9788 // RHS, we're done. 9789 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9790 getConstant(SharperMin))) 9791 return true; 9792 LLVM_FALLTHROUGH; 9793 9794 case ICmpInst::ICMP_SGT: 9795 case ICmpInst::ICMP_UGT: 9796 // We know from the range information that (V `Pred` Min || 9797 // V == Min). We know from the guarding condition that !(V 9798 // == Min). This gives us 9799 // 9800 // V `Pred` Min || V == Min && !(V == Min) 9801 // => V `Pred` Min 9802 // 9803 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9804 9805 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9806 return true; 9807 LLVM_FALLTHROUGH; 9808 9809 default: 9810 // No change 9811 break; 9812 } 9813 } 9814 } 9815 9816 // Check whether the actual condition is beyond sufficient. 9817 if (FoundPred == ICmpInst::ICMP_EQ) 9818 if (ICmpInst::isTrueWhenEqual(Pred)) 9819 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9820 return true; 9821 if (Pred == ICmpInst::ICMP_NE) 9822 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9823 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9824 return true; 9825 9826 // Otherwise assume the worst. 9827 return false; 9828 } 9829 9830 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9831 const SCEV *&L, const SCEV *&R, 9832 SCEV::NoWrapFlags &Flags) { 9833 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9834 if (!AE || AE->getNumOperands() != 2) 9835 return false; 9836 9837 L = AE->getOperand(0); 9838 R = AE->getOperand(1); 9839 Flags = AE->getNoWrapFlags(); 9840 return true; 9841 } 9842 9843 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9844 const SCEV *Less) { 9845 // We avoid subtracting expressions here because this function is usually 9846 // fairly deep in the call stack (i.e. is called many times). 9847 9848 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9849 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9850 const auto *MAR = cast<SCEVAddRecExpr>(More); 9851 9852 if (LAR->getLoop() != MAR->getLoop()) 9853 return None; 9854 9855 // We look at affine expressions only; not for correctness but to keep 9856 // getStepRecurrence cheap. 9857 if (!LAR->isAffine() || !MAR->isAffine()) 9858 return None; 9859 9860 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9861 return None; 9862 9863 Less = LAR->getStart(); 9864 More = MAR->getStart(); 9865 9866 // fall through 9867 } 9868 9869 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9870 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9871 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9872 return M - L; 9873 } 9874 9875 SCEV::NoWrapFlags Flags; 9876 const SCEV *LLess = nullptr, *RLess = nullptr; 9877 const SCEV *LMore = nullptr, *RMore = nullptr; 9878 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9879 // Compare (X + C1) vs X. 9880 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9881 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9882 if (RLess == More) 9883 return -(C1->getAPInt()); 9884 9885 // Compare X vs (X + C2). 9886 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9887 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9888 if (RMore == Less) 9889 return C2->getAPInt(); 9890 9891 // Compare (X + C1) vs (X + C2). 9892 if (C1 && C2 && RLess == RMore) 9893 return C2->getAPInt() - C1->getAPInt(); 9894 9895 return None; 9896 } 9897 9898 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9899 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9900 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9901 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9902 return false; 9903 9904 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9905 if (!AddRecLHS) 9906 return false; 9907 9908 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9909 if (!AddRecFoundLHS) 9910 return false; 9911 9912 // We'd like to let SCEV reason about control dependencies, so we constrain 9913 // both the inequalities to be about add recurrences on the same loop. This 9914 // way we can use isLoopEntryGuardedByCond later. 9915 9916 const Loop *L = AddRecFoundLHS->getLoop(); 9917 if (L != AddRecLHS->getLoop()) 9918 return false; 9919 9920 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9921 // 9922 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9923 // ... (2) 9924 // 9925 // Informal proof for (2), assuming (1) [*]: 9926 // 9927 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9928 // 9929 // Then 9930 // 9931 // FoundLHS s< FoundRHS s< INT_MIN - C 9932 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9933 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9934 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9935 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9936 // <=> FoundLHS + C s< FoundRHS + C 9937 // 9938 // [*]: (1) can be proved by ruling out overflow. 9939 // 9940 // [**]: This can be proved by analyzing all the four possibilities: 9941 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9942 // (A s>= 0, B s>= 0). 9943 // 9944 // Note: 9945 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9946 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9947 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9948 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9949 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9950 // C)". 9951 9952 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9953 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9954 if (!LDiff || !RDiff || *LDiff != *RDiff) 9955 return false; 9956 9957 if (LDiff->isMinValue()) 9958 return true; 9959 9960 APInt FoundRHSLimit; 9961 9962 if (Pred == CmpInst::ICMP_ULT) { 9963 FoundRHSLimit = -(*RDiff); 9964 } else { 9965 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9966 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9967 } 9968 9969 // Try to prove (1) or (2), as needed. 9970 return isAvailableAtLoopEntry(FoundRHS, L) && 9971 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9972 getConstant(FoundRHSLimit)); 9973 } 9974 9975 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 9976 const SCEV *LHS, const SCEV *RHS, 9977 const SCEV *FoundLHS, 9978 const SCEV *FoundRHS, unsigned Depth) { 9979 const PHINode *LPhi = nullptr, *RPhi = nullptr; 9980 9981 auto ClearOnExit = make_scope_exit([&]() { 9982 if (LPhi) { 9983 bool Erased = PendingMerges.erase(LPhi); 9984 assert(Erased && "Failed to erase LPhi!"); 9985 (void)Erased; 9986 } 9987 if (RPhi) { 9988 bool Erased = PendingMerges.erase(RPhi); 9989 assert(Erased && "Failed to erase RPhi!"); 9990 (void)Erased; 9991 } 9992 }); 9993 9994 // Find respective Phis and check that they are not being pending. 9995 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 9996 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 9997 if (!PendingMerges.insert(Phi).second) 9998 return false; 9999 LPhi = Phi; 10000 } 10001 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10002 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10003 // If we detect a loop of Phi nodes being processed by this method, for 10004 // example: 10005 // 10006 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10007 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10008 // 10009 // we don't want to deal with a case that complex, so return conservative 10010 // answer false. 10011 if (!PendingMerges.insert(Phi).second) 10012 return false; 10013 RPhi = Phi; 10014 } 10015 10016 // If none of LHS, RHS is a Phi, nothing to do here. 10017 if (!LPhi && !RPhi) 10018 return false; 10019 10020 // If there is a SCEVUnknown Phi we are interested in, make it left. 10021 if (!LPhi) { 10022 std::swap(LHS, RHS); 10023 std::swap(FoundLHS, FoundRHS); 10024 std::swap(LPhi, RPhi); 10025 Pred = ICmpInst::getSwappedPredicate(Pred); 10026 } 10027 10028 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10029 const BasicBlock *LBB = LPhi->getParent(); 10030 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10031 10032 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10033 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10034 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10035 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10036 }; 10037 10038 if (RPhi && RPhi->getParent() == LBB) { 10039 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10040 // If we compare two Phis from the same block, and for each entry block 10041 // the predicate is true for incoming values from this block, then the 10042 // predicate is also true for the Phis. 10043 for (const BasicBlock *IncBB : predecessors(LBB)) { 10044 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10045 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10046 if (!ProvedEasily(L, R)) 10047 return false; 10048 } 10049 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10050 // Case two: RHS is also a Phi from the same basic block, and it is an 10051 // AddRec. It means that there is a loop which has both AddRec and Unknown 10052 // PHIs, for it we can compare incoming values of AddRec from above the loop 10053 // and latch with their respective incoming values of LPhi. 10054 // TODO: Generalize to handle loops with many inputs in a header. 10055 if (LPhi->getNumIncomingValues() != 2) return false; 10056 10057 auto *RLoop = RAR->getLoop(); 10058 auto *Predecessor = RLoop->getLoopPredecessor(); 10059 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10060 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10061 if (!ProvedEasily(L1, RAR->getStart())) 10062 return false; 10063 auto *Latch = RLoop->getLoopLatch(); 10064 assert(Latch && "Loop with AddRec with no latch?"); 10065 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10066 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10067 return false; 10068 } else { 10069 // In all other cases go over inputs of LHS and compare each of them to RHS, 10070 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10071 // At this point RHS is either a non-Phi, or it is a Phi from some block 10072 // different from LBB. 10073 for (const BasicBlock *IncBB : predecessors(LBB)) { 10074 // Check that RHS is available in this block. 10075 if (!dominates(RHS, IncBB)) 10076 return false; 10077 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10078 if (!ProvedEasily(L, RHS)) 10079 return false; 10080 } 10081 } 10082 return true; 10083 } 10084 10085 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10086 const SCEV *LHS, const SCEV *RHS, 10087 const SCEV *FoundLHS, 10088 const SCEV *FoundRHS) { 10089 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10090 return true; 10091 10092 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10093 return true; 10094 10095 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10096 FoundLHS, FoundRHS) || 10097 // ~x < ~y --> x > y 10098 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10099 getNotSCEV(FoundRHS), 10100 getNotSCEV(FoundLHS)); 10101 } 10102 10103 /// If Expr computes ~A, return A else return nullptr 10104 static const SCEV *MatchNotExpr(const SCEV *Expr) { 10105 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 10106 if (!Add || Add->getNumOperands() != 2 || 10107 !Add->getOperand(0)->isAllOnesValue()) 10108 return nullptr; 10109 10110 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 10111 if (!AddRHS || AddRHS->getNumOperands() != 2 || 10112 !AddRHS->getOperand(0)->isAllOnesValue()) 10113 return nullptr; 10114 10115 return AddRHS->getOperand(1); 10116 } 10117 10118 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 10119 template<typename MaxExprType> 10120 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 10121 const SCEV *Candidate) { 10122 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 10123 if (!MaxExpr) return false; 10124 10125 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 10126 } 10127 10128 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 10129 template<typename MaxExprType> 10130 static bool IsMinConsistingOf(ScalarEvolution &SE, 10131 const SCEV *MaybeMinExpr, 10132 const SCEV *Candidate) { 10133 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 10134 if (!MaybeMaxExpr) 10135 return false; 10136 10137 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 10138 } 10139 10140 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10141 ICmpInst::Predicate Pred, 10142 const SCEV *LHS, const SCEV *RHS) { 10143 // If both sides are affine addrecs for the same loop, with equal 10144 // steps, and we know the recurrences don't wrap, then we only 10145 // need to check the predicate on the starting values. 10146 10147 if (!ICmpInst::isRelational(Pred)) 10148 return false; 10149 10150 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10151 if (!LAR) 10152 return false; 10153 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10154 if (!RAR) 10155 return false; 10156 if (LAR->getLoop() != RAR->getLoop()) 10157 return false; 10158 if (!LAR->isAffine() || !RAR->isAffine()) 10159 return false; 10160 10161 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10162 return false; 10163 10164 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10165 SCEV::FlagNSW : SCEV::FlagNUW; 10166 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10167 return false; 10168 10169 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10170 } 10171 10172 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10173 /// expression? 10174 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10175 ICmpInst::Predicate Pred, 10176 const SCEV *LHS, const SCEV *RHS) { 10177 switch (Pred) { 10178 default: 10179 return false; 10180 10181 case ICmpInst::ICMP_SGE: 10182 std::swap(LHS, RHS); 10183 LLVM_FALLTHROUGH; 10184 case ICmpInst::ICMP_SLE: 10185 return 10186 // min(A, ...) <= A 10187 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 10188 // A <= max(A, ...) 10189 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10190 10191 case ICmpInst::ICMP_UGE: 10192 std::swap(LHS, RHS); 10193 LLVM_FALLTHROUGH; 10194 case ICmpInst::ICMP_ULE: 10195 return 10196 // min(A, ...) <= A 10197 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 10198 // A <= max(A, ...) 10199 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10200 } 10201 10202 llvm_unreachable("covered switch fell through?!"); 10203 } 10204 10205 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10206 const SCEV *LHS, const SCEV *RHS, 10207 const SCEV *FoundLHS, 10208 const SCEV *FoundRHS, 10209 unsigned Depth) { 10210 assert(getTypeSizeInBits(LHS->getType()) == 10211 getTypeSizeInBits(RHS->getType()) && 10212 "LHS and RHS have different sizes?"); 10213 assert(getTypeSizeInBits(FoundLHS->getType()) == 10214 getTypeSizeInBits(FoundRHS->getType()) && 10215 "FoundLHS and FoundRHS have different sizes?"); 10216 // We want to avoid hurting the compile time with analysis of too big trees. 10217 if (Depth > MaxSCEVOperationsImplicationDepth) 10218 return false; 10219 // We only want to work with ICMP_SGT comparison so far. 10220 // TODO: Extend to ICMP_UGT? 10221 if (Pred == ICmpInst::ICMP_SLT) { 10222 Pred = ICmpInst::ICMP_SGT; 10223 std::swap(LHS, RHS); 10224 std::swap(FoundLHS, FoundRHS); 10225 } 10226 if (Pred != ICmpInst::ICMP_SGT) 10227 return false; 10228 10229 auto GetOpFromSExt = [&](const SCEV *S) { 10230 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10231 return Ext->getOperand(); 10232 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10233 // the constant in some cases. 10234 return S; 10235 }; 10236 10237 // Acquire values from extensions. 10238 auto *OrigLHS = LHS; 10239 auto *OrigFoundLHS = FoundLHS; 10240 LHS = GetOpFromSExt(LHS); 10241 FoundLHS = GetOpFromSExt(FoundLHS); 10242 10243 // Is the SGT predicate can be proved trivially or using the found context. 10244 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10245 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10246 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10247 FoundRHS, Depth + 1); 10248 }; 10249 10250 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10251 // We want to avoid creation of any new non-constant SCEV. Since we are 10252 // going to compare the operands to RHS, we should be certain that we don't 10253 // need any size extensions for this. So let's decline all cases when the 10254 // sizes of types of LHS and RHS do not match. 10255 // TODO: Maybe try to get RHS from sext to catch more cases? 10256 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10257 return false; 10258 10259 // Should not overflow. 10260 if (!LHSAddExpr->hasNoSignedWrap()) 10261 return false; 10262 10263 auto *LL = LHSAddExpr->getOperand(0); 10264 auto *LR = LHSAddExpr->getOperand(1); 10265 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10266 10267 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10268 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10269 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10270 }; 10271 // Try to prove the following rule: 10272 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10273 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10274 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10275 return true; 10276 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10277 Value *LL, *LR; 10278 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10279 10280 using namespace llvm::PatternMatch; 10281 10282 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10283 // Rules for division. 10284 // We are going to perform some comparisons with Denominator and its 10285 // derivative expressions. In general case, creating a SCEV for it may 10286 // lead to a complex analysis of the entire graph, and in particular it 10287 // can request trip count recalculation for the same loop. This would 10288 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10289 // this, we only want to create SCEVs that are constants in this section. 10290 // So we bail if Denominator is not a constant. 10291 if (!isa<ConstantInt>(LR)) 10292 return false; 10293 10294 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10295 10296 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10297 // then a SCEV for the numerator already exists and matches with FoundLHS. 10298 auto *Numerator = getExistingSCEV(LL); 10299 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10300 return false; 10301 10302 // Make sure that the numerator matches with FoundLHS and the denominator 10303 // is positive. 10304 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10305 return false; 10306 10307 auto *DTy = Denominator->getType(); 10308 auto *FRHSTy = FoundRHS->getType(); 10309 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10310 // One of types is a pointer and another one is not. We cannot extend 10311 // them properly to a wider type, so let us just reject this case. 10312 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10313 // to avoid this check. 10314 return false; 10315 10316 // Given that: 10317 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10318 auto *WTy = getWiderType(DTy, FRHSTy); 10319 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10320 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10321 10322 // Try to prove the following rule: 10323 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10324 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10325 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10326 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10327 if (isKnownNonPositive(RHS) && 10328 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10329 return true; 10330 10331 // Try to prove the following rule: 10332 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10333 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10334 // If we divide it by Denominator > 2, then: 10335 // 1. If FoundLHS is negative, then the result is 0. 10336 // 2. If FoundLHS is non-negative, then the result is non-negative. 10337 // Anyways, the result is non-negative. 10338 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10339 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10340 if (isKnownNegative(RHS) && 10341 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10342 return true; 10343 } 10344 } 10345 10346 // If our expression contained SCEVUnknown Phis, and we split it down and now 10347 // need to prove something for them, try to prove the predicate for every 10348 // possible incoming values of those Phis. 10349 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10350 return true; 10351 10352 return false; 10353 } 10354 10355 bool 10356 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10357 const SCEV *LHS, const SCEV *RHS) { 10358 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10359 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10360 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10361 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10362 } 10363 10364 bool 10365 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10366 const SCEV *LHS, const SCEV *RHS, 10367 const SCEV *FoundLHS, 10368 const SCEV *FoundRHS) { 10369 switch (Pred) { 10370 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10371 case ICmpInst::ICMP_EQ: 10372 case ICmpInst::ICMP_NE: 10373 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10374 return true; 10375 break; 10376 case ICmpInst::ICMP_SLT: 10377 case ICmpInst::ICMP_SLE: 10378 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10379 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10380 return true; 10381 break; 10382 case ICmpInst::ICMP_SGT: 10383 case ICmpInst::ICMP_SGE: 10384 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10385 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10386 return true; 10387 break; 10388 case ICmpInst::ICMP_ULT: 10389 case ICmpInst::ICMP_ULE: 10390 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10391 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10392 return true; 10393 break; 10394 case ICmpInst::ICMP_UGT: 10395 case ICmpInst::ICMP_UGE: 10396 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10397 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10398 return true; 10399 break; 10400 } 10401 10402 // Maybe it can be proved via operations? 10403 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10404 return true; 10405 10406 return false; 10407 } 10408 10409 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10410 const SCEV *LHS, 10411 const SCEV *RHS, 10412 const SCEV *FoundLHS, 10413 const SCEV *FoundRHS) { 10414 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10415 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10416 // reduce the compile time impact of this optimization. 10417 return false; 10418 10419 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10420 if (!Addend) 10421 return false; 10422 10423 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10424 10425 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10426 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10427 ConstantRange FoundLHSRange = 10428 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10429 10430 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10431 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10432 10433 // We can also compute the range of values for `LHS` that satisfy the 10434 // consequent, "`LHS` `Pred` `RHS`": 10435 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10436 ConstantRange SatisfyingLHSRange = 10437 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10438 10439 // The antecedent implies the consequent if every value of `LHS` that 10440 // satisfies the antecedent also satisfies the consequent. 10441 return SatisfyingLHSRange.contains(LHSRange); 10442 } 10443 10444 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10445 bool IsSigned, bool NoWrap) { 10446 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10447 10448 if (NoWrap) return false; 10449 10450 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10451 const SCEV *One = getOne(Stride->getType()); 10452 10453 if (IsSigned) { 10454 APInt MaxRHS = getSignedRangeMax(RHS); 10455 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10456 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10457 10458 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10459 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10460 } 10461 10462 APInt MaxRHS = getUnsignedRangeMax(RHS); 10463 APInt MaxValue = APInt::getMaxValue(BitWidth); 10464 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10465 10466 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10467 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10468 } 10469 10470 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10471 bool IsSigned, bool NoWrap) { 10472 if (NoWrap) return false; 10473 10474 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10475 const SCEV *One = getOne(Stride->getType()); 10476 10477 if (IsSigned) { 10478 APInt MinRHS = getSignedRangeMin(RHS); 10479 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10480 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10481 10482 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10483 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10484 } 10485 10486 APInt MinRHS = getUnsignedRangeMin(RHS); 10487 APInt MinValue = APInt::getMinValue(BitWidth); 10488 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10489 10490 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10491 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10492 } 10493 10494 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10495 bool Equality) { 10496 const SCEV *One = getOne(Step->getType()); 10497 Delta = Equality ? getAddExpr(Delta, Step) 10498 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10499 return getUDivExpr(Delta, Step); 10500 } 10501 10502 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10503 const SCEV *Stride, 10504 const SCEV *End, 10505 unsigned BitWidth, 10506 bool IsSigned) { 10507 10508 assert(!isKnownNonPositive(Stride) && 10509 "Stride is expected strictly positive!"); 10510 // Calculate the maximum backedge count based on the range of values 10511 // permitted by Start, End, and Stride. 10512 const SCEV *MaxBECount; 10513 APInt MinStart = 10514 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10515 10516 APInt StrideForMaxBECount = 10517 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10518 10519 // We already know that the stride is positive, so we paper over conservatism 10520 // in our range computation by forcing StrideForMaxBECount to be at least one. 10521 // In theory this is unnecessary, but we expect MaxBECount to be a 10522 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10523 // is nothing to constant fold it to). 10524 APInt One(BitWidth, 1, IsSigned); 10525 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10526 10527 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10528 : APInt::getMaxValue(BitWidth); 10529 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10530 10531 // Although End can be a MAX expression we estimate MaxEnd considering only 10532 // the case End = RHS of the loop termination condition. This is safe because 10533 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10534 // taken count. 10535 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10536 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10537 10538 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10539 getConstant(StrideForMaxBECount) /* Step */, 10540 false /* Equality */); 10541 10542 return MaxBECount; 10543 } 10544 10545 ScalarEvolution::ExitLimit 10546 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10547 const Loop *L, bool IsSigned, 10548 bool ControlsExit, bool AllowPredicates) { 10549 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10550 10551 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10552 bool PredicatedIV = false; 10553 10554 if (!IV && AllowPredicates) { 10555 // Try to make this an AddRec using runtime tests, in the first X 10556 // iterations of this loop, where X is the SCEV expression found by the 10557 // algorithm below. 10558 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10559 PredicatedIV = true; 10560 } 10561 10562 // Avoid weird loops 10563 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10564 return getCouldNotCompute(); 10565 10566 bool NoWrap = ControlsExit && 10567 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10568 10569 const SCEV *Stride = IV->getStepRecurrence(*this); 10570 10571 bool PositiveStride = isKnownPositive(Stride); 10572 10573 // Avoid negative or zero stride values. 10574 if (!PositiveStride) { 10575 // We can compute the correct backedge taken count for loops with unknown 10576 // strides if we can prove that the loop is not an infinite loop with side 10577 // effects. Here's the loop structure we are trying to handle - 10578 // 10579 // i = start 10580 // do { 10581 // A[i] = i; 10582 // i += s; 10583 // } while (i < end); 10584 // 10585 // The backedge taken count for such loops is evaluated as - 10586 // (max(end, start + stride) - start - 1) /u stride 10587 // 10588 // The additional preconditions that we need to check to prove correctness 10589 // of the above formula is as follows - 10590 // 10591 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10592 // NoWrap flag). 10593 // b) loop is single exit with no side effects. 10594 // 10595 // 10596 // Precondition a) implies that if the stride is negative, this is a single 10597 // trip loop. The backedge taken count formula reduces to zero in this case. 10598 // 10599 // Precondition b) implies that the unknown stride cannot be zero otherwise 10600 // we have UB. 10601 // 10602 // The positive stride case is the same as isKnownPositive(Stride) returning 10603 // true (original behavior of the function). 10604 // 10605 // We want to make sure that the stride is truly unknown as there are edge 10606 // cases where ScalarEvolution propagates no wrap flags to the 10607 // post-increment/decrement IV even though the increment/decrement operation 10608 // itself is wrapping. The computed backedge taken count may be wrong in 10609 // such cases. This is prevented by checking that the stride is not known to 10610 // be either positive or non-positive. For example, no wrap flags are 10611 // propagated to the post-increment IV of this loop with a trip count of 2 - 10612 // 10613 // unsigned char i; 10614 // for(i=127; i<128; i+=129) 10615 // A[i] = i; 10616 // 10617 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10618 !loopHasNoSideEffects(L)) 10619 return getCouldNotCompute(); 10620 } else if (!Stride->isOne() && 10621 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10622 // Avoid proven overflow cases: this will ensure that the backedge taken 10623 // count will not generate any unsigned overflow. Relaxed no-overflow 10624 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10625 // undefined behaviors like the case of C language. 10626 return getCouldNotCompute(); 10627 10628 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10629 : ICmpInst::ICMP_ULT; 10630 const SCEV *Start = IV->getStart(); 10631 const SCEV *End = RHS; 10632 // When the RHS is not invariant, we do not know the end bound of the loop and 10633 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10634 // calculate the MaxBECount, given the start, stride and max value for the end 10635 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10636 // checked above). 10637 if (!isLoopInvariant(RHS, L)) { 10638 const SCEV *MaxBECount = computeMaxBECountForLT( 10639 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10640 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10641 false /*MaxOrZero*/, Predicates); 10642 } 10643 // If the backedge is taken at least once, then it will be taken 10644 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10645 // is the LHS value of the less-than comparison the first time it is evaluated 10646 // and End is the RHS. 10647 const SCEV *BECountIfBackedgeTaken = 10648 computeBECount(getMinusSCEV(End, Start), Stride, false); 10649 // If the loop entry is guarded by the result of the backedge test of the 10650 // first loop iteration, then we know the backedge will be taken at least 10651 // once and so the backedge taken count is as above. If not then we use the 10652 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10653 // as if the backedge is taken at least once max(End,Start) is End and so the 10654 // result is as above, and if not max(End,Start) is Start so we get a backedge 10655 // count of zero. 10656 const SCEV *BECount; 10657 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10658 BECount = BECountIfBackedgeTaken; 10659 else { 10660 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10661 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10662 } 10663 10664 const SCEV *MaxBECount; 10665 bool MaxOrZero = false; 10666 if (isa<SCEVConstant>(BECount)) 10667 MaxBECount = BECount; 10668 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10669 // If we know exactly how many times the backedge will be taken if it's 10670 // taken at least once, then the backedge count will either be that or 10671 // zero. 10672 MaxBECount = BECountIfBackedgeTaken; 10673 MaxOrZero = true; 10674 } else { 10675 MaxBECount = computeMaxBECountForLT( 10676 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10677 } 10678 10679 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10680 !isa<SCEVCouldNotCompute>(BECount)) 10681 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10682 10683 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10684 } 10685 10686 ScalarEvolution::ExitLimit 10687 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10688 const Loop *L, bool IsSigned, 10689 bool ControlsExit, bool AllowPredicates) { 10690 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10691 // We handle only IV > Invariant 10692 if (!isLoopInvariant(RHS, L)) 10693 return getCouldNotCompute(); 10694 10695 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10696 if (!IV && AllowPredicates) 10697 // Try to make this an AddRec using runtime tests, in the first X 10698 // iterations of this loop, where X is the SCEV expression found by the 10699 // algorithm below. 10700 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10701 10702 // Avoid weird loops 10703 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10704 return getCouldNotCompute(); 10705 10706 bool NoWrap = ControlsExit && 10707 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10708 10709 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10710 10711 // Avoid negative or zero stride values 10712 if (!isKnownPositive(Stride)) 10713 return getCouldNotCompute(); 10714 10715 // Avoid proven overflow cases: this will ensure that the backedge taken count 10716 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10717 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10718 // behaviors like the case of C language. 10719 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10720 return getCouldNotCompute(); 10721 10722 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10723 : ICmpInst::ICMP_UGT; 10724 10725 const SCEV *Start = IV->getStart(); 10726 const SCEV *End = RHS; 10727 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10728 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10729 10730 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10731 10732 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10733 : getUnsignedRangeMax(Start); 10734 10735 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10736 : getUnsignedRangeMin(Stride); 10737 10738 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10739 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10740 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10741 10742 // Although End can be a MIN expression we estimate MinEnd considering only 10743 // the case End = RHS. This is safe because in the other case (Start - End) 10744 // is zero, leading to a zero maximum backedge taken count. 10745 APInt MinEnd = 10746 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10747 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10748 10749 10750 const SCEV *MaxBECount = getCouldNotCompute(); 10751 if (isa<SCEVConstant>(BECount)) 10752 MaxBECount = BECount; 10753 else 10754 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 10755 getConstant(MinStride), false); 10756 10757 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10758 MaxBECount = BECount; 10759 10760 return ExitLimit(BECount, MaxBECount, false, Predicates); 10761 } 10762 10763 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10764 ScalarEvolution &SE) const { 10765 if (Range.isFullSet()) // Infinite loop. 10766 return SE.getCouldNotCompute(); 10767 10768 // If the start is a non-zero constant, shift the range to simplify things. 10769 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10770 if (!SC->getValue()->isZero()) { 10771 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10772 Operands[0] = SE.getZero(SC->getType()); 10773 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10774 getNoWrapFlags(FlagNW)); 10775 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10776 return ShiftedAddRec->getNumIterationsInRange( 10777 Range.subtract(SC->getAPInt()), SE); 10778 // This is strange and shouldn't happen. 10779 return SE.getCouldNotCompute(); 10780 } 10781 10782 // The only time we can solve this is when we have all constant indices. 10783 // Otherwise, we cannot determine the overflow conditions. 10784 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10785 return SE.getCouldNotCompute(); 10786 10787 // Okay at this point we know that all elements of the chrec are constants and 10788 // that the start element is zero. 10789 10790 // First check to see if the range contains zero. If not, the first 10791 // iteration exits. 10792 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10793 if (!Range.contains(APInt(BitWidth, 0))) 10794 return SE.getZero(getType()); 10795 10796 if (isAffine()) { 10797 // If this is an affine expression then we have this situation: 10798 // Solve {0,+,A} in Range === Ax in Range 10799 10800 // We know that zero is in the range. If A is positive then we know that 10801 // the upper value of the range must be the first possible exit value. 10802 // If A is negative then the lower of the range is the last possible loop 10803 // value. Also note that we already checked for a full range. 10804 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10805 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10806 10807 // The exit value should be (End+A)/A. 10808 APInt ExitVal = (End + A).udiv(A); 10809 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10810 10811 // Evaluate at the exit value. If we really did fall out of the valid 10812 // range, then we computed our trip count, otherwise wrap around or other 10813 // things must have happened. 10814 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10815 if (Range.contains(Val->getValue())) 10816 return SE.getCouldNotCompute(); // Something strange happened 10817 10818 // Ensure that the previous value is in the range. This is a sanity check. 10819 assert(Range.contains( 10820 EvaluateConstantChrecAtConstant(this, 10821 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10822 "Linear scev computation is off in a bad way!"); 10823 return SE.getConstant(ExitValue); 10824 } 10825 10826 if (isQuadratic()) { 10827 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10828 return SE.getConstant(S.getValue()); 10829 } 10830 10831 return SE.getCouldNotCompute(); 10832 } 10833 10834 const SCEVAddRecExpr * 10835 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10836 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10837 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10838 // but in this case we cannot guarantee that the value returned will be an 10839 // AddRec because SCEV does not have a fixed point where it stops 10840 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10841 // may happen if we reach arithmetic depth limit while simplifying. So we 10842 // construct the returned value explicitly. 10843 SmallVector<const SCEV *, 3> Ops; 10844 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10845 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10846 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10847 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10848 // We know that the last operand is not a constant zero (otherwise it would 10849 // have been popped out earlier). This guarantees us that if the result has 10850 // the same last operand, then it will also not be popped out, meaning that 10851 // the returned value will be an AddRec. 10852 const SCEV *Last = getOperand(getNumOperands() - 1); 10853 assert(!Last->isZero() && "Recurrency with zero step?"); 10854 Ops.push_back(Last); 10855 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10856 SCEV::FlagAnyWrap)); 10857 } 10858 10859 // Return true when S contains at least an undef value. 10860 static inline bool containsUndefs(const SCEV *S) { 10861 return SCEVExprContains(S, [](const SCEV *S) { 10862 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10863 return isa<UndefValue>(SU->getValue()); 10864 return false; 10865 }); 10866 } 10867 10868 namespace { 10869 10870 // Collect all steps of SCEV expressions. 10871 struct SCEVCollectStrides { 10872 ScalarEvolution &SE; 10873 SmallVectorImpl<const SCEV *> &Strides; 10874 10875 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10876 : SE(SE), Strides(S) {} 10877 10878 bool follow(const SCEV *S) { 10879 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10880 Strides.push_back(AR->getStepRecurrence(SE)); 10881 return true; 10882 } 10883 10884 bool isDone() const { return false; } 10885 }; 10886 10887 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10888 struct SCEVCollectTerms { 10889 SmallVectorImpl<const SCEV *> &Terms; 10890 10891 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10892 10893 bool follow(const SCEV *S) { 10894 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10895 isa<SCEVSignExtendExpr>(S)) { 10896 if (!containsUndefs(S)) 10897 Terms.push_back(S); 10898 10899 // Stop recursion: once we collected a term, do not walk its operands. 10900 return false; 10901 } 10902 10903 // Keep looking. 10904 return true; 10905 } 10906 10907 bool isDone() const { return false; } 10908 }; 10909 10910 // Check if a SCEV contains an AddRecExpr. 10911 struct SCEVHasAddRec { 10912 bool &ContainsAddRec; 10913 10914 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10915 ContainsAddRec = false; 10916 } 10917 10918 bool follow(const SCEV *S) { 10919 if (isa<SCEVAddRecExpr>(S)) { 10920 ContainsAddRec = true; 10921 10922 // Stop recursion: once we collected a term, do not walk its operands. 10923 return false; 10924 } 10925 10926 // Keep looking. 10927 return true; 10928 } 10929 10930 bool isDone() const { return false; } 10931 }; 10932 10933 // Find factors that are multiplied with an expression that (possibly as a 10934 // subexpression) contains an AddRecExpr. In the expression: 10935 // 10936 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10937 // 10938 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10939 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10940 // parameters as they form a product with an induction variable. 10941 // 10942 // This collector expects all array size parameters to be in the same MulExpr. 10943 // It might be necessary to later add support for collecting parameters that are 10944 // spread over different nested MulExpr. 10945 struct SCEVCollectAddRecMultiplies { 10946 SmallVectorImpl<const SCEV *> &Terms; 10947 ScalarEvolution &SE; 10948 10949 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10950 : Terms(T), SE(SE) {} 10951 10952 bool follow(const SCEV *S) { 10953 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10954 bool HasAddRec = false; 10955 SmallVector<const SCEV *, 0> Operands; 10956 for (auto Op : Mul->operands()) { 10957 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10958 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10959 Operands.push_back(Op); 10960 } else if (Unknown) { 10961 HasAddRec = true; 10962 } else { 10963 bool ContainsAddRec; 10964 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10965 visitAll(Op, ContiansAddRec); 10966 HasAddRec |= ContainsAddRec; 10967 } 10968 } 10969 if (Operands.size() == 0) 10970 return true; 10971 10972 if (!HasAddRec) 10973 return false; 10974 10975 Terms.push_back(SE.getMulExpr(Operands)); 10976 // Stop recursion: once we collected a term, do not walk its operands. 10977 return false; 10978 } 10979 10980 // Keep looking. 10981 return true; 10982 } 10983 10984 bool isDone() const { return false; } 10985 }; 10986 10987 } // end anonymous namespace 10988 10989 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 10990 /// two places: 10991 /// 1) The strides of AddRec expressions. 10992 /// 2) Unknowns that are multiplied with AddRec expressions. 10993 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 10994 SmallVectorImpl<const SCEV *> &Terms) { 10995 SmallVector<const SCEV *, 4> Strides; 10996 SCEVCollectStrides StrideCollector(*this, Strides); 10997 visitAll(Expr, StrideCollector); 10998 10999 LLVM_DEBUG({ 11000 dbgs() << "Strides:\n"; 11001 for (const SCEV *S : Strides) 11002 dbgs() << *S << "\n"; 11003 }); 11004 11005 for (const SCEV *S : Strides) { 11006 SCEVCollectTerms TermCollector(Terms); 11007 visitAll(S, TermCollector); 11008 } 11009 11010 LLVM_DEBUG({ 11011 dbgs() << "Terms:\n"; 11012 for (const SCEV *T : Terms) 11013 dbgs() << *T << "\n"; 11014 }); 11015 11016 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11017 visitAll(Expr, MulCollector); 11018 } 11019 11020 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11021 SmallVectorImpl<const SCEV *> &Terms, 11022 SmallVectorImpl<const SCEV *> &Sizes) { 11023 int Last = Terms.size() - 1; 11024 const SCEV *Step = Terms[Last]; 11025 11026 // End of recursion. 11027 if (Last == 0) { 11028 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11029 SmallVector<const SCEV *, 2> Qs; 11030 for (const SCEV *Op : M->operands()) 11031 if (!isa<SCEVConstant>(Op)) 11032 Qs.push_back(Op); 11033 11034 Step = SE.getMulExpr(Qs); 11035 } 11036 11037 Sizes.push_back(Step); 11038 return true; 11039 } 11040 11041 for (const SCEV *&Term : Terms) { 11042 // Normalize the terms before the next call to findArrayDimensionsRec. 11043 const SCEV *Q, *R; 11044 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11045 11046 // Bail out when GCD does not evenly divide one of the terms. 11047 if (!R->isZero()) 11048 return false; 11049 11050 Term = Q; 11051 } 11052 11053 // Remove all SCEVConstants. 11054 Terms.erase( 11055 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11056 Terms.end()); 11057 11058 if (Terms.size() > 0) 11059 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11060 return false; 11061 11062 Sizes.push_back(Step); 11063 return true; 11064 } 11065 11066 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11067 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11068 for (const SCEV *T : Terms) 11069 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 11070 return true; 11071 return false; 11072 } 11073 11074 // Return the number of product terms in S. 11075 static inline int numberOfTerms(const SCEV *S) { 11076 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11077 return Expr->getNumOperands(); 11078 return 1; 11079 } 11080 11081 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11082 if (isa<SCEVConstant>(T)) 11083 return nullptr; 11084 11085 if (isa<SCEVUnknown>(T)) 11086 return T; 11087 11088 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11089 SmallVector<const SCEV *, 2> Factors; 11090 for (const SCEV *Op : M->operands()) 11091 if (!isa<SCEVConstant>(Op)) 11092 Factors.push_back(Op); 11093 11094 return SE.getMulExpr(Factors); 11095 } 11096 11097 return T; 11098 } 11099 11100 /// Return the size of an element read or written by Inst. 11101 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11102 Type *Ty; 11103 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11104 Ty = Store->getValueOperand()->getType(); 11105 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11106 Ty = Load->getType(); 11107 else 11108 return nullptr; 11109 11110 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11111 return getSizeOfExpr(ETy, Ty); 11112 } 11113 11114 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11115 SmallVectorImpl<const SCEV *> &Sizes, 11116 const SCEV *ElementSize) { 11117 if (Terms.size() < 1 || !ElementSize) 11118 return; 11119 11120 // Early return when Terms do not contain parameters: we do not delinearize 11121 // non parametric SCEVs. 11122 if (!containsParameters(Terms)) 11123 return; 11124 11125 LLVM_DEBUG({ 11126 dbgs() << "Terms:\n"; 11127 for (const SCEV *T : Terms) 11128 dbgs() << *T << "\n"; 11129 }); 11130 11131 // Remove duplicates. 11132 array_pod_sort(Terms.begin(), Terms.end()); 11133 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11134 11135 // Put larger terms first. 11136 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11137 return numberOfTerms(LHS) > numberOfTerms(RHS); 11138 }); 11139 11140 // Try to divide all terms by the element size. If term is not divisible by 11141 // element size, proceed with the original term. 11142 for (const SCEV *&Term : Terms) { 11143 const SCEV *Q, *R; 11144 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11145 if (!Q->isZero()) 11146 Term = Q; 11147 } 11148 11149 SmallVector<const SCEV *, 4> NewTerms; 11150 11151 // Remove constant factors. 11152 for (const SCEV *T : Terms) 11153 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11154 NewTerms.push_back(NewT); 11155 11156 LLVM_DEBUG({ 11157 dbgs() << "Terms after sorting:\n"; 11158 for (const SCEV *T : NewTerms) 11159 dbgs() << *T << "\n"; 11160 }); 11161 11162 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11163 Sizes.clear(); 11164 return; 11165 } 11166 11167 // The last element to be pushed into Sizes is the size of an element. 11168 Sizes.push_back(ElementSize); 11169 11170 LLVM_DEBUG({ 11171 dbgs() << "Sizes:\n"; 11172 for (const SCEV *S : Sizes) 11173 dbgs() << *S << "\n"; 11174 }); 11175 } 11176 11177 void ScalarEvolution::computeAccessFunctions( 11178 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11179 SmallVectorImpl<const SCEV *> &Sizes) { 11180 // Early exit in case this SCEV is not an affine multivariate function. 11181 if (Sizes.empty()) 11182 return; 11183 11184 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11185 if (!AR->isAffine()) 11186 return; 11187 11188 const SCEV *Res = Expr; 11189 int Last = Sizes.size() - 1; 11190 for (int i = Last; i >= 0; i--) { 11191 const SCEV *Q, *R; 11192 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11193 11194 LLVM_DEBUG({ 11195 dbgs() << "Res: " << *Res << "\n"; 11196 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11197 dbgs() << "Res divided by Sizes[i]:\n"; 11198 dbgs() << "Quotient: " << *Q << "\n"; 11199 dbgs() << "Remainder: " << *R << "\n"; 11200 }); 11201 11202 Res = Q; 11203 11204 // Do not record the last subscript corresponding to the size of elements in 11205 // the array. 11206 if (i == Last) { 11207 11208 // Bail out if the remainder is too complex. 11209 if (isa<SCEVAddRecExpr>(R)) { 11210 Subscripts.clear(); 11211 Sizes.clear(); 11212 return; 11213 } 11214 11215 continue; 11216 } 11217 11218 // Record the access function for the current subscript. 11219 Subscripts.push_back(R); 11220 } 11221 11222 // Also push in last position the remainder of the last division: it will be 11223 // the access function of the innermost dimension. 11224 Subscripts.push_back(Res); 11225 11226 std::reverse(Subscripts.begin(), Subscripts.end()); 11227 11228 LLVM_DEBUG({ 11229 dbgs() << "Subscripts:\n"; 11230 for (const SCEV *S : Subscripts) 11231 dbgs() << *S << "\n"; 11232 }); 11233 } 11234 11235 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11236 /// sizes of an array access. Returns the remainder of the delinearization that 11237 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11238 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11239 /// expressions in the stride and base of a SCEV corresponding to the 11240 /// computation of a GCD (greatest common divisor) of base and stride. When 11241 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11242 /// 11243 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11244 /// 11245 /// void foo(long n, long m, long o, double A[n][m][o]) { 11246 /// 11247 /// for (long i = 0; i < n; i++) 11248 /// for (long j = 0; j < m; j++) 11249 /// for (long k = 0; k < o; k++) 11250 /// A[i][j][k] = 1.0; 11251 /// } 11252 /// 11253 /// the delinearization input is the following AddRec SCEV: 11254 /// 11255 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11256 /// 11257 /// From this SCEV, we are able to say that the base offset of the access is %A 11258 /// because it appears as an offset that does not divide any of the strides in 11259 /// the loops: 11260 /// 11261 /// CHECK: Base offset: %A 11262 /// 11263 /// and then SCEV->delinearize determines the size of some of the dimensions of 11264 /// the array as these are the multiples by which the strides are happening: 11265 /// 11266 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11267 /// 11268 /// Note that the outermost dimension remains of UnknownSize because there are 11269 /// no strides that would help identifying the size of the last dimension: when 11270 /// the array has been statically allocated, one could compute the size of that 11271 /// dimension by dividing the overall size of the array by the size of the known 11272 /// dimensions: %m * %o * 8. 11273 /// 11274 /// Finally delinearize provides the access functions for the array reference 11275 /// that does correspond to A[i][j][k] of the above C testcase: 11276 /// 11277 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11278 /// 11279 /// The testcases are checking the output of a function pass: 11280 /// DelinearizationPass that walks through all loads and stores of a function 11281 /// asking for the SCEV of the memory access with respect to all enclosing 11282 /// loops, calling SCEV->delinearize on that and printing the results. 11283 void ScalarEvolution::delinearize(const SCEV *Expr, 11284 SmallVectorImpl<const SCEV *> &Subscripts, 11285 SmallVectorImpl<const SCEV *> &Sizes, 11286 const SCEV *ElementSize) { 11287 // First step: collect parametric terms. 11288 SmallVector<const SCEV *, 4> Terms; 11289 collectParametricTerms(Expr, Terms); 11290 11291 if (Terms.empty()) 11292 return; 11293 11294 // Second step: find subscript sizes. 11295 findArrayDimensions(Terms, Sizes, ElementSize); 11296 11297 if (Sizes.empty()) 11298 return; 11299 11300 // Third step: compute the access functions for each subscript. 11301 computeAccessFunctions(Expr, Subscripts, Sizes); 11302 11303 if (Subscripts.empty()) 11304 return; 11305 11306 LLVM_DEBUG({ 11307 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11308 dbgs() << "ArrayDecl[UnknownSize]"; 11309 for (const SCEV *S : Sizes) 11310 dbgs() << "[" << *S << "]"; 11311 11312 dbgs() << "\nArrayRef"; 11313 for (const SCEV *S : Subscripts) 11314 dbgs() << "[" << *S << "]"; 11315 dbgs() << "\n"; 11316 }); 11317 } 11318 11319 //===----------------------------------------------------------------------===// 11320 // SCEVCallbackVH Class Implementation 11321 //===----------------------------------------------------------------------===// 11322 11323 void ScalarEvolution::SCEVCallbackVH::deleted() { 11324 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11325 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11326 SE->ConstantEvolutionLoopExitValue.erase(PN); 11327 SE->eraseValueFromMap(getValPtr()); 11328 // this now dangles! 11329 } 11330 11331 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11332 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11333 11334 // Forget all the expressions associated with users of the old value, 11335 // so that future queries will recompute the expressions using the new 11336 // value. 11337 Value *Old = getValPtr(); 11338 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11339 SmallPtrSet<User *, 8> Visited; 11340 while (!Worklist.empty()) { 11341 User *U = Worklist.pop_back_val(); 11342 // Deleting the Old value will cause this to dangle. Postpone 11343 // that until everything else is done. 11344 if (U == Old) 11345 continue; 11346 if (!Visited.insert(U).second) 11347 continue; 11348 if (PHINode *PN = dyn_cast<PHINode>(U)) 11349 SE->ConstantEvolutionLoopExitValue.erase(PN); 11350 SE->eraseValueFromMap(U); 11351 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11352 } 11353 // Delete the Old value. 11354 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11355 SE->ConstantEvolutionLoopExitValue.erase(PN); 11356 SE->eraseValueFromMap(Old); 11357 // this now dangles! 11358 } 11359 11360 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11361 : CallbackVH(V), SE(se) {} 11362 11363 //===----------------------------------------------------------------------===// 11364 // ScalarEvolution Class Implementation 11365 //===----------------------------------------------------------------------===// 11366 11367 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11368 AssumptionCache &AC, DominatorTree &DT, 11369 LoopInfo &LI) 11370 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11371 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11372 LoopDispositions(64), BlockDispositions(64) { 11373 // To use guards for proving predicates, we need to scan every instruction in 11374 // relevant basic blocks, and not just terminators. Doing this is a waste of 11375 // time if the IR does not actually contain any calls to 11376 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11377 // 11378 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11379 // to _add_ guards to the module when there weren't any before, and wants 11380 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11381 // efficient in lieu of being smart in that rather obscure case. 11382 11383 auto *GuardDecl = F.getParent()->getFunction( 11384 Intrinsic::getName(Intrinsic::experimental_guard)); 11385 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11386 } 11387 11388 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11389 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11390 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11391 ValueExprMap(std::move(Arg.ValueExprMap)), 11392 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11393 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11394 PendingMerges(std::move(Arg.PendingMerges)), 11395 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11396 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11397 PredicatedBackedgeTakenCounts( 11398 std::move(Arg.PredicatedBackedgeTakenCounts)), 11399 ConstantEvolutionLoopExitValue( 11400 std::move(Arg.ConstantEvolutionLoopExitValue)), 11401 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11402 LoopDispositions(std::move(Arg.LoopDispositions)), 11403 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11404 BlockDispositions(std::move(Arg.BlockDispositions)), 11405 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11406 SignedRanges(std::move(Arg.SignedRanges)), 11407 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11408 UniquePreds(std::move(Arg.UniquePreds)), 11409 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11410 LoopUsers(std::move(Arg.LoopUsers)), 11411 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11412 FirstUnknown(Arg.FirstUnknown) { 11413 Arg.FirstUnknown = nullptr; 11414 } 11415 11416 ScalarEvolution::~ScalarEvolution() { 11417 // Iterate through all the SCEVUnknown instances and call their 11418 // destructors, so that they release their references to their values. 11419 for (SCEVUnknown *U = FirstUnknown; U;) { 11420 SCEVUnknown *Tmp = U; 11421 U = U->Next; 11422 Tmp->~SCEVUnknown(); 11423 } 11424 FirstUnknown = nullptr; 11425 11426 ExprValueMap.clear(); 11427 ValueExprMap.clear(); 11428 HasRecMap.clear(); 11429 11430 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11431 // that a loop had multiple computable exits. 11432 for (auto &BTCI : BackedgeTakenCounts) 11433 BTCI.second.clear(); 11434 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11435 BTCI.second.clear(); 11436 11437 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11438 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11439 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11440 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11441 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11442 } 11443 11444 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11445 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11446 } 11447 11448 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11449 const Loop *L) { 11450 // Print all inner loops first 11451 for (Loop *I : *L) 11452 PrintLoopInfo(OS, SE, I); 11453 11454 OS << "Loop "; 11455 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11456 OS << ": "; 11457 11458 SmallVector<BasicBlock *, 8> ExitBlocks; 11459 L->getExitBlocks(ExitBlocks); 11460 if (ExitBlocks.size() != 1) 11461 OS << "<multiple exits> "; 11462 11463 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11464 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 11465 } else { 11466 OS << "Unpredictable backedge-taken count. "; 11467 } 11468 11469 OS << "\n" 11470 "Loop "; 11471 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11472 OS << ": "; 11473 11474 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 11475 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 11476 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11477 OS << ", actual taken count either this or zero."; 11478 } else { 11479 OS << "Unpredictable max backedge-taken count. "; 11480 } 11481 11482 OS << "\n" 11483 "Loop "; 11484 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11485 OS << ": "; 11486 11487 SCEVUnionPredicate Pred; 11488 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11489 if (!isa<SCEVCouldNotCompute>(PBT)) { 11490 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11491 OS << " Predicates:\n"; 11492 Pred.print(OS, 4); 11493 } else { 11494 OS << "Unpredictable predicated backedge-taken count. "; 11495 } 11496 OS << "\n"; 11497 11498 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11499 OS << "Loop "; 11500 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11501 OS << ": "; 11502 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11503 } 11504 } 11505 11506 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11507 switch (LD) { 11508 case ScalarEvolution::LoopVariant: 11509 return "Variant"; 11510 case ScalarEvolution::LoopInvariant: 11511 return "Invariant"; 11512 case ScalarEvolution::LoopComputable: 11513 return "Computable"; 11514 } 11515 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11516 } 11517 11518 void ScalarEvolution::print(raw_ostream &OS) const { 11519 // ScalarEvolution's implementation of the print method is to print 11520 // out SCEV values of all instructions that are interesting. Doing 11521 // this potentially causes it to create new SCEV objects though, 11522 // which technically conflicts with the const qualifier. This isn't 11523 // observable from outside the class though, so casting away the 11524 // const isn't dangerous. 11525 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11526 11527 OS << "Classifying expressions for: "; 11528 F.printAsOperand(OS, /*PrintType=*/false); 11529 OS << "\n"; 11530 for (Instruction &I : instructions(F)) 11531 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11532 OS << I << '\n'; 11533 OS << " --> "; 11534 const SCEV *SV = SE.getSCEV(&I); 11535 SV->print(OS); 11536 if (!isa<SCEVCouldNotCompute>(SV)) { 11537 OS << " U: "; 11538 SE.getUnsignedRange(SV).print(OS); 11539 OS << " S: "; 11540 SE.getSignedRange(SV).print(OS); 11541 } 11542 11543 const Loop *L = LI.getLoopFor(I.getParent()); 11544 11545 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11546 if (AtUse != SV) { 11547 OS << " --> "; 11548 AtUse->print(OS); 11549 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11550 OS << " U: "; 11551 SE.getUnsignedRange(AtUse).print(OS); 11552 OS << " S: "; 11553 SE.getSignedRange(AtUse).print(OS); 11554 } 11555 } 11556 11557 if (L) { 11558 OS << "\t\t" "Exits: "; 11559 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11560 if (!SE.isLoopInvariant(ExitValue, L)) { 11561 OS << "<<Unknown>>"; 11562 } else { 11563 OS << *ExitValue; 11564 } 11565 11566 bool First = true; 11567 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11568 if (First) { 11569 OS << "\t\t" "LoopDispositions: { "; 11570 First = false; 11571 } else { 11572 OS << ", "; 11573 } 11574 11575 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11576 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11577 } 11578 11579 for (auto *InnerL : depth_first(L)) { 11580 if (InnerL == L) 11581 continue; 11582 if (First) { 11583 OS << "\t\t" "LoopDispositions: { "; 11584 First = false; 11585 } else { 11586 OS << ", "; 11587 } 11588 11589 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11590 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11591 } 11592 11593 OS << " }"; 11594 } 11595 11596 OS << "\n"; 11597 } 11598 11599 OS << "Determining loop execution counts for: "; 11600 F.printAsOperand(OS, /*PrintType=*/false); 11601 OS << "\n"; 11602 for (Loop *I : LI) 11603 PrintLoopInfo(OS, &SE, I); 11604 } 11605 11606 ScalarEvolution::LoopDisposition 11607 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11608 auto &Values = LoopDispositions[S]; 11609 for (auto &V : Values) { 11610 if (V.getPointer() == L) 11611 return V.getInt(); 11612 } 11613 Values.emplace_back(L, LoopVariant); 11614 LoopDisposition D = computeLoopDisposition(S, L); 11615 auto &Values2 = LoopDispositions[S]; 11616 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11617 if (V.getPointer() == L) { 11618 V.setInt(D); 11619 break; 11620 } 11621 } 11622 return D; 11623 } 11624 11625 ScalarEvolution::LoopDisposition 11626 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11627 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11628 case scConstant: 11629 return LoopInvariant; 11630 case scTruncate: 11631 case scZeroExtend: 11632 case scSignExtend: 11633 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11634 case scAddRecExpr: { 11635 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11636 11637 // If L is the addrec's loop, it's computable. 11638 if (AR->getLoop() == L) 11639 return LoopComputable; 11640 11641 // Add recurrences are never invariant in the function-body (null loop). 11642 if (!L) 11643 return LoopVariant; 11644 11645 // Everything that is not defined at loop entry is variant. 11646 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11647 return LoopVariant; 11648 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11649 " dominate the contained loop's header?"); 11650 11651 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11652 if (AR->getLoop()->contains(L)) 11653 return LoopInvariant; 11654 11655 // This recurrence is variant w.r.t. L if any of its operands 11656 // are variant. 11657 for (auto *Op : AR->operands()) 11658 if (!isLoopInvariant(Op, L)) 11659 return LoopVariant; 11660 11661 // Otherwise it's loop-invariant. 11662 return LoopInvariant; 11663 } 11664 case scAddExpr: 11665 case scMulExpr: 11666 case scUMaxExpr: 11667 case scSMaxExpr: { 11668 bool HasVarying = false; 11669 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11670 LoopDisposition D = getLoopDisposition(Op, L); 11671 if (D == LoopVariant) 11672 return LoopVariant; 11673 if (D == LoopComputable) 11674 HasVarying = true; 11675 } 11676 return HasVarying ? LoopComputable : LoopInvariant; 11677 } 11678 case scUDivExpr: { 11679 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11680 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11681 if (LD == LoopVariant) 11682 return LoopVariant; 11683 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11684 if (RD == LoopVariant) 11685 return LoopVariant; 11686 return (LD == LoopInvariant && RD == LoopInvariant) ? 11687 LoopInvariant : LoopComputable; 11688 } 11689 case scUnknown: 11690 // All non-instruction values are loop invariant. All instructions are loop 11691 // invariant if they are not contained in the specified loop. 11692 // Instructions are never considered invariant in the function body 11693 // (null loop) because they are defined within the "loop". 11694 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11695 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11696 return LoopInvariant; 11697 case scCouldNotCompute: 11698 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11699 } 11700 llvm_unreachable("Unknown SCEV kind!"); 11701 } 11702 11703 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11704 return getLoopDisposition(S, L) == LoopInvariant; 11705 } 11706 11707 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11708 return getLoopDisposition(S, L) == LoopComputable; 11709 } 11710 11711 ScalarEvolution::BlockDisposition 11712 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11713 auto &Values = BlockDispositions[S]; 11714 for (auto &V : Values) { 11715 if (V.getPointer() == BB) 11716 return V.getInt(); 11717 } 11718 Values.emplace_back(BB, DoesNotDominateBlock); 11719 BlockDisposition D = computeBlockDisposition(S, BB); 11720 auto &Values2 = BlockDispositions[S]; 11721 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11722 if (V.getPointer() == BB) { 11723 V.setInt(D); 11724 break; 11725 } 11726 } 11727 return D; 11728 } 11729 11730 ScalarEvolution::BlockDisposition 11731 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11732 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11733 case scConstant: 11734 return ProperlyDominatesBlock; 11735 case scTruncate: 11736 case scZeroExtend: 11737 case scSignExtend: 11738 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11739 case scAddRecExpr: { 11740 // This uses a "dominates" query instead of "properly dominates" query 11741 // to test for proper dominance too, because the instruction which 11742 // produces the addrec's value is a PHI, and a PHI effectively properly 11743 // dominates its entire containing block. 11744 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11745 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11746 return DoesNotDominateBlock; 11747 11748 // Fall through into SCEVNAryExpr handling. 11749 LLVM_FALLTHROUGH; 11750 } 11751 case scAddExpr: 11752 case scMulExpr: 11753 case scUMaxExpr: 11754 case scSMaxExpr: { 11755 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11756 bool Proper = true; 11757 for (const SCEV *NAryOp : NAry->operands()) { 11758 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11759 if (D == DoesNotDominateBlock) 11760 return DoesNotDominateBlock; 11761 if (D == DominatesBlock) 11762 Proper = false; 11763 } 11764 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11765 } 11766 case scUDivExpr: { 11767 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11768 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11769 BlockDisposition LD = getBlockDisposition(LHS, BB); 11770 if (LD == DoesNotDominateBlock) 11771 return DoesNotDominateBlock; 11772 BlockDisposition RD = getBlockDisposition(RHS, BB); 11773 if (RD == DoesNotDominateBlock) 11774 return DoesNotDominateBlock; 11775 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11776 ProperlyDominatesBlock : DominatesBlock; 11777 } 11778 case scUnknown: 11779 if (Instruction *I = 11780 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11781 if (I->getParent() == BB) 11782 return DominatesBlock; 11783 if (DT.properlyDominates(I->getParent(), BB)) 11784 return ProperlyDominatesBlock; 11785 return DoesNotDominateBlock; 11786 } 11787 return ProperlyDominatesBlock; 11788 case scCouldNotCompute: 11789 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11790 } 11791 llvm_unreachable("Unknown SCEV kind!"); 11792 } 11793 11794 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11795 return getBlockDisposition(S, BB) >= DominatesBlock; 11796 } 11797 11798 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11799 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11800 } 11801 11802 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11803 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11804 } 11805 11806 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11807 auto IsS = [&](const SCEV *X) { return S == X; }; 11808 auto ContainsS = [&](const SCEV *X) { 11809 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11810 }; 11811 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11812 } 11813 11814 void 11815 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11816 ValuesAtScopes.erase(S); 11817 LoopDispositions.erase(S); 11818 BlockDispositions.erase(S); 11819 UnsignedRanges.erase(S); 11820 SignedRanges.erase(S); 11821 ExprValueMap.erase(S); 11822 HasRecMap.erase(S); 11823 MinTrailingZerosCache.erase(S); 11824 11825 for (auto I = PredicatedSCEVRewrites.begin(); 11826 I != PredicatedSCEVRewrites.end();) { 11827 std::pair<const SCEV *, const Loop *> Entry = I->first; 11828 if (Entry.first == S) 11829 PredicatedSCEVRewrites.erase(I++); 11830 else 11831 ++I; 11832 } 11833 11834 auto RemoveSCEVFromBackedgeMap = 11835 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11836 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11837 BackedgeTakenInfo &BEInfo = I->second; 11838 if (BEInfo.hasOperand(S, this)) { 11839 BEInfo.clear(); 11840 Map.erase(I++); 11841 } else 11842 ++I; 11843 } 11844 }; 11845 11846 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11847 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11848 } 11849 11850 void 11851 ScalarEvolution::getUsedLoops(const SCEV *S, 11852 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11853 struct FindUsedLoops { 11854 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11855 : LoopsUsed(LoopsUsed) {} 11856 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11857 bool follow(const SCEV *S) { 11858 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11859 LoopsUsed.insert(AR->getLoop()); 11860 return true; 11861 } 11862 11863 bool isDone() const { return false; } 11864 }; 11865 11866 FindUsedLoops F(LoopsUsed); 11867 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11868 } 11869 11870 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11871 SmallPtrSet<const Loop *, 8> LoopsUsed; 11872 getUsedLoops(S, LoopsUsed); 11873 for (auto *L : LoopsUsed) 11874 LoopUsers[L].push_back(S); 11875 } 11876 11877 void ScalarEvolution::verify() const { 11878 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11879 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11880 11881 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11882 11883 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11884 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11885 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11886 11887 const SCEV *visitConstant(const SCEVConstant *Constant) { 11888 return SE.getConstant(Constant->getAPInt()); 11889 } 11890 11891 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11892 return SE.getUnknown(Expr->getValue()); 11893 } 11894 11895 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11896 return SE.getCouldNotCompute(); 11897 } 11898 }; 11899 11900 SCEVMapper SCM(SE2); 11901 11902 while (!LoopStack.empty()) { 11903 auto *L = LoopStack.pop_back_val(); 11904 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11905 11906 auto *CurBECount = SCM.visit( 11907 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11908 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11909 11910 if (CurBECount == SE2.getCouldNotCompute() || 11911 NewBECount == SE2.getCouldNotCompute()) { 11912 // NB! This situation is legal, but is very suspicious -- whatever pass 11913 // change the loop to make a trip count go from could not compute to 11914 // computable or vice-versa *should have* invalidated SCEV. However, we 11915 // choose not to assert here (for now) since we don't want false 11916 // positives. 11917 continue; 11918 } 11919 11920 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11921 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11922 // not propagate undef aggressively). This means we can (and do) fail 11923 // verification in cases where a transform makes the trip count of a loop 11924 // go from "undef" to "undef+1" (say). The transform is fine, since in 11925 // both cases the loop iterates "undef" times, but SCEV thinks we 11926 // increased the trip count of the loop by 1 incorrectly. 11927 continue; 11928 } 11929 11930 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11931 SE.getTypeSizeInBits(NewBECount->getType())) 11932 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11933 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11934 SE.getTypeSizeInBits(NewBECount->getType())) 11935 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11936 11937 auto *ConstantDelta = 11938 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 11939 11940 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 11941 dbgs() << "Trip Count Changed!\n"; 11942 dbgs() << "Old: " << *CurBECount << "\n"; 11943 dbgs() << "New: " << *NewBECount << "\n"; 11944 dbgs() << "Delta: " << *ConstantDelta << "\n"; 11945 std::abort(); 11946 } 11947 } 11948 } 11949 11950 bool ScalarEvolution::invalidate( 11951 Function &F, const PreservedAnalyses &PA, 11952 FunctionAnalysisManager::Invalidator &Inv) { 11953 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11954 // of its dependencies is invalidated. 11955 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11956 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11957 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11958 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11959 Inv.invalidate<LoopAnalysis>(F, PA); 11960 } 11961 11962 AnalysisKey ScalarEvolutionAnalysis::Key; 11963 11964 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11965 FunctionAnalysisManager &AM) { 11966 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11967 AM.getResult<AssumptionAnalysis>(F), 11968 AM.getResult<DominatorTreeAnalysis>(F), 11969 AM.getResult<LoopAnalysis>(F)); 11970 } 11971 11972 PreservedAnalyses 11973 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11974 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11975 return PreservedAnalyses::all(); 11976 } 11977 11978 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 11979 "Scalar Evolution Analysis", false, true) 11980 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 11981 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 11982 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 11983 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 11984 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 11985 "Scalar Evolution Analysis", false, true) 11986 11987 char ScalarEvolutionWrapperPass::ID = 0; 11988 11989 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 11990 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 11991 } 11992 11993 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 11994 SE.reset(new ScalarEvolution( 11995 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 11996 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 11997 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 11998 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 11999 return false; 12000 } 12001 12002 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12003 12004 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12005 SE->print(OS); 12006 } 12007 12008 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12009 if (!VerifySCEV) 12010 return; 12011 12012 SE->verify(); 12013 } 12014 12015 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12016 AU.setPreservesAll(); 12017 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12018 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12019 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12020 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12021 } 12022 12023 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12024 const SCEV *RHS) { 12025 FoldingSetNodeID ID; 12026 assert(LHS->getType() == RHS->getType() && 12027 "Type mismatch between LHS and RHS"); 12028 // Unique this node based on the arguments 12029 ID.AddInteger(SCEVPredicate::P_Equal); 12030 ID.AddPointer(LHS); 12031 ID.AddPointer(RHS); 12032 void *IP = nullptr; 12033 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12034 return S; 12035 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12036 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12037 UniquePreds.InsertNode(Eq, IP); 12038 return Eq; 12039 } 12040 12041 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12042 const SCEVAddRecExpr *AR, 12043 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12044 FoldingSetNodeID ID; 12045 // Unique this node based on the arguments 12046 ID.AddInteger(SCEVPredicate::P_Wrap); 12047 ID.AddPointer(AR); 12048 ID.AddInteger(AddedFlags); 12049 void *IP = nullptr; 12050 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12051 return S; 12052 auto *OF = new (SCEVAllocator) 12053 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12054 UniquePreds.InsertNode(OF, IP); 12055 return OF; 12056 } 12057 12058 namespace { 12059 12060 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12061 public: 12062 12063 /// Rewrites \p S in the context of a loop L and the SCEV predication 12064 /// infrastructure. 12065 /// 12066 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12067 /// equivalences present in \p Pred. 12068 /// 12069 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12070 /// \p NewPreds such that the result will be an AddRecExpr. 12071 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12072 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12073 SCEVUnionPredicate *Pred) { 12074 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12075 return Rewriter.visit(S); 12076 } 12077 12078 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12079 if (Pred) { 12080 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12081 for (auto *Pred : ExprPreds) 12082 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12083 if (IPred->getLHS() == Expr) 12084 return IPred->getRHS(); 12085 } 12086 return convertToAddRecWithPreds(Expr); 12087 } 12088 12089 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12090 const SCEV *Operand = visit(Expr->getOperand()); 12091 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12092 if (AR && AR->getLoop() == L && AR->isAffine()) { 12093 // This couldn't be folded because the operand didn't have the nuw 12094 // flag. Add the nusw flag as an assumption that we could make. 12095 const SCEV *Step = AR->getStepRecurrence(SE); 12096 Type *Ty = Expr->getType(); 12097 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12098 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12099 SE.getSignExtendExpr(Step, Ty), L, 12100 AR->getNoWrapFlags()); 12101 } 12102 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12103 } 12104 12105 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12106 const SCEV *Operand = visit(Expr->getOperand()); 12107 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12108 if (AR && AR->getLoop() == L && AR->isAffine()) { 12109 // This couldn't be folded because the operand didn't have the nsw 12110 // flag. Add the nssw flag as an assumption that we could make. 12111 const SCEV *Step = AR->getStepRecurrence(SE); 12112 Type *Ty = Expr->getType(); 12113 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12114 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12115 SE.getSignExtendExpr(Step, Ty), L, 12116 AR->getNoWrapFlags()); 12117 } 12118 return SE.getSignExtendExpr(Operand, Expr->getType()); 12119 } 12120 12121 private: 12122 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12123 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12124 SCEVUnionPredicate *Pred) 12125 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12126 12127 bool addOverflowAssumption(const SCEVPredicate *P) { 12128 if (!NewPreds) { 12129 // Check if we've already made this assumption. 12130 return Pred && Pred->implies(P); 12131 } 12132 NewPreds->insert(P); 12133 return true; 12134 } 12135 12136 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12137 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12138 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12139 return addOverflowAssumption(A); 12140 } 12141 12142 // If \p Expr represents a PHINode, we try to see if it can be represented 12143 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12144 // to add this predicate as a runtime overflow check, we return the AddRec. 12145 // If \p Expr does not meet these conditions (is not a PHI node, or we 12146 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12147 // return \p Expr. 12148 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12149 if (!isa<PHINode>(Expr->getValue())) 12150 return Expr; 12151 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12152 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12153 if (!PredicatedRewrite) 12154 return Expr; 12155 for (auto *P : PredicatedRewrite->second){ 12156 // Wrap predicates from outer loops are not supported. 12157 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12158 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12159 if (L != AR->getLoop()) 12160 return Expr; 12161 } 12162 if (!addOverflowAssumption(P)) 12163 return Expr; 12164 } 12165 return PredicatedRewrite->first; 12166 } 12167 12168 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12169 SCEVUnionPredicate *Pred; 12170 const Loop *L; 12171 }; 12172 12173 } // end anonymous namespace 12174 12175 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12176 SCEVUnionPredicate &Preds) { 12177 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12178 } 12179 12180 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12181 const SCEV *S, const Loop *L, 12182 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12183 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12184 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12185 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12186 12187 if (!AddRec) 12188 return nullptr; 12189 12190 // Since the transformation was successful, we can now transfer the SCEV 12191 // predicates. 12192 for (auto *P : TransformPreds) 12193 Preds.insert(P); 12194 12195 return AddRec; 12196 } 12197 12198 /// SCEV predicates 12199 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12200 SCEVPredicateKind Kind) 12201 : FastID(ID), Kind(Kind) {} 12202 12203 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12204 const SCEV *LHS, const SCEV *RHS) 12205 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12206 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12207 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12208 } 12209 12210 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12211 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12212 12213 if (!Op) 12214 return false; 12215 12216 return Op->LHS == LHS && Op->RHS == RHS; 12217 } 12218 12219 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12220 12221 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12222 12223 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12224 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12225 } 12226 12227 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12228 const SCEVAddRecExpr *AR, 12229 IncrementWrapFlags Flags) 12230 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12231 12232 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12233 12234 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12235 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12236 12237 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12238 } 12239 12240 bool SCEVWrapPredicate::isAlwaysTrue() const { 12241 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12242 IncrementWrapFlags IFlags = Flags; 12243 12244 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12245 IFlags = clearFlags(IFlags, IncrementNSSW); 12246 12247 return IFlags == IncrementAnyWrap; 12248 } 12249 12250 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12251 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12252 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12253 OS << "<nusw>"; 12254 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12255 OS << "<nssw>"; 12256 OS << "\n"; 12257 } 12258 12259 SCEVWrapPredicate::IncrementWrapFlags 12260 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12261 ScalarEvolution &SE) { 12262 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12263 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12264 12265 // We can safely transfer the NSW flag as NSSW. 12266 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12267 ImpliedFlags = IncrementNSSW; 12268 12269 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12270 // If the increment is positive, the SCEV NUW flag will also imply the 12271 // WrapPredicate NUSW flag. 12272 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12273 if (Step->getValue()->getValue().isNonNegative()) 12274 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12275 } 12276 12277 return ImpliedFlags; 12278 } 12279 12280 /// Union predicates don't get cached so create a dummy set ID for it. 12281 SCEVUnionPredicate::SCEVUnionPredicate() 12282 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12283 12284 bool SCEVUnionPredicate::isAlwaysTrue() const { 12285 return all_of(Preds, 12286 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12287 } 12288 12289 ArrayRef<const SCEVPredicate *> 12290 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12291 auto I = SCEVToPreds.find(Expr); 12292 if (I == SCEVToPreds.end()) 12293 return ArrayRef<const SCEVPredicate *>(); 12294 return I->second; 12295 } 12296 12297 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12298 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12299 return all_of(Set->Preds, 12300 [this](const SCEVPredicate *I) { return this->implies(I); }); 12301 12302 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12303 if (ScevPredsIt == SCEVToPreds.end()) 12304 return false; 12305 auto &SCEVPreds = ScevPredsIt->second; 12306 12307 return any_of(SCEVPreds, 12308 [N](const SCEVPredicate *I) { return I->implies(N); }); 12309 } 12310 12311 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12312 12313 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12314 for (auto Pred : Preds) 12315 Pred->print(OS, Depth); 12316 } 12317 12318 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12319 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12320 for (auto Pred : Set->Preds) 12321 add(Pred); 12322 return; 12323 } 12324 12325 if (implies(N)) 12326 return; 12327 12328 const SCEV *Key = N->getExpr(); 12329 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12330 " associated expression!"); 12331 12332 SCEVToPreds[Key].push_back(N); 12333 Preds.push_back(N); 12334 } 12335 12336 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12337 Loop &L) 12338 : SE(SE), L(L) {} 12339 12340 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12341 const SCEV *Expr = SE.getSCEV(V); 12342 RewriteEntry &Entry = RewriteMap[Expr]; 12343 12344 // If we already have an entry and the version matches, return it. 12345 if (Entry.second && Generation == Entry.first) 12346 return Entry.second; 12347 12348 // We found an entry but it's stale. Rewrite the stale entry 12349 // according to the current predicate. 12350 if (Entry.second) 12351 Expr = Entry.second; 12352 12353 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12354 Entry = {Generation, NewSCEV}; 12355 12356 return NewSCEV; 12357 } 12358 12359 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12360 if (!BackedgeCount) { 12361 SCEVUnionPredicate BackedgePred; 12362 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12363 addPredicate(BackedgePred); 12364 } 12365 return BackedgeCount; 12366 } 12367 12368 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12369 if (Preds.implies(&Pred)) 12370 return; 12371 Preds.add(&Pred); 12372 updateGeneration(); 12373 } 12374 12375 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12376 return Preds; 12377 } 12378 12379 void PredicatedScalarEvolution::updateGeneration() { 12380 // If the generation number wrapped recompute everything. 12381 if (++Generation == 0) { 12382 for (auto &II : RewriteMap) { 12383 const SCEV *Rewritten = II.second.second; 12384 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12385 } 12386 } 12387 } 12388 12389 void PredicatedScalarEvolution::setNoOverflow( 12390 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12391 const SCEV *Expr = getSCEV(V); 12392 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12393 12394 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12395 12396 // Clear the statically implied flags. 12397 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12398 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12399 12400 auto II = FlagsMap.insert({V, Flags}); 12401 if (!II.second) 12402 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12403 } 12404 12405 bool PredicatedScalarEvolution::hasNoOverflow( 12406 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12407 const SCEV *Expr = getSCEV(V); 12408 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12409 12410 Flags = SCEVWrapPredicate::clearFlags( 12411 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12412 12413 auto II = FlagsMap.find(V); 12414 12415 if (II != FlagsMap.end()) 12416 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12417 12418 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12419 } 12420 12421 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12422 const SCEV *Expr = this->getSCEV(V); 12423 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12424 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12425 12426 if (!New) 12427 return nullptr; 12428 12429 for (auto *P : NewPreds) 12430 Preds.add(P); 12431 12432 updateGeneration(); 12433 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12434 return New; 12435 } 12436 12437 PredicatedScalarEvolution::PredicatedScalarEvolution( 12438 const PredicatedScalarEvolution &Init) 12439 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12440 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12441 for (const auto &I : Init.FlagsMap) 12442 FlagsMap.insert(I); 12443 } 12444 12445 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12446 // For each block. 12447 for (auto *BB : L.getBlocks()) 12448 for (auto &I : *BB) { 12449 if (!SE.isSCEVable(I.getType())) 12450 continue; 12451 12452 auto *Expr = SE.getSCEV(&I); 12453 auto II = RewriteMap.find(Expr); 12454 12455 if (II == RewriteMap.end()) 12456 continue; 12457 12458 // Don't print things that are not interesting. 12459 if (II->second.second == Expr) 12460 continue; 12461 12462 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12463 OS.indent(Depth + 2) << *Expr << "\n"; 12464 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12465 } 12466 } 12467 12468 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12469 // arbitrary expressions. 12470 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12471 // 4, A / B becomes X / 8). 12472 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12473 const SCEV *&RHS) { 12474 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12475 if (Add == nullptr || Add->getNumOperands() != 2) 12476 return false; 12477 12478 const SCEV *A = Add->getOperand(1); 12479 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12480 12481 if (Mul == nullptr) 12482 return false; 12483 12484 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12485 // (SomeExpr + (-(SomeExpr / B) * B)). 12486 if (Expr == getURemExpr(A, B)) { 12487 LHS = A; 12488 RHS = B; 12489 return true; 12490 } 12491 return false; 12492 }; 12493 12494 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12495 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12496 return MatchURemWithDivisor(Mul->getOperand(1)) || 12497 MatchURemWithDivisor(Mul->getOperand(2)); 12498 12499 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12500 if (Mul->getNumOperands() == 2) 12501 return MatchURemWithDivisor(Mul->getOperand(1)) || 12502 MatchURemWithDivisor(Mul->getOperand(0)) || 12503 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12504 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12505 return false; 12506 } 12507