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/ScalarEvolutionDivision.h" 83 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 84 #include "llvm/Analysis/TargetLibraryInfo.h" 85 #include "llvm/Analysis/ValueTracking.h" 86 #include "llvm/Config/llvm-config.h" 87 #include "llvm/IR/Argument.h" 88 #include "llvm/IR/BasicBlock.h" 89 #include "llvm/IR/CFG.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/InitializePasses.h" 116 #include "llvm/Pass.h" 117 #include "llvm/Support/Casting.h" 118 #include "llvm/Support/CommandLine.h" 119 #include "llvm/Support/Compiler.h" 120 #include "llvm/Support/Debug.h" 121 #include "llvm/Support/ErrorHandling.h" 122 #include "llvm/Support/KnownBits.h" 123 #include "llvm/Support/SaveAndRestore.h" 124 #include "llvm/Support/raw_ostream.h" 125 #include <algorithm> 126 #include <cassert> 127 #include <climits> 128 #include <cstddef> 129 #include <cstdint> 130 #include <cstdlib> 131 #include <map> 132 #include <memory> 133 #include <tuple> 134 #include <utility> 135 #include <vector> 136 137 using namespace llvm; 138 using namespace PatternMatch; 139 140 #define DEBUG_TYPE "scalar-evolution" 141 142 STATISTIC(NumArrayLenItCounts, 143 "Number of trip counts computed with array length"); 144 STATISTIC(NumTripCountsComputed, 145 "Number of loops with predictable loop counts"); 146 STATISTIC(NumTripCountsNotComputed, 147 "Number of loops without predictable loop counts"); 148 STATISTIC(NumBruteForceTripCountsComputed, 149 "Number of loops with trip counts computed by force"); 150 151 static cl::opt<unsigned> 152 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 153 cl::ZeroOrMore, 154 cl::desc("Maximum number of iterations SCEV will " 155 "symbolically execute a constant " 156 "derived loop"), 157 cl::init(100)); 158 159 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 160 static cl::opt<bool> VerifySCEV( 161 "verify-scev", cl::Hidden, 162 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 163 static cl::opt<bool> VerifySCEVStrict( 164 "verify-scev-strict", cl::Hidden, 165 cl::desc("Enable stricter verification with -verify-scev is passed")); 166 static cl::opt<bool> 167 VerifySCEVMap("verify-scev-maps", cl::Hidden, 168 cl::desc("Verify no dangling value in ScalarEvolution's " 169 "ExprValueMap (slow)")); 170 171 static cl::opt<bool> VerifyIR( 172 "scev-verify-ir", cl::Hidden, 173 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 174 cl::init(false)); 175 176 static cl::opt<unsigned> MulOpsInlineThreshold( 177 "scev-mulops-inline-threshold", cl::Hidden, 178 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 179 cl::init(32)); 180 181 static cl::opt<unsigned> AddOpsInlineThreshold( 182 "scev-addops-inline-threshold", cl::Hidden, 183 cl::desc("Threshold for inlining addition operands into a SCEV"), 184 cl::init(500)); 185 186 static cl::opt<unsigned> MaxSCEVCompareDepth( 187 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 188 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 189 cl::init(32)); 190 191 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 192 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 193 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 194 cl::init(2)); 195 196 static cl::opt<unsigned> MaxValueCompareDepth( 197 "scalar-evolution-max-value-compare-depth", cl::Hidden, 198 cl::desc("Maximum depth of recursive value complexity comparisons"), 199 cl::init(2)); 200 201 static cl::opt<unsigned> 202 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 203 cl::desc("Maximum depth of recursive arithmetics"), 204 cl::init(32)); 205 206 static cl::opt<unsigned> MaxConstantEvolvingDepth( 207 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 208 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 209 210 static cl::opt<unsigned> 211 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 212 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 213 cl::init(8)); 214 215 static cl::opt<unsigned> 216 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 217 cl::desc("Max coefficients in AddRec during evolving"), 218 cl::init(8)); 219 220 static cl::opt<unsigned> 221 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 222 cl::desc("Size of the expression which is considered huge"), 223 cl::init(4096)); 224 225 static cl::opt<bool> 226 ClassifyExpressions("scalar-evolution-classify-expressions", 227 cl::Hidden, cl::init(true), 228 cl::desc("When printing analysis, include information on every instruction")); 229 230 static cl::opt<bool> UseExpensiveRangeSharpening( 231 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden, 232 cl::init(false), 233 cl::desc("Use more powerful methods of sharpening expression ranges. May " 234 "be costly in terms of compile time")); 235 236 //===----------------------------------------------------------------------===// 237 // SCEV class definitions 238 //===----------------------------------------------------------------------===// 239 240 //===----------------------------------------------------------------------===// 241 // Implementation of the SCEV class. 242 // 243 244 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 245 LLVM_DUMP_METHOD void SCEV::dump() const { 246 print(dbgs()); 247 dbgs() << '\n'; 248 } 249 #endif 250 251 void SCEV::print(raw_ostream &OS) const { 252 switch (getSCEVType()) { 253 case scConstant: 254 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 255 return; 256 case scPtrToInt: { 257 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this); 258 const SCEV *Op = PtrToInt->getOperand(); 259 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to " 260 << *PtrToInt->getType() << ")"; 261 return; 262 } 263 case scTruncate: { 264 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 265 const SCEV *Op = Trunc->getOperand(); 266 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 267 << *Trunc->getType() << ")"; 268 return; 269 } 270 case scZeroExtend: { 271 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 272 const SCEV *Op = ZExt->getOperand(); 273 OS << "(zext " << *Op->getType() << " " << *Op << " to " 274 << *ZExt->getType() << ")"; 275 return; 276 } 277 case scSignExtend: { 278 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 279 const SCEV *Op = SExt->getOperand(); 280 OS << "(sext " << *Op->getType() << " " << *Op << " to " 281 << *SExt->getType() << ")"; 282 return; 283 } 284 case scAddRecExpr: { 285 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 286 OS << "{" << *AR->getOperand(0); 287 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 288 OS << ",+," << *AR->getOperand(i); 289 OS << "}<"; 290 if (AR->hasNoUnsignedWrap()) 291 OS << "nuw><"; 292 if (AR->hasNoSignedWrap()) 293 OS << "nsw><"; 294 if (AR->hasNoSelfWrap() && 295 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 296 OS << "nw><"; 297 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 298 OS << ">"; 299 return; 300 } 301 case scAddExpr: 302 case scMulExpr: 303 case scUMaxExpr: 304 case scSMaxExpr: 305 case scUMinExpr: 306 case scSMinExpr: { 307 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 308 const char *OpStr = nullptr; 309 switch (NAry->getSCEVType()) { 310 case scAddExpr: OpStr = " + "; break; 311 case scMulExpr: OpStr = " * "; break; 312 case scUMaxExpr: OpStr = " umax "; break; 313 case scSMaxExpr: OpStr = " smax "; break; 314 case scUMinExpr: 315 OpStr = " umin "; 316 break; 317 case scSMinExpr: 318 OpStr = " smin "; 319 break; 320 default: 321 llvm_unreachable("There are no other nary expression types."); 322 } 323 OS << "("; 324 ListSeparator LS(OpStr); 325 for (const SCEV *Op : NAry->operands()) 326 OS << LS << *Op; 327 OS << ")"; 328 switch (NAry->getSCEVType()) { 329 case scAddExpr: 330 case scMulExpr: 331 if (NAry->hasNoUnsignedWrap()) 332 OS << "<nuw>"; 333 if (NAry->hasNoSignedWrap()) 334 OS << "<nsw>"; 335 break; 336 default: 337 // Nothing to print for other nary expressions. 338 break; 339 } 340 return; 341 } 342 case scUDivExpr: { 343 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 344 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 345 return; 346 } 347 case scUnknown: { 348 const SCEVUnknown *U = cast<SCEVUnknown>(this); 349 Type *AllocTy; 350 if (U->isSizeOf(AllocTy)) { 351 OS << "sizeof(" << *AllocTy << ")"; 352 return; 353 } 354 if (U->isAlignOf(AllocTy)) { 355 OS << "alignof(" << *AllocTy << ")"; 356 return; 357 } 358 359 Type *CTy; 360 Constant *FieldNo; 361 if (U->isOffsetOf(CTy, FieldNo)) { 362 OS << "offsetof(" << *CTy << ", "; 363 FieldNo->printAsOperand(OS, false); 364 OS << ")"; 365 return; 366 } 367 368 // Otherwise just print it normally. 369 U->getValue()->printAsOperand(OS, false); 370 return; 371 } 372 case scCouldNotCompute: 373 OS << "***COULDNOTCOMPUTE***"; 374 return; 375 } 376 llvm_unreachable("Unknown SCEV kind!"); 377 } 378 379 Type *SCEV::getType() const { 380 switch (getSCEVType()) { 381 case scConstant: 382 return cast<SCEVConstant>(this)->getType(); 383 case scPtrToInt: 384 case scTruncate: 385 case scZeroExtend: 386 case scSignExtend: 387 return cast<SCEVCastExpr>(this)->getType(); 388 case scAddRecExpr: 389 case scMulExpr: 390 case scUMaxExpr: 391 case scSMaxExpr: 392 case scUMinExpr: 393 case scSMinExpr: 394 return cast<SCEVNAryExpr>(this)->getType(); 395 case scAddExpr: 396 return cast<SCEVAddExpr>(this)->getType(); 397 case scUDivExpr: 398 return cast<SCEVUDivExpr>(this)->getType(); 399 case scUnknown: 400 return cast<SCEVUnknown>(this)->getType(); 401 case scCouldNotCompute: 402 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 403 } 404 llvm_unreachable("Unknown SCEV kind!"); 405 } 406 407 bool SCEV::isZero() const { 408 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 409 return SC->getValue()->isZero(); 410 return false; 411 } 412 413 bool SCEV::isOne() const { 414 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 415 return SC->getValue()->isOne(); 416 return false; 417 } 418 419 bool SCEV::isAllOnesValue() const { 420 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 421 return SC->getValue()->isMinusOne(); 422 return false; 423 } 424 425 bool SCEV::isNonConstantNegative() const { 426 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 427 if (!Mul) return false; 428 429 // If there is a constant factor, it will be first. 430 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 431 if (!SC) return false; 432 433 // Return true if the value is negative, this matches things like (-42 * V). 434 return SC->getAPInt().isNegative(); 435 } 436 437 SCEVCouldNotCompute::SCEVCouldNotCompute() : 438 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 439 440 bool SCEVCouldNotCompute::classof(const SCEV *S) { 441 return S->getSCEVType() == scCouldNotCompute; 442 } 443 444 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 445 FoldingSetNodeID ID; 446 ID.AddInteger(scConstant); 447 ID.AddPointer(V); 448 void *IP = nullptr; 449 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 450 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 451 UniqueSCEVs.InsertNode(S, IP); 452 return S; 453 } 454 455 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 456 return getConstant(ConstantInt::get(getContext(), Val)); 457 } 458 459 const SCEV * 460 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 461 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 462 return getConstant(ConstantInt::get(ITy, V, isSigned)); 463 } 464 465 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, 466 const SCEV *op, Type *ty) 467 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 468 Operands[0] = op; 469 } 470 471 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, 472 Type *ITy) 473 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) { 474 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && 475 "Must be a non-bit-width-changing pointer-to-integer cast!"); 476 } 477 478 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, 479 SCEVTypes SCEVTy, const SCEV *op, 480 Type *ty) 481 : SCEVCastExpr(ID, SCEVTy, op, ty) {} 482 483 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, 484 Type *ty) 485 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) { 486 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 487 "Cannot truncate non-integer value!"); 488 } 489 490 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 491 const SCEV *op, Type *ty) 492 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) { 493 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 494 "Cannot zero extend non-integer value!"); 495 } 496 497 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 498 const SCEV *op, Type *ty) 499 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) { 500 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 501 "Cannot sign extend non-integer value!"); 502 } 503 504 void SCEVUnknown::deleted() { 505 // Clear this SCEVUnknown from various maps. 506 SE->forgetMemoizedResults(this); 507 508 // Remove this SCEVUnknown from the uniquing map. 509 SE->UniqueSCEVs.RemoveNode(this); 510 511 // Release the value. 512 setValPtr(nullptr); 513 } 514 515 void SCEVUnknown::allUsesReplacedWith(Value *New) { 516 // Remove this SCEVUnknown from the uniquing map. 517 SE->UniqueSCEVs.RemoveNode(this); 518 519 // Update this SCEVUnknown to point to the new value. This is needed 520 // because there may still be outstanding SCEVs which still point to 521 // this SCEVUnknown. 522 setValPtr(New); 523 } 524 525 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 526 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 527 if (VCE->getOpcode() == Instruction::PtrToInt) 528 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 529 if (CE->getOpcode() == Instruction::GetElementPtr && 530 CE->getOperand(0)->isNullValue() && 531 CE->getNumOperands() == 2) 532 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 533 if (CI->isOne()) { 534 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 535 ->getElementType(); 536 return true; 537 } 538 539 return false; 540 } 541 542 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 543 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 544 if (VCE->getOpcode() == Instruction::PtrToInt) 545 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 546 if (CE->getOpcode() == Instruction::GetElementPtr && 547 CE->getOperand(0)->isNullValue()) { 548 Type *Ty = 549 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 550 if (StructType *STy = dyn_cast<StructType>(Ty)) 551 if (!STy->isPacked() && 552 CE->getNumOperands() == 3 && 553 CE->getOperand(1)->isNullValue()) { 554 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 555 if (CI->isOne() && 556 STy->getNumElements() == 2 && 557 STy->getElementType(0)->isIntegerTy(1)) { 558 AllocTy = STy->getElementType(1); 559 return true; 560 } 561 } 562 } 563 564 return false; 565 } 566 567 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 568 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 569 if (VCE->getOpcode() == Instruction::PtrToInt) 570 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 571 if (CE->getOpcode() == Instruction::GetElementPtr && 572 CE->getNumOperands() == 3 && 573 CE->getOperand(0)->isNullValue() && 574 CE->getOperand(1)->isNullValue()) { 575 Type *Ty = 576 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 577 // Ignore vector types here so that ScalarEvolutionExpander doesn't 578 // emit getelementptrs that index into vectors. 579 if (Ty->isStructTy() || Ty->isArrayTy()) { 580 CTy = Ty; 581 FieldNo = CE->getOperand(2); 582 return true; 583 } 584 } 585 586 return false; 587 } 588 589 //===----------------------------------------------------------------------===// 590 // SCEV Utilities 591 //===----------------------------------------------------------------------===// 592 593 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 594 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 595 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 596 /// have been previously deemed to be "equally complex" by this routine. It is 597 /// intended to avoid exponential time complexity in cases like: 598 /// 599 /// %a = f(%x, %y) 600 /// %b = f(%a, %a) 601 /// %c = f(%b, %b) 602 /// 603 /// %d = f(%x, %y) 604 /// %e = f(%d, %d) 605 /// %f = f(%e, %e) 606 /// 607 /// CompareValueComplexity(%f, %c) 608 /// 609 /// Since we do not continue running this routine on expression trees once we 610 /// have seen unequal values, there is no need to track them in the cache. 611 static int 612 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 613 const LoopInfo *const LI, Value *LV, Value *RV, 614 unsigned Depth) { 615 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 616 return 0; 617 618 // Order pointer values after integer values. This helps SCEVExpander form 619 // GEPs. 620 bool LIsPointer = LV->getType()->isPointerTy(), 621 RIsPointer = RV->getType()->isPointerTy(); 622 if (LIsPointer != RIsPointer) 623 return (int)LIsPointer - (int)RIsPointer; 624 625 // Compare getValueID values. 626 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 627 if (LID != RID) 628 return (int)LID - (int)RID; 629 630 // Sort arguments by their position. 631 if (const auto *LA = dyn_cast<Argument>(LV)) { 632 const auto *RA = cast<Argument>(RV); 633 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 634 return (int)LArgNo - (int)RArgNo; 635 } 636 637 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 638 const auto *RGV = cast<GlobalValue>(RV); 639 640 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 641 auto LT = GV->getLinkage(); 642 return !(GlobalValue::isPrivateLinkage(LT) || 643 GlobalValue::isInternalLinkage(LT)); 644 }; 645 646 // Use the names to distinguish the two values, but only if the 647 // names are semantically important. 648 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 649 return LGV->getName().compare(RGV->getName()); 650 } 651 652 // For instructions, compare their loop depth, and their operand count. This 653 // is pretty loose. 654 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 655 const auto *RInst = cast<Instruction>(RV); 656 657 // Compare loop depths. 658 const BasicBlock *LParent = LInst->getParent(), 659 *RParent = RInst->getParent(); 660 if (LParent != RParent) { 661 unsigned LDepth = LI->getLoopDepth(LParent), 662 RDepth = LI->getLoopDepth(RParent); 663 if (LDepth != RDepth) 664 return (int)LDepth - (int)RDepth; 665 } 666 667 // Compare the number of operands. 668 unsigned LNumOps = LInst->getNumOperands(), 669 RNumOps = RInst->getNumOperands(); 670 if (LNumOps != RNumOps) 671 return (int)LNumOps - (int)RNumOps; 672 673 for (unsigned Idx : seq(0u, LNumOps)) { 674 int Result = 675 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 676 RInst->getOperand(Idx), Depth + 1); 677 if (Result != 0) 678 return Result; 679 } 680 } 681 682 EqCacheValue.unionSets(LV, RV); 683 return 0; 684 } 685 686 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 687 // than RHS, respectively. A three-way result allows recursive comparisons to be 688 // more efficient. 689 // If the max analysis depth was reached, return None, assuming we do not know 690 // if they are equivalent for sure. 691 static Optional<int> 692 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV, 693 EquivalenceClasses<const Value *> &EqCacheValue, 694 const LoopInfo *const LI, const SCEV *LHS, 695 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) { 696 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 697 if (LHS == RHS) 698 return 0; 699 700 // Primarily, sort the SCEVs by their getSCEVType(). 701 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 702 if (LType != RType) 703 return (int)LType - (int)RType; 704 705 if (EqCacheSCEV.isEquivalent(LHS, RHS)) 706 return 0; 707 708 if (Depth > MaxSCEVCompareDepth) 709 return None; 710 711 // Aside from the getSCEVType() ordering, the particular ordering 712 // isn't very important except that it's beneficial to be consistent, 713 // so that (a + b) and (b + a) don't end up as different expressions. 714 switch (LType) { 715 case scUnknown: { 716 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 717 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 718 719 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 720 RU->getValue(), Depth + 1); 721 if (X == 0) 722 EqCacheSCEV.unionSets(LHS, RHS); 723 return X; 724 } 725 726 case scConstant: { 727 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 728 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 729 730 // Compare constant values. 731 const APInt &LA = LC->getAPInt(); 732 const APInt &RA = RC->getAPInt(); 733 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 734 if (LBitWidth != RBitWidth) 735 return (int)LBitWidth - (int)RBitWidth; 736 return LA.ult(RA) ? -1 : 1; 737 } 738 739 case scAddRecExpr: { 740 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 741 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 742 743 // There is always a dominance between two recs that are used by one SCEV, 744 // so we can safely sort recs by loop header dominance. We require such 745 // order in getAddExpr. 746 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 747 if (LLoop != RLoop) { 748 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 749 assert(LHead != RHead && "Two loops share the same header?"); 750 if (DT.dominates(LHead, RHead)) 751 return 1; 752 else 753 assert(DT.dominates(RHead, LHead) && 754 "No dominance between recurrences used by one SCEV?"); 755 return -1; 756 } 757 758 // Addrec complexity grows with operand count. 759 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 760 if (LNumOps != RNumOps) 761 return (int)LNumOps - (int)RNumOps; 762 763 // Lexicographically compare. 764 for (unsigned i = 0; i != LNumOps; ++i) { 765 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 766 LA->getOperand(i), RA->getOperand(i), DT, 767 Depth + 1); 768 if (X != 0) 769 return X; 770 } 771 EqCacheSCEV.unionSets(LHS, RHS); 772 return 0; 773 } 774 775 case scAddExpr: 776 case scMulExpr: 777 case scSMaxExpr: 778 case scUMaxExpr: 779 case scSMinExpr: 780 case scUMinExpr: { 781 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 782 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 783 784 // Lexicographically compare n-ary expressions. 785 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 786 if (LNumOps != RNumOps) 787 return (int)LNumOps - (int)RNumOps; 788 789 for (unsigned i = 0; i != LNumOps; ++i) { 790 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 791 LC->getOperand(i), RC->getOperand(i), DT, 792 Depth + 1); 793 if (X != 0) 794 return X; 795 } 796 EqCacheSCEV.unionSets(LHS, RHS); 797 return 0; 798 } 799 800 case scUDivExpr: { 801 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 802 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 803 804 // Lexicographically compare udiv expressions. 805 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 806 RC->getLHS(), DT, Depth + 1); 807 if (X != 0) 808 return X; 809 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 810 RC->getRHS(), DT, Depth + 1); 811 if (X == 0) 812 EqCacheSCEV.unionSets(LHS, RHS); 813 return X; 814 } 815 816 case scPtrToInt: 817 case scTruncate: 818 case scZeroExtend: 819 case scSignExtend: { 820 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 821 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 822 823 // Compare cast expressions by operand. 824 auto X = 825 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(), 826 RC->getOperand(), DT, Depth + 1); 827 if (X == 0) 828 EqCacheSCEV.unionSets(LHS, RHS); 829 return X; 830 } 831 832 case scCouldNotCompute: 833 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 834 } 835 llvm_unreachable("Unknown SCEV kind!"); 836 } 837 838 /// Given a list of SCEV objects, order them by their complexity, and group 839 /// objects of the same complexity together by value. When this routine is 840 /// finished, we know that any duplicates in the vector are consecutive and that 841 /// complexity is monotonically increasing. 842 /// 843 /// Note that we go take special precautions to ensure that we get deterministic 844 /// results from this routine. In other words, we don't want the results of 845 /// this to depend on where the addresses of various SCEV objects happened to 846 /// land in memory. 847 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 848 LoopInfo *LI, DominatorTree &DT) { 849 if (Ops.size() < 2) return; // Noop 850 851 EquivalenceClasses<const SCEV *> EqCacheSCEV; 852 EquivalenceClasses<const Value *> EqCacheValue; 853 854 // Whether LHS has provably less complexity than RHS. 855 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) { 856 auto Complexity = 857 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT); 858 return Complexity && *Complexity < 0; 859 }; 860 if (Ops.size() == 2) { 861 // This is the common case, which also happens to be trivially simple. 862 // Special case it. 863 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 864 if (IsLessComplex(RHS, LHS)) 865 std::swap(LHS, RHS); 866 return; 867 } 868 869 // Do the rough sort by complexity. 870 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 871 return IsLessComplex(LHS, RHS); 872 }); 873 874 // Now that we are sorted by complexity, group elements of the same 875 // complexity. Note that this is, at worst, N^2, but the vector is likely to 876 // be extremely short in practice. Note that we take this approach because we 877 // do not want to depend on the addresses of the objects we are grouping. 878 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 879 const SCEV *S = Ops[i]; 880 unsigned Complexity = S->getSCEVType(); 881 882 // If there are any objects of the same complexity and same value as this 883 // one, group them. 884 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 885 if (Ops[j] == S) { // Found a duplicate. 886 // Move it to immediately after i'th element. 887 std::swap(Ops[i+1], Ops[j]); 888 ++i; // no need to rescan it. 889 if (i == e-2) return; // Done! 890 } 891 } 892 } 893 } 894 895 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 896 /// least HugeExprThreshold nodes). 897 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 898 return any_of(Ops, [](const SCEV *S) { 899 return S->getExpressionSize() >= HugeExprThreshold; 900 }); 901 } 902 903 //===----------------------------------------------------------------------===// 904 // Simple SCEV method implementations 905 //===----------------------------------------------------------------------===// 906 907 /// Compute BC(It, K). The result has width W. Assume, K > 0. 908 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 909 ScalarEvolution &SE, 910 Type *ResultTy) { 911 // Handle the simplest case efficiently. 912 if (K == 1) 913 return SE.getTruncateOrZeroExtend(It, ResultTy); 914 915 // We are using the following formula for BC(It, K): 916 // 917 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 918 // 919 // Suppose, W is the bitwidth of the return value. We must be prepared for 920 // overflow. Hence, we must assure that the result of our computation is 921 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 922 // safe in modular arithmetic. 923 // 924 // However, this code doesn't use exactly that formula; the formula it uses 925 // is something like the following, where T is the number of factors of 2 in 926 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 927 // exponentiation: 928 // 929 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 930 // 931 // This formula is trivially equivalent to the previous formula. However, 932 // this formula can be implemented much more efficiently. The trick is that 933 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 934 // arithmetic. To do exact division in modular arithmetic, all we have 935 // to do is multiply by the inverse. Therefore, this step can be done at 936 // width W. 937 // 938 // The next issue is how to safely do the division by 2^T. The way this 939 // is done is by doing the multiplication step at a width of at least W + T 940 // bits. This way, the bottom W+T bits of the product are accurate. Then, 941 // when we perform the division by 2^T (which is equivalent to a right shift 942 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 943 // truncated out after the division by 2^T. 944 // 945 // In comparison to just directly using the first formula, this technique 946 // is much more efficient; using the first formula requires W * K bits, 947 // but this formula less than W + K bits. Also, the first formula requires 948 // a division step, whereas this formula only requires multiplies and shifts. 949 // 950 // It doesn't matter whether the subtraction step is done in the calculation 951 // width or the input iteration count's width; if the subtraction overflows, 952 // the result must be zero anyway. We prefer here to do it in the width of 953 // the induction variable because it helps a lot for certain cases; CodeGen 954 // isn't smart enough to ignore the overflow, which leads to much less 955 // efficient code if the width of the subtraction is wider than the native 956 // register width. 957 // 958 // (It's possible to not widen at all by pulling out factors of 2 before 959 // the multiplication; for example, K=2 can be calculated as 960 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 961 // extra arithmetic, so it's not an obvious win, and it gets 962 // much more complicated for K > 3.) 963 964 // Protection from insane SCEVs; this bound is conservative, 965 // but it probably doesn't matter. 966 if (K > 1000) 967 return SE.getCouldNotCompute(); 968 969 unsigned W = SE.getTypeSizeInBits(ResultTy); 970 971 // Calculate K! / 2^T and T; we divide out the factors of two before 972 // multiplying for calculating K! / 2^T to avoid overflow. 973 // Other overflow doesn't matter because we only care about the bottom 974 // W bits of the result. 975 APInt OddFactorial(W, 1); 976 unsigned T = 1; 977 for (unsigned i = 3; i <= K; ++i) { 978 APInt Mult(W, i); 979 unsigned TwoFactors = Mult.countTrailingZeros(); 980 T += TwoFactors; 981 Mult.lshrInPlace(TwoFactors); 982 OddFactorial *= Mult; 983 } 984 985 // We need at least W + T bits for the multiplication step 986 unsigned CalculationBits = W + T; 987 988 // Calculate 2^T, at width T+W. 989 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 990 991 // Calculate the multiplicative inverse of K! / 2^T; 992 // this multiplication factor will perform the exact division by 993 // K! / 2^T. 994 APInt Mod = APInt::getSignedMinValue(W+1); 995 APInt MultiplyFactor = OddFactorial.zext(W+1); 996 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 997 MultiplyFactor = MultiplyFactor.trunc(W); 998 999 // Calculate the product, at width T+W 1000 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1001 CalculationBits); 1002 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1003 for (unsigned i = 1; i != K; ++i) { 1004 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1005 Dividend = SE.getMulExpr(Dividend, 1006 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1007 } 1008 1009 // Divide by 2^T 1010 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1011 1012 // Truncate the result, and divide by K! / 2^T. 1013 1014 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1015 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1016 } 1017 1018 /// Return the value of this chain of recurrences at the specified iteration 1019 /// number. We can evaluate this recurrence by multiplying each element in the 1020 /// chain by the binomial coefficient corresponding to it. In other words, we 1021 /// can evaluate {A,+,B,+,C,+,D} as: 1022 /// 1023 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1024 /// 1025 /// where BC(It, k) stands for binomial coefficient. 1026 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1027 ScalarEvolution &SE) const { 1028 return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE); 1029 } 1030 1031 const SCEV * 1032 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands, 1033 const SCEV *It, ScalarEvolution &SE) { 1034 assert(Operands.size() > 0); 1035 const SCEV *Result = Operands[0]; 1036 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 1037 // The computation is correct in the face of overflow provided that the 1038 // multiplication is performed _after_ the evaluation of the binomial 1039 // coefficient. 1040 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType()); 1041 if (isa<SCEVCouldNotCompute>(Coeff)) 1042 return Coeff; 1043 1044 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff)); 1045 } 1046 return Result; 1047 } 1048 1049 //===----------------------------------------------------------------------===// 1050 // SCEV Expression folder implementations 1051 //===----------------------------------------------------------------------===// 1052 1053 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op, 1054 unsigned Depth) { 1055 assert(Depth <= 1 && 1056 "getLosslessPtrToIntExpr() should self-recurse at most once."); 1057 1058 // We could be called with an integer-typed operands during SCEV rewrites. 1059 // Since the operand is an integer already, just perform zext/trunc/self cast. 1060 if (!Op->getType()->isPointerTy()) 1061 return Op; 1062 1063 assert(!getDataLayout().isNonIntegralPointerType(Op->getType()) && 1064 "Source pointer type must be integral for ptrtoint!"); 1065 1066 // What would be an ID for such a SCEV cast expression? 1067 FoldingSetNodeID ID; 1068 ID.AddInteger(scPtrToInt); 1069 ID.AddPointer(Op); 1070 1071 void *IP = nullptr; 1072 1073 // Is there already an expression for such a cast? 1074 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1075 return S; 1076 1077 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType()); 1078 1079 // We can only model ptrtoint if SCEV's effective (integer) type 1080 // is sufficiently wide to represent all possible pointer values. 1081 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) != 1082 getDataLayout().getTypeSizeInBits(IntPtrTy)) 1083 return getCouldNotCompute(); 1084 1085 // If not, is this expression something we can't reduce any further? 1086 if (auto *U = dyn_cast<SCEVUnknown>(Op)) { 1087 // Perform some basic constant folding. If the operand of the ptr2int cast 1088 // is a null pointer, don't create a ptr2int SCEV expression (that will be 1089 // left as-is), but produce a zero constant. 1090 // NOTE: We could handle a more general case, but lack motivational cases. 1091 if (isa<ConstantPointerNull>(U->getValue())) 1092 return getZero(IntPtrTy); 1093 1094 // Create an explicit cast node. 1095 // We can reuse the existing insert position since if we get here, 1096 // we won't have made any changes which would invalidate it. 1097 SCEV *S = new (SCEVAllocator) 1098 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy); 1099 UniqueSCEVs.InsertNode(S, IP); 1100 addToLoopUseLists(S); 1101 return S; 1102 } 1103 1104 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for " 1105 "non-SCEVUnknown's."); 1106 1107 // Otherwise, we've got some expression that is more complex than just a 1108 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an 1109 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown 1110 // only, and the expressions must otherwise be integer-typed. 1111 // So sink the cast down to the SCEVUnknown's. 1112 1113 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression, 1114 /// which computes a pointer-typed value, and rewrites the whole expression 1115 /// tree so that *all* the computations are done on integers, and the only 1116 /// pointer-typed operands in the expression are SCEVUnknown. 1117 class SCEVPtrToIntSinkingRewriter 1118 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> { 1119 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>; 1120 1121 public: 1122 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {} 1123 1124 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) { 1125 SCEVPtrToIntSinkingRewriter Rewriter(SE); 1126 return Rewriter.visit(Scev); 1127 } 1128 1129 const SCEV *visit(const SCEV *S) { 1130 Type *STy = S->getType(); 1131 // If the expression is not pointer-typed, just keep it as-is. 1132 if (!STy->isPointerTy()) 1133 return S; 1134 // Else, recursively sink the cast down into it. 1135 return Base::visit(S); 1136 } 1137 1138 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) { 1139 SmallVector<const SCEV *, 2> Operands; 1140 bool Changed = false; 1141 for (auto *Op : Expr->operands()) { 1142 Operands.push_back(visit(Op)); 1143 Changed |= Op != Operands.back(); 1144 } 1145 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags()); 1146 } 1147 1148 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) { 1149 SmallVector<const SCEV *, 2> Operands; 1150 bool Changed = false; 1151 for (auto *Op : Expr->operands()) { 1152 Operands.push_back(visit(Op)); 1153 Changed |= Op != Operands.back(); 1154 } 1155 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags()); 1156 } 1157 1158 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 1159 assert(Expr->getType()->isPointerTy() && 1160 "Should only reach pointer-typed SCEVUnknown's."); 1161 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1); 1162 } 1163 }; 1164 1165 // And actually perform the cast sinking. 1166 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this); 1167 assert(IntOp->getType()->isIntegerTy() && 1168 "We must have succeeded in sinking the cast, " 1169 "and ending up with an integer-typed expression!"); 1170 return IntOp; 1171 } 1172 1173 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) { 1174 assert(Ty->isIntegerTy() && "Target type must be an integer type!"); 1175 1176 const SCEV *IntOp = getLosslessPtrToIntExpr(Op); 1177 if (isa<SCEVCouldNotCompute>(IntOp)) 1178 return IntOp; 1179 1180 return getTruncateOrZeroExtend(IntOp, Ty); 1181 } 1182 1183 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1184 unsigned Depth) { 1185 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1186 "This is not a truncating conversion!"); 1187 assert(isSCEVable(Ty) && 1188 "This is not a conversion to a SCEVable type!"); 1189 Ty = getEffectiveSCEVType(Ty); 1190 1191 FoldingSetNodeID ID; 1192 ID.AddInteger(scTruncate); 1193 ID.AddPointer(Op); 1194 ID.AddPointer(Ty); 1195 void *IP = nullptr; 1196 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1197 1198 // Fold if the operand is constant. 1199 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1200 return getConstant( 1201 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1202 1203 // trunc(trunc(x)) --> trunc(x) 1204 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1205 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1206 1207 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1208 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1209 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1210 1211 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1212 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1213 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1214 1215 if (Depth > MaxCastDepth) { 1216 SCEV *S = 1217 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1218 UniqueSCEVs.InsertNode(S, IP); 1219 addToLoopUseLists(S); 1220 return S; 1221 } 1222 1223 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1224 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1225 // if after transforming we have at most one truncate, not counting truncates 1226 // that replace other casts. 1227 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1228 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1229 SmallVector<const SCEV *, 4> Operands; 1230 unsigned numTruncs = 0; 1231 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1232 ++i) { 1233 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1234 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) && 1235 isa<SCEVTruncateExpr>(S)) 1236 numTruncs++; 1237 Operands.push_back(S); 1238 } 1239 if (numTruncs < 2) { 1240 if (isa<SCEVAddExpr>(Op)) 1241 return getAddExpr(Operands); 1242 else if (isa<SCEVMulExpr>(Op)) 1243 return getMulExpr(Operands); 1244 else 1245 llvm_unreachable("Unexpected SCEV type for Op."); 1246 } 1247 // Although we checked in the beginning that ID is not in the cache, it is 1248 // possible that during recursion and different modification ID was inserted 1249 // into the cache. So if we find it, just return it. 1250 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1251 return S; 1252 } 1253 1254 // If the input value is a chrec scev, truncate the chrec's operands. 1255 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1256 SmallVector<const SCEV *, 4> Operands; 1257 for (const SCEV *Op : AddRec->operands()) 1258 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1259 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1260 } 1261 1262 // Return zero if truncating to known zeros. 1263 uint32_t MinTrailingZeros = GetMinTrailingZeros(Op); 1264 if (MinTrailingZeros >= getTypeSizeInBits(Ty)) 1265 return getZero(Ty); 1266 1267 // The cast wasn't folded; create an explicit cast node. We can reuse 1268 // the existing insert position since if we get here, we won't have 1269 // made any changes which would invalidate it. 1270 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1271 Op, Ty); 1272 UniqueSCEVs.InsertNode(S, IP); 1273 addToLoopUseLists(S); 1274 return S; 1275 } 1276 1277 // Get the limit of a recurrence such that incrementing by Step cannot cause 1278 // signed overflow as long as the value of the recurrence within the 1279 // loop does not exceed this limit before incrementing. 1280 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1281 ICmpInst::Predicate *Pred, 1282 ScalarEvolution *SE) { 1283 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1284 if (SE->isKnownPositive(Step)) { 1285 *Pred = ICmpInst::ICMP_SLT; 1286 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1287 SE->getSignedRangeMax(Step)); 1288 } 1289 if (SE->isKnownNegative(Step)) { 1290 *Pred = ICmpInst::ICMP_SGT; 1291 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1292 SE->getSignedRangeMin(Step)); 1293 } 1294 return nullptr; 1295 } 1296 1297 // Get the limit of a recurrence such that incrementing by Step cannot cause 1298 // unsigned overflow as long as the value of the recurrence within the loop does 1299 // not exceed this limit before incrementing. 1300 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1301 ICmpInst::Predicate *Pred, 1302 ScalarEvolution *SE) { 1303 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1304 *Pred = ICmpInst::ICMP_ULT; 1305 1306 return SE->getConstant(APInt::getMinValue(BitWidth) - 1307 SE->getUnsignedRangeMax(Step)); 1308 } 1309 1310 namespace { 1311 1312 struct ExtendOpTraitsBase { 1313 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1314 unsigned); 1315 }; 1316 1317 // Used to make code generic over signed and unsigned overflow. 1318 template <typename ExtendOp> struct ExtendOpTraits { 1319 // Members present: 1320 // 1321 // static const SCEV::NoWrapFlags WrapType; 1322 // 1323 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1324 // 1325 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1326 // ICmpInst::Predicate *Pred, 1327 // ScalarEvolution *SE); 1328 }; 1329 1330 template <> 1331 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1332 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1333 1334 static const GetExtendExprTy GetExtendExpr; 1335 1336 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1337 ICmpInst::Predicate *Pred, 1338 ScalarEvolution *SE) { 1339 return getSignedOverflowLimitForStep(Step, Pred, SE); 1340 } 1341 }; 1342 1343 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1344 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1345 1346 template <> 1347 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1348 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1349 1350 static const GetExtendExprTy GetExtendExpr; 1351 1352 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1353 ICmpInst::Predicate *Pred, 1354 ScalarEvolution *SE) { 1355 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1356 } 1357 }; 1358 1359 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1360 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1361 1362 } // end anonymous namespace 1363 1364 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1365 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1366 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1367 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1368 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1369 // expression "Step + sext/zext(PreIncAR)" is congruent with 1370 // "sext/zext(PostIncAR)" 1371 template <typename ExtendOpTy> 1372 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1373 ScalarEvolution *SE, unsigned Depth) { 1374 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1375 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1376 1377 const Loop *L = AR->getLoop(); 1378 const SCEV *Start = AR->getStart(); 1379 const SCEV *Step = AR->getStepRecurrence(*SE); 1380 1381 // Check for a simple looking step prior to loop entry. 1382 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1383 if (!SA) 1384 return nullptr; 1385 1386 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1387 // subtraction is expensive. For this purpose, perform a quick and dirty 1388 // difference, by checking for Step in the operand list. 1389 SmallVector<const SCEV *, 4> DiffOps; 1390 for (const SCEV *Op : SA->operands()) 1391 if (Op != Step) 1392 DiffOps.push_back(Op); 1393 1394 if (DiffOps.size() == SA->getNumOperands()) 1395 return nullptr; 1396 1397 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1398 // `Step`: 1399 1400 // 1. NSW/NUW flags on the step increment. 1401 auto PreStartFlags = 1402 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1403 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1404 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1405 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1406 1407 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1408 // "S+X does not sign/unsign-overflow". 1409 // 1410 1411 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1412 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1413 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1414 return PreStart; 1415 1416 // 2. Direct overflow check on the step operation's expression. 1417 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1418 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1419 const SCEV *OperandExtendedStart = 1420 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1421 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1422 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1423 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1424 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1425 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1426 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1427 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType); 1428 } 1429 return PreStart; 1430 } 1431 1432 // 3. Loop precondition. 1433 ICmpInst::Predicate Pred; 1434 const SCEV *OverflowLimit = 1435 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1436 1437 if (OverflowLimit && 1438 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1439 return PreStart; 1440 1441 return nullptr; 1442 } 1443 1444 // Get the normalized zero or sign extended expression for this AddRec's Start. 1445 template <typename ExtendOpTy> 1446 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1447 ScalarEvolution *SE, 1448 unsigned Depth) { 1449 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1450 1451 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1452 if (!PreStart) 1453 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1454 1455 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1456 Depth), 1457 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1458 } 1459 1460 // Try to prove away overflow by looking at "nearby" add recurrences. A 1461 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1462 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1463 // 1464 // Formally: 1465 // 1466 // {S,+,X} == {S-T,+,X} + T 1467 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1468 // 1469 // If ({S-T,+,X} + T) does not overflow ... (1) 1470 // 1471 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1472 // 1473 // If {S-T,+,X} does not overflow ... (2) 1474 // 1475 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1476 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1477 // 1478 // If (S-T)+T does not overflow ... (3) 1479 // 1480 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1481 // == {Ext(S),+,Ext(X)} == LHS 1482 // 1483 // Thus, if (1), (2) and (3) are true for some T, then 1484 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1485 // 1486 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1487 // does not overflow" restricted to the 0th iteration. Therefore we only need 1488 // to check for (1) and (2). 1489 // 1490 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1491 // is `Delta` (defined below). 1492 template <typename ExtendOpTy> 1493 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1494 const SCEV *Step, 1495 const Loop *L) { 1496 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1497 1498 // We restrict `Start` to a constant to prevent SCEV from spending too much 1499 // time here. It is correct (but more expensive) to continue with a 1500 // non-constant `Start` and do a general SCEV subtraction to compute 1501 // `PreStart` below. 1502 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1503 if (!StartC) 1504 return false; 1505 1506 APInt StartAI = StartC->getAPInt(); 1507 1508 for (unsigned Delta : {-2, -1, 1, 2}) { 1509 const SCEV *PreStart = getConstant(StartAI - Delta); 1510 1511 FoldingSetNodeID ID; 1512 ID.AddInteger(scAddRecExpr); 1513 ID.AddPointer(PreStart); 1514 ID.AddPointer(Step); 1515 ID.AddPointer(L); 1516 void *IP = nullptr; 1517 const auto *PreAR = 1518 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1519 1520 // Give up if we don't already have the add recurrence we need because 1521 // actually constructing an add recurrence is relatively expensive. 1522 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1523 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1524 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1525 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1526 DeltaS, &Pred, this); 1527 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1528 return true; 1529 } 1530 } 1531 1532 return false; 1533 } 1534 1535 // Finds an integer D for an expression (C + x + y + ...) such that the top 1536 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1537 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1538 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1539 // the (C + x + y + ...) expression is \p WholeAddExpr. 1540 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1541 const SCEVConstant *ConstantTerm, 1542 const SCEVAddExpr *WholeAddExpr) { 1543 const APInt &C = ConstantTerm->getAPInt(); 1544 const unsigned BitWidth = C.getBitWidth(); 1545 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1546 uint32_t TZ = BitWidth; 1547 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1548 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1549 if (TZ) { 1550 // Set D to be as many least significant bits of C as possible while still 1551 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1552 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1553 } 1554 return APInt(BitWidth, 0); 1555 } 1556 1557 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1558 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1559 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1560 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1561 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1562 const APInt &ConstantStart, 1563 const SCEV *Step) { 1564 const unsigned BitWidth = ConstantStart.getBitWidth(); 1565 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1566 if (TZ) 1567 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1568 : ConstantStart; 1569 return APInt(BitWidth, 0); 1570 } 1571 1572 const SCEV * 1573 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1574 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1575 "This is not an extending conversion!"); 1576 assert(isSCEVable(Ty) && 1577 "This is not a conversion to a SCEVable type!"); 1578 Ty = getEffectiveSCEVType(Ty); 1579 1580 // Fold if the operand is constant. 1581 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1582 return getConstant( 1583 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1584 1585 // zext(zext(x)) --> zext(x) 1586 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1587 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1588 1589 // Before doing any expensive analysis, check to see if we've already 1590 // computed a SCEV for this Op and Ty. 1591 FoldingSetNodeID ID; 1592 ID.AddInteger(scZeroExtend); 1593 ID.AddPointer(Op); 1594 ID.AddPointer(Ty); 1595 void *IP = nullptr; 1596 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1597 if (Depth > MaxCastDepth) { 1598 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1599 Op, Ty); 1600 UniqueSCEVs.InsertNode(S, IP); 1601 addToLoopUseLists(S); 1602 return S; 1603 } 1604 1605 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1606 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1607 // It's possible the bits taken off by the truncate were all zero bits. If 1608 // so, we should be able to simplify this further. 1609 const SCEV *X = ST->getOperand(); 1610 ConstantRange CR = getUnsignedRange(X); 1611 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1612 unsigned NewBits = getTypeSizeInBits(Ty); 1613 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1614 CR.zextOrTrunc(NewBits))) 1615 return getTruncateOrZeroExtend(X, Ty, Depth); 1616 } 1617 1618 // If the input value is a chrec scev, and we can prove that the value 1619 // did not overflow the old, smaller, value, we can zero extend all of the 1620 // operands (often constants). This allows analysis of something like 1621 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1622 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1623 if (AR->isAffine()) { 1624 const SCEV *Start = AR->getStart(); 1625 const SCEV *Step = AR->getStepRecurrence(*this); 1626 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1627 const Loop *L = AR->getLoop(); 1628 1629 if (!AR->hasNoUnsignedWrap()) { 1630 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1631 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1632 } 1633 1634 // If we have special knowledge that this addrec won't overflow, 1635 // we don't need to do any further analysis. 1636 if (AR->hasNoUnsignedWrap()) 1637 return getAddRecExpr( 1638 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1639 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1640 1641 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1642 // Note that this serves two purposes: It filters out loops that are 1643 // simply not analyzable, and it covers the case where this code is 1644 // being called from within backedge-taken count analysis, such that 1645 // attempting to ask for the backedge-taken count would likely result 1646 // in infinite recursion. In the later case, the analysis code will 1647 // cope with a conservative value, and it will take care to purge 1648 // that value once it has finished. 1649 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1650 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1651 // Manually compute the final value for AR, checking for overflow. 1652 1653 // Check whether the backedge-taken count can be losslessly casted to 1654 // the addrec's type. The count is always unsigned. 1655 const SCEV *CastedMaxBECount = 1656 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1657 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1658 CastedMaxBECount, MaxBECount->getType(), Depth); 1659 if (MaxBECount == RecastedMaxBECount) { 1660 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1661 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1662 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1663 SCEV::FlagAnyWrap, Depth + 1); 1664 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1665 SCEV::FlagAnyWrap, 1666 Depth + 1), 1667 WideTy, Depth + 1); 1668 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1669 const SCEV *WideMaxBECount = 1670 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1671 const SCEV *OperandExtendedAdd = 1672 getAddExpr(WideStart, 1673 getMulExpr(WideMaxBECount, 1674 getZeroExtendExpr(Step, WideTy, Depth + 1), 1675 SCEV::FlagAnyWrap, Depth + 1), 1676 SCEV::FlagAnyWrap, Depth + 1); 1677 if (ZAdd == OperandExtendedAdd) { 1678 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1679 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1680 // Return the expression with the addrec on the outside. 1681 return getAddRecExpr( 1682 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1683 Depth + 1), 1684 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1685 AR->getNoWrapFlags()); 1686 } 1687 // Similar to above, only this time treat the step value as signed. 1688 // This covers loops that count down. 1689 OperandExtendedAdd = 1690 getAddExpr(WideStart, 1691 getMulExpr(WideMaxBECount, 1692 getSignExtendExpr(Step, WideTy, Depth + 1), 1693 SCEV::FlagAnyWrap, Depth + 1), 1694 SCEV::FlagAnyWrap, Depth + 1); 1695 if (ZAdd == OperandExtendedAdd) { 1696 // Cache knowledge of AR NW, which is propagated to this AddRec. 1697 // Negative step causes unsigned wrap, but it still can't self-wrap. 1698 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1699 // Return the expression with the addrec on the outside. 1700 return getAddRecExpr( 1701 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1702 Depth + 1), 1703 getSignExtendExpr(Step, Ty, Depth + 1), L, 1704 AR->getNoWrapFlags()); 1705 } 1706 } 1707 } 1708 1709 // Normally, in the cases we can prove no-overflow via a 1710 // backedge guarding condition, we can also compute a backedge 1711 // taken count for the loop. The exceptions are assumptions and 1712 // guards present in the loop -- SCEV is not great at exploiting 1713 // these to compute max backedge taken counts, but can still use 1714 // these to prove lack of overflow. Use this fact to avoid 1715 // doing extra work that may not pay off. 1716 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1717 !AC.assumptions().empty()) { 1718 1719 auto NewFlags = proveNoUnsignedWrapViaInduction(AR); 1720 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1721 if (AR->hasNoUnsignedWrap()) { 1722 // Same as nuw case above - duplicated here to avoid a compile time 1723 // issue. It's not clear that the order of checks does matter, but 1724 // it's one of two issue possible causes for a change which was 1725 // reverted. Be conservative for the moment. 1726 return getAddRecExpr( 1727 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1728 Depth + 1), 1729 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1730 AR->getNoWrapFlags()); 1731 } 1732 1733 // For a negative step, we can extend the operands iff doing so only 1734 // traverses values in the range zext([0,UINT_MAX]). 1735 if (isKnownNegative(Step)) { 1736 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1737 getSignedRangeMin(Step)); 1738 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1739 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1740 // Cache knowledge of AR NW, which is propagated to this 1741 // AddRec. Negative step causes unsigned wrap, but it 1742 // still can't self-wrap. 1743 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1744 // Return the expression with the addrec on the outside. 1745 return getAddRecExpr( 1746 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1747 Depth + 1), 1748 getSignExtendExpr(Step, Ty, Depth + 1), L, 1749 AR->getNoWrapFlags()); 1750 } 1751 } 1752 } 1753 1754 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1755 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1756 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1757 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1758 const APInt &C = SC->getAPInt(); 1759 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1760 if (D != 0) { 1761 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1762 const SCEV *SResidual = 1763 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1764 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1765 return getAddExpr(SZExtD, SZExtR, 1766 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1767 Depth + 1); 1768 } 1769 } 1770 1771 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1772 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1773 return getAddRecExpr( 1774 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1775 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1776 } 1777 } 1778 1779 // zext(A % B) --> zext(A) % zext(B) 1780 { 1781 const SCEV *LHS; 1782 const SCEV *RHS; 1783 if (matchURem(Op, LHS, RHS)) 1784 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1785 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1786 } 1787 1788 // zext(A / B) --> zext(A) / zext(B). 1789 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1790 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1791 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1792 1793 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1794 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1795 if (SA->hasNoUnsignedWrap()) { 1796 // If the addition does not unsign overflow then we can, by definition, 1797 // commute the zero extension with the addition operation. 1798 SmallVector<const SCEV *, 4> Ops; 1799 for (const auto *Op : SA->operands()) 1800 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1801 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1802 } 1803 1804 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1805 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1806 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1807 // 1808 // Often address arithmetics contain expressions like 1809 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1810 // This transformation is useful while proving that such expressions are 1811 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1812 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1813 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1814 if (D != 0) { 1815 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1816 const SCEV *SResidual = 1817 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1818 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1819 return getAddExpr(SZExtD, SZExtR, 1820 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1821 Depth + 1); 1822 } 1823 } 1824 } 1825 1826 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1827 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1828 if (SM->hasNoUnsignedWrap()) { 1829 // If the multiply does not unsign overflow then we can, by definition, 1830 // commute the zero extension with the multiply operation. 1831 SmallVector<const SCEV *, 4> Ops; 1832 for (const auto *Op : SM->operands()) 1833 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1834 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1835 } 1836 1837 // zext(2^K * (trunc X to iN)) to iM -> 1838 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1839 // 1840 // Proof: 1841 // 1842 // zext(2^K * (trunc X to iN)) to iM 1843 // = zext((trunc X to iN) << K) to iM 1844 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1845 // (because shl removes the top K bits) 1846 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1847 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1848 // 1849 if (SM->getNumOperands() == 2) 1850 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1851 if (MulLHS->getAPInt().isPowerOf2()) 1852 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1853 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1854 MulLHS->getAPInt().logBase2(); 1855 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1856 return getMulExpr( 1857 getZeroExtendExpr(MulLHS, Ty), 1858 getZeroExtendExpr( 1859 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1860 SCEV::FlagNUW, Depth + 1); 1861 } 1862 } 1863 1864 // The cast wasn't folded; create an explicit cast node. 1865 // Recompute the insert position, as it may have been invalidated. 1866 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1867 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1868 Op, Ty); 1869 UniqueSCEVs.InsertNode(S, IP); 1870 addToLoopUseLists(S); 1871 return S; 1872 } 1873 1874 const SCEV * 1875 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1876 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1877 "This is not an extending conversion!"); 1878 assert(isSCEVable(Ty) && 1879 "This is not a conversion to a SCEVable type!"); 1880 Ty = getEffectiveSCEVType(Ty); 1881 1882 // Fold if the operand is constant. 1883 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1884 return getConstant( 1885 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1886 1887 // sext(sext(x)) --> sext(x) 1888 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1889 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1890 1891 // sext(zext(x)) --> zext(x) 1892 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1893 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1894 1895 // Before doing any expensive analysis, check to see if we've already 1896 // computed a SCEV for this Op and Ty. 1897 FoldingSetNodeID ID; 1898 ID.AddInteger(scSignExtend); 1899 ID.AddPointer(Op); 1900 ID.AddPointer(Ty); 1901 void *IP = nullptr; 1902 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1903 // Limit recursion depth. 1904 if (Depth > MaxCastDepth) { 1905 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1906 Op, Ty); 1907 UniqueSCEVs.InsertNode(S, IP); 1908 addToLoopUseLists(S); 1909 return S; 1910 } 1911 1912 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1913 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1914 // It's possible the bits taken off by the truncate were all sign bits. If 1915 // so, we should be able to simplify this further. 1916 const SCEV *X = ST->getOperand(); 1917 ConstantRange CR = getSignedRange(X); 1918 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1919 unsigned NewBits = getTypeSizeInBits(Ty); 1920 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1921 CR.sextOrTrunc(NewBits))) 1922 return getTruncateOrSignExtend(X, Ty, Depth); 1923 } 1924 1925 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1926 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1927 if (SA->hasNoSignedWrap()) { 1928 // If the addition does not sign overflow then we can, by definition, 1929 // commute the sign extension with the addition operation. 1930 SmallVector<const SCEV *, 4> Ops; 1931 for (const auto *Op : SA->operands()) 1932 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1933 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1934 } 1935 1936 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1937 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1938 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1939 // 1940 // For instance, this will bring two seemingly different expressions: 1941 // 1 + sext(5 + 20 * %x + 24 * %y) and 1942 // sext(6 + 20 * %x + 24 * %y) 1943 // to the same form: 1944 // 2 + sext(4 + 20 * %x + 24 * %y) 1945 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1946 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1947 if (D != 0) { 1948 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1949 const SCEV *SResidual = 1950 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1951 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1952 return getAddExpr(SSExtD, SSExtR, 1953 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1954 Depth + 1); 1955 } 1956 } 1957 } 1958 // If the input value is a chrec scev, and we can prove that the value 1959 // did not overflow the old, smaller, value, we can sign extend all of the 1960 // operands (often constants). This allows analysis of something like 1961 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1962 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1963 if (AR->isAffine()) { 1964 const SCEV *Start = AR->getStart(); 1965 const SCEV *Step = AR->getStepRecurrence(*this); 1966 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1967 const Loop *L = AR->getLoop(); 1968 1969 if (!AR->hasNoSignedWrap()) { 1970 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1971 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1972 } 1973 1974 // If we have special knowledge that this addrec won't overflow, 1975 // we don't need to do any further analysis. 1976 if (AR->hasNoSignedWrap()) 1977 return getAddRecExpr( 1978 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1979 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1980 1981 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1982 // Note that this serves two purposes: It filters out loops that are 1983 // simply not analyzable, and it covers the case where this code is 1984 // being called from within backedge-taken count analysis, such that 1985 // attempting to ask for the backedge-taken count would likely result 1986 // in infinite recursion. In the later case, the analysis code will 1987 // cope with a conservative value, and it will take care to purge 1988 // that value once it has finished. 1989 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1990 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1991 // Manually compute the final value for AR, checking for 1992 // overflow. 1993 1994 // Check whether the backedge-taken count can be losslessly casted to 1995 // the addrec's type. The count is always unsigned. 1996 const SCEV *CastedMaxBECount = 1997 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1998 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1999 CastedMaxBECount, MaxBECount->getType(), Depth); 2000 if (MaxBECount == RecastedMaxBECount) { 2001 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2002 // Check whether Start+Step*MaxBECount has no signed overflow. 2003 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2004 SCEV::FlagAnyWrap, Depth + 1); 2005 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2006 SCEV::FlagAnyWrap, 2007 Depth + 1), 2008 WideTy, Depth + 1); 2009 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2010 const SCEV *WideMaxBECount = 2011 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2012 const SCEV *OperandExtendedAdd = 2013 getAddExpr(WideStart, 2014 getMulExpr(WideMaxBECount, 2015 getSignExtendExpr(Step, WideTy, Depth + 1), 2016 SCEV::FlagAnyWrap, Depth + 1), 2017 SCEV::FlagAnyWrap, Depth + 1); 2018 if (SAdd == OperandExtendedAdd) { 2019 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2020 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2021 // Return the expression with the addrec on the outside. 2022 return getAddRecExpr( 2023 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2024 Depth + 1), 2025 getSignExtendExpr(Step, Ty, Depth + 1), L, 2026 AR->getNoWrapFlags()); 2027 } 2028 // Similar to above, only this time treat the step value as unsigned. 2029 // This covers loops that count up with an unsigned step. 2030 OperandExtendedAdd = 2031 getAddExpr(WideStart, 2032 getMulExpr(WideMaxBECount, 2033 getZeroExtendExpr(Step, WideTy, Depth + 1), 2034 SCEV::FlagAnyWrap, Depth + 1), 2035 SCEV::FlagAnyWrap, Depth + 1); 2036 if (SAdd == OperandExtendedAdd) { 2037 // If AR wraps around then 2038 // 2039 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2040 // => SAdd != OperandExtendedAdd 2041 // 2042 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2043 // (SAdd == OperandExtendedAdd => AR is NW) 2044 2045 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 2046 2047 // Return the expression with the addrec on the outside. 2048 return getAddRecExpr( 2049 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2050 Depth + 1), 2051 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2052 AR->getNoWrapFlags()); 2053 } 2054 } 2055 } 2056 2057 auto NewFlags = proveNoSignedWrapViaInduction(AR); 2058 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 2059 if (AR->hasNoSignedWrap()) { 2060 // Same as nsw case above - duplicated here to avoid a compile time 2061 // issue. It's not clear that the order of checks does matter, but 2062 // it's one of two issue possible causes for a change which was 2063 // reverted. Be conservative for the moment. 2064 return getAddRecExpr( 2065 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2066 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2067 } 2068 2069 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2070 // if D + (C - D + Step * n) could be proven to not signed wrap 2071 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2072 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2073 const APInt &C = SC->getAPInt(); 2074 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2075 if (D != 0) { 2076 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2077 const SCEV *SResidual = 2078 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2079 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2080 return getAddExpr(SSExtD, SSExtR, 2081 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2082 Depth + 1); 2083 } 2084 } 2085 2086 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2087 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2088 return getAddRecExpr( 2089 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2090 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2091 } 2092 } 2093 2094 // If the input value is provably positive and we could not simplify 2095 // away the sext build a zext instead. 2096 if (isKnownNonNegative(Op)) 2097 return getZeroExtendExpr(Op, Ty, Depth + 1); 2098 2099 // The cast wasn't folded; create an explicit cast node. 2100 // Recompute the insert position, as it may have been invalidated. 2101 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2102 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2103 Op, Ty); 2104 UniqueSCEVs.InsertNode(S, IP); 2105 addToLoopUseLists(S); 2106 return S; 2107 } 2108 2109 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2110 /// unspecified bits out to the given type. 2111 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2112 Type *Ty) { 2113 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2114 "This is not an extending conversion!"); 2115 assert(isSCEVable(Ty) && 2116 "This is not a conversion to a SCEVable type!"); 2117 Ty = getEffectiveSCEVType(Ty); 2118 2119 // Sign-extend negative constants. 2120 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2121 if (SC->getAPInt().isNegative()) 2122 return getSignExtendExpr(Op, Ty); 2123 2124 // Peel off a truncate cast. 2125 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2126 const SCEV *NewOp = T->getOperand(); 2127 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2128 return getAnyExtendExpr(NewOp, Ty); 2129 return getTruncateOrNoop(NewOp, Ty); 2130 } 2131 2132 // Next try a zext cast. If the cast is folded, use it. 2133 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2134 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2135 return ZExt; 2136 2137 // Next try a sext cast. If the cast is folded, use it. 2138 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2139 if (!isa<SCEVSignExtendExpr>(SExt)) 2140 return SExt; 2141 2142 // Force the cast to be folded into the operands of an addrec. 2143 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2144 SmallVector<const SCEV *, 4> Ops; 2145 for (const SCEV *Op : AR->operands()) 2146 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2147 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2148 } 2149 2150 // If the expression is obviously signed, use the sext cast value. 2151 if (isa<SCEVSMaxExpr>(Op)) 2152 return SExt; 2153 2154 // Absent any other information, use the zext cast value. 2155 return ZExt; 2156 } 2157 2158 /// Process the given Ops list, which is a list of operands to be added under 2159 /// the given scale, update the given map. This is a helper function for 2160 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2161 /// that would form an add expression like this: 2162 /// 2163 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2164 /// 2165 /// where A and B are constants, update the map with these values: 2166 /// 2167 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2168 /// 2169 /// and add 13 + A*B*29 to AccumulatedConstant. 2170 /// This will allow getAddRecExpr to produce this: 2171 /// 2172 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2173 /// 2174 /// This form often exposes folding opportunities that are hidden in 2175 /// the original operand list. 2176 /// 2177 /// Return true iff it appears that any interesting folding opportunities 2178 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2179 /// the common case where no interesting opportunities are present, and 2180 /// is also used as a check to avoid infinite recursion. 2181 static bool 2182 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2183 SmallVectorImpl<const SCEV *> &NewOps, 2184 APInt &AccumulatedConstant, 2185 const SCEV *const *Ops, size_t NumOperands, 2186 const APInt &Scale, 2187 ScalarEvolution &SE) { 2188 bool Interesting = false; 2189 2190 // Iterate over the add operands. They are sorted, with constants first. 2191 unsigned i = 0; 2192 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2193 ++i; 2194 // Pull a buried constant out to the outside. 2195 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2196 Interesting = true; 2197 AccumulatedConstant += Scale * C->getAPInt(); 2198 } 2199 2200 // Next comes everything else. We're especially interested in multiplies 2201 // here, but they're in the middle, so just visit the rest with one loop. 2202 for (; i != NumOperands; ++i) { 2203 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2204 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2205 APInt NewScale = 2206 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2207 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2208 // A multiplication of a constant with another add; recurse. 2209 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2210 Interesting |= 2211 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2212 Add->op_begin(), Add->getNumOperands(), 2213 NewScale, SE); 2214 } else { 2215 // A multiplication of a constant with some other value. Update 2216 // the map. 2217 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands())); 2218 const SCEV *Key = SE.getMulExpr(MulOps); 2219 auto Pair = M.insert({Key, NewScale}); 2220 if (Pair.second) { 2221 NewOps.push_back(Pair.first->first); 2222 } else { 2223 Pair.first->second += NewScale; 2224 // The map already had an entry for this value, which may indicate 2225 // a folding opportunity. 2226 Interesting = true; 2227 } 2228 } 2229 } else { 2230 // An ordinary operand. Update the map. 2231 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2232 M.insert({Ops[i], Scale}); 2233 if (Pair.second) { 2234 NewOps.push_back(Pair.first->first); 2235 } else { 2236 Pair.first->second += Scale; 2237 // The map already had an entry for this value, which may indicate 2238 // a folding opportunity. 2239 Interesting = true; 2240 } 2241 } 2242 } 2243 2244 return Interesting; 2245 } 2246 2247 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, 2248 const SCEV *LHS, const SCEV *RHS) { 2249 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *, 2250 SCEV::NoWrapFlags, unsigned); 2251 switch (BinOp) { 2252 default: 2253 llvm_unreachable("Unsupported binary op"); 2254 case Instruction::Add: 2255 Operation = &ScalarEvolution::getAddExpr; 2256 break; 2257 case Instruction::Sub: 2258 Operation = &ScalarEvolution::getMinusSCEV; 2259 break; 2260 case Instruction::Mul: 2261 Operation = &ScalarEvolution::getMulExpr; 2262 break; 2263 } 2264 2265 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) = 2266 Signed ? &ScalarEvolution::getSignExtendExpr 2267 : &ScalarEvolution::getZeroExtendExpr; 2268 2269 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS) 2270 auto *NarrowTy = cast<IntegerType>(LHS->getType()); 2271 auto *WideTy = 2272 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2); 2273 2274 const SCEV *A = (this->*Extension)( 2275 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0); 2276 const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0), 2277 (this->*Extension)(RHS, WideTy, 0), 2278 SCEV::FlagAnyWrap, 0); 2279 return A == B; 2280 } 2281 2282 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/> 2283 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp( 2284 const OverflowingBinaryOperator *OBO) { 2285 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap; 2286 2287 if (OBO->hasNoUnsignedWrap()) 2288 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2289 if (OBO->hasNoSignedWrap()) 2290 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2291 2292 bool Deduced = false; 2293 2294 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap()) 2295 return {Flags, Deduced}; 2296 2297 if (OBO->getOpcode() != Instruction::Add && 2298 OBO->getOpcode() != Instruction::Sub && 2299 OBO->getOpcode() != Instruction::Mul) 2300 return {Flags, Deduced}; 2301 2302 const SCEV *LHS = getSCEV(OBO->getOperand(0)); 2303 const SCEV *RHS = getSCEV(OBO->getOperand(1)); 2304 2305 if (!OBO->hasNoUnsignedWrap() && 2306 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2307 /* Signed */ false, LHS, RHS)) { 2308 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2309 Deduced = true; 2310 } 2311 2312 if (!OBO->hasNoSignedWrap() && 2313 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2314 /* Signed */ true, LHS, RHS)) { 2315 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2316 Deduced = true; 2317 } 2318 2319 return {Flags, Deduced}; 2320 } 2321 2322 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2323 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2324 // can't-overflow flags for the operation if possible. 2325 static SCEV::NoWrapFlags 2326 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2327 const ArrayRef<const SCEV *> Ops, 2328 SCEV::NoWrapFlags Flags) { 2329 using namespace std::placeholders; 2330 2331 using OBO = OverflowingBinaryOperator; 2332 2333 bool CanAnalyze = 2334 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2335 (void)CanAnalyze; 2336 assert(CanAnalyze && "don't call from other places!"); 2337 2338 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2339 SCEV::NoWrapFlags SignOrUnsignWrap = 2340 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2341 2342 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2343 auto IsKnownNonNegative = [&](const SCEV *S) { 2344 return SE->isKnownNonNegative(S); 2345 }; 2346 2347 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2348 Flags = 2349 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2350 2351 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2352 2353 if (SignOrUnsignWrap != SignOrUnsignMask && 2354 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2355 isa<SCEVConstant>(Ops[0])) { 2356 2357 auto Opcode = [&] { 2358 switch (Type) { 2359 case scAddExpr: 2360 return Instruction::Add; 2361 case scMulExpr: 2362 return Instruction::Mul; 2363 default: 2364 llvm_unreachable("Unexpected SCEV op."); 2365 } 2366 }(); 2367 2368 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2369 2370 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2371 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2372 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2373 Opcode, C, OBO::NoSignedWrap); 2374 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2375 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2376 } 2377 2378 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2379 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2380 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2381 Opcode, C, OBO::NoUnsignedWrap); 2382 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2383 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2384 } 2385 } 2386 2387 return Flags; 2388 } 2389 2390 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2391 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2392 } 2393 2394 /// Get a canonical add expression, or something simpler if possible. 2395 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2396 SCEV::NoWrapFlags OrigFlags, 2397 unsigned Depth) { 2398 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2399 "only nuw or nsw allowed"); 2400 assert(!Ops.empty() && "Cannot get empty add!"); 2401 if (Ops.size() == 1) return Ops[0]; 2402 #ifndef NDEBUG 2403 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2404 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2405 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2406 "SCEVAddExpr operand types don't match!"); 2407 #endif 2408 2409 // Sort by complexity, this groups all similar expression types together. 2410 GroupByComplexity(Ops, &LI, DT); 2411 2412 // If there are any constants, fold them together. 2413 unsigned Idx = 0; 2414 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2415 ++Idx; 2416 assert(Idx < Ops.size()); 2417 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2418 // We found two constants, fold them together! 2419 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2420 if (Ops.size() == 2) return Ops[0]; 2421 Ops.erase(Ops.begin()+1); // Erase the folded element 2422 LHSC = cast<SCEVConstant>(Ops[0]); 2423 } 2424 2425 // If we are left with a constant zero being added, strip it off. 2426 if (LHSC->getValue()->isZero()) { 2427 Ops.erase(Ops.begin()); 2428 --Idx; 2429 } 2430 2431 if (Ops.size() == 1) return Ops[0]; 2432 } 2433 2434 // Delay expensive flag strengthening until necessary. 2435 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2436 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2437 }; 2438 2439 // Limit recursion calls depth. 2440 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2441 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2442 2443 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) { 2444 // Don't strengthen flags if we have no new information. 2445 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2446 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2447 Add->setNoWrapFlags(ComputeFlags(Ops)); 2448 return S; 2449 } 2450 2451 // Okay, check to see if the same value occurs in the operand list more than 2452 // once. If so, merge them together into an multiply expression. Since we 2453 // sorted the list, these values are required to be adjacent. 2454 Type *Ty = Ops[0]->getType(); 2455 bool FoundMatch = false; 2456 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2457 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2458 // Scan ahead to count how many equal operands there are. 2459 unsigned Count = 2; 2460 while (i+Count != e && Ops[i+Count] == Ops[i]) 2461 ++Count; 2462 // Merge the values into a multiply. 2463 const SCEV *Scale = getConstant(Ty, Count); 2464 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2465 if (Ops.size() == Count) 2466 return Mul; 2467 Ops[i] = Mul; 2468 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2469 --i; e -= Count - 1; 2470 FoundMatch = true; 2471 } 2472 if (FoundMatch) 2473 return getAddExpr(Ops, OrigFlags, Depth + 1); 2474 2475 // Check for truncates. If all the operands are truncated from the same 2476 // type, see if factoring out the truncate would permit the result to be 2477 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2478 // if the contents of the resulting outer trunc fold to something simple. 2479 auto FindTruncSrcType = [&]() -> Type * { 2480 // We're ultimately looking to fold an addrec of truncs and muls of only 2481 // constants and truncs, so if we find any other types of SCEV 2482 // as operands of the addrec then we bail and return nullptr here. 2483 // Otherwise, we return the type of the operand of a trunc that we find. 2484 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2485 return T->getOperand()->getType(); 2486 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2487 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2488 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2489 return T->getOperand()->getType(); 2490 } 2491 return nullptr; 2492 }; 2493 if (auto *SrcType = FindTruncSrcType()) { 2494 SmallVector<const SCEV *, 8> LargeOps; 2495 bool Ok = true; 2496 // Check all the operands to see if they can be represented in the 2497 // source type of the truncate. 2498 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2499 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2500 if (T->getOperand()->getType() != SrcType) { 2501 Ok = false; 2502 break; 2503 } 2504 LargeOps.push_back(T->getOperand()); 2505 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2506 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2507 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2508 SmallVector<const SCEV *, 8> LargeMulOps; 2509 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2510 if (const SCEVTruncateExpr *T = 2511 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2512 if (T->getOperand()->getType() != SrcType) { 2513 Ok = false; 2514 break; 2515 } 2516 LargeMulOps.push_back(T->getOperand()); 2517 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2518 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2519 } else { 2520 Ok = false; 2521 break; 2522 } 2523 } 2524 if (Ok) 2525 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2526 } else { 2527 Ok = false; 2528 break; 2529 } 2530 } 2531 if (Ok) { 2532 // Evaluate the expression in the larger type. 2533 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2534 // If it folds to something simple, use it. Otherwise, don't. 2535 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2536 return getTruncateExpr(Fold, Ty); 2537 } 2538 } 2539 2540 // Skip past any other cast SCEVs. 2541 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2542 ++Idx; 2543 2544 // If there are add operands they would be next. 2545 if (Idx < Ops.size()) { 2546 bool DeletedAdd = false; 2547 // If the original flags and all inlined SCEVAddExprs are NUW, use the 2548 // common NUW flag for expression after inlining. Other flags cannot be 2549 // preserved, because they may depend on the original order of operations. 2550 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW); 2551 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2552 if (Ops.size() > AddOpsInlineThreshold || 2553 Add->getNumOperands() > AddOpsInlineThreshold) 2554 break; 2555 // If we have an add, expand the add operands onto the end of the operands 2556 // list. 2557 Ops.erase(Ops.begin()+Idx); 2558 Ops.append(Add->op_begin(), Add->op_end()); 2559 DeletedAdd = true; 2560 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags()); 2561 } 2562 2563 // If we deleted at least one add, we added operands to the end of the list, 2564 // and they are not necessarily sorted. Recurse to resort and resimplify 2565 // any operands we just acquired. 2566 if (DeletedAdd) 2567 return getAddExpr(Ops, CommonFlags, Depth + 1); 2568 } 2569 2570 // Skip over the add expression until we get to a multiply. 2571 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2572 ++Idx; 2573 2574 // Check to see if there are any folding opportunities present with 2575 // operands multiplied by constant values. 2576 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2577 uint64_t BitWidth = getTypeSizeInBits(Ty); 2578 DenseMap<const SCEV *, APInt> M; 2579 SmallVector<const SCEV *, 8> NewOps; 2580 APInt AccumulatedConstant(BitWidth, 0); 2581 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2582 Ops.data(), Ops.size(), 2583 APInt(BitWidth, 1), *this)) { 2584 struct APIntCompare { 2585 bool operator()(const APInt &LHS, const APInt &RHS) const { 2586 return LHS.ult(RHS); 2587 } 2588 }; 2589 2590 // Some interesting folding opportunity is present, so its worthwhile to 2591 // re-generate the operands list. Group the operands by constant scale, 2592 // to avoid multiplying by the same constant scale multiple times. 2593 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2594 for (const SCEV *NewOp : NewOps) 2595 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2596 // Re-generate the operands list. 2597 Ops.clear(); 2598 if (AccumulatedConstant != 0) 2599 Ops.push_back(getConstant(AccumulatedConstant)); 2600 for (auto &MulOp : MulOpLists) 2601 if (MulOp.first != 0) 2602 Ops.push_back(getMulExpr( 2603 getConstant(MulOp.first), 2604 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2605 SCEV::FlagAnyWrap, Depth + 1)); 2606 if (Ops.empty()) 2607 return getZero(Ty); 2608 if (Ops.size() == 1) 2609 return Ops[0]; 2610 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2611 } 2612 } 2613 2614 // If we are adding something to a multiply expression, make sure the 2615 // something is not already an operand of the multiply. If so, merge it into 2616 // the multiply. 2617 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2618 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2619 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2620 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2621 if (isa<SCEVConstant>(MulOpSCEV)) 2622 continue; 2623 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2624 if (MulOpSCEV == Ops[AddOp]) { 2625 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2626 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2627 if (Mul->getNumOperands() != 2) { 2628 // If the multiply has more than two operands, we must get the 2629 // Y*Z term. 2630 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2631 Mul->op_begin()+MulOp); 2632 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2633 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2634 } 2635 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2636 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2637 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2638 SCEV::FlagAnyWrap, Depth + 1); 2639 if (Ops.size() == 2) return OuterMul; 2640 if (AddOp < Idx) { 2641 Ops.erase(Ops.begin()+AddOp); 2642 Ops.erase(Ops.begin()+Idx-1); 2643 } else { 2644 Ops.erase(Ops.begin()+Idx); 2645 Ops.erase(Ops.begin()+AddOp-1); 2646 } 2647 Ops.push_back(OuterMul); 2648 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2649 } 2650 2651 // Check this multiply against other multiplies being added together. 2652 for (unsigned OtherMulIdx = Idx+1; 2653 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2654 ++OtherMulIdx) { 2655 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2656 // If MulOp occurs in OtherMul, we can fold the two multiplies 2657 // together. 2658 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2659 OMulOp != e; ++OMulOp) 2660 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2661 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2662 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2663 if (Mul->getNumOperands() != 2) { 2664 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2665 Mul->op_begin()+MulOp); 2666 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2667 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2668 } 2669 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2670 if (OtherMul->getNumOperands() != 2) { 2671 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2672 OtherMul->op_begin()+OMulOp); 2673 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2674 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2675 } 2676 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2677 const SCEV *InnerMulSum = 2678 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2679 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2680 SCEV::FlagAnyWrap, Depth + 1); 2681 if (Ops.size() == 2) return OuterMul; 2682 Ops.erase(Ops.begin()+Idx); 2683 Ops.erase(Ops.begin()+OtherMulIdx-1); 2684 Ops.push_back(OuterMul); 2685 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2686 } 2687 } 2688 } 2689 } 2690 2691 // If there are any add recurrences in the operands list, see if any other 2692 // added values are loop invariant. If so, we can fold them into the 2693 // recurrence. 2694 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2695 ++Idx; 2696 2697 // Scan over all recurrences, trying to fold loop invariants into them. 2698 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2699 // Scan all of the other operands to this add and add them to the vector if 2700 // they are loop invariant w.r.t. the recurrence. 2701 SmallVector<const SCEV *, 8> LIOps; 2702 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2703 const Loop *AddRecLoop = AddRec->getLoop(); 2704 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2705 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2706 LIOps.push_back(Ops[i]); 2707 Ops.erase(Ops.begin()+i); 2708 --i; --e; 2709 } 2710 2711 // If we found some loop invariants, fold them into the recurrence. 2712 if (!LIOps.empty()) { 2713 // Compute nowrap flags for the addition of the loop-invariant ops and 2714 // the addrec. Temporarily push it as an operand for that purpose. 2715 LIOps.push_back(AddRec); 2716 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2717 LIOps.pop_back(); 2718 2719 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2720 LIOps.push_back(AddRec->getStart()); 2721 2722 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2723 // This follows from the fact that the no-wrap flags on the outer add 2724 // expression are applicable on the 0th iteration, when the add recurrence 2725 // will be equal to its start value. 2726 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2727 2728 // Build the new addrec. Propagate the NUW and NSW flags if both the 2729 // outer add and the inner addrec are guaranteed to have no overflow. 2730 // Always propagate NW. 2731 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2732 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2733 2734 // If all of the other operands were loop invariant, we are done. 2735 if (Ops.size() == 1) return NewRec; 2736 2737 // Otherwise, add the folded AddRec by the non-invariant parts. 2738 for (unsigned i = 0;; ++i) 2739 if (Ops[i] == AddRec) { 2740 Ops[i] = NewRec; 2741 break; 2742 } 2743 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2744 } 2745 2746 // Okay, if there weren't any loop invariants to be folded, check to see if 2747 // there are multiple AddRec's with the same loop induction variable being 2748 // added together. If so, we can fold them. 2749 for (unsigned OtherIdx = Idx+1; 2750 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2751 ++OtherIdx) { 2752 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2753 // so that the 1st found AddRecExpr is dominated by all others. 2754 assert(DT.dominates( 2755 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2756 AddRec->getLoop()->getHeader()) && 2757 "AddRecExprs are not sorted in reverse dominance order?"); 2758 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2759 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2760 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2761 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2762 ++OtherIdx) { 2763 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2764 if (OtherAddRec->getLoop() == AddRecLoop) { 2765 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2766 i != e; ++i) { 2767 if (i >= AddRecOps.size()) { 2768 AddRecOps.append(OtherAddRec->op_begin()+i, 2769 OtherAddRec->op_end()); 2770 break; 2771 } 2772 SmallVector<const SCEV *, 2> TwoOps = { 2773 AddRecOps[i], OtherAddRec->getOperand(i)}; 2774 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2775 } 2776 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2777 } 2778 } 2779 // Step size has changed, so we cannot guarantee no self-wraparound. 2780 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2781 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2782 } 2783 } 2784 2785 // Otherwise couldn't fold anything into this recurrence. Move onto the 2786 // next one. 2787 } 2788 2789 // Okay, it looks like we really DO need an add expr. Check to see if we 2790 // already have one, otherwise create a new one. 2791 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2792 } 2793 2794 const SCEV * 2795 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2796 SCEV::NoWrapFlags Flags) { 2797 FoldingSetNodeID ID; 2798 ID.AddInteger(scAddExpr); 2799 for (const SCEV *Op : Ops) 2800 ID.AddPointer(Op); 2801 void *IP = nullptr; 2802 SCEVAddExpr *S = 2803 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2804 if (!S) { 2805 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2806 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2807 S = new (SCEVAllocator) 2808 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2809 UniqueSCEVs.InsertNode(S, IP); 2810 addToLoopUseLists(S); 2811 } 2812 S->setNoWrapFlags(Flags); 2813 return S; 2814 } 2815 2816 const SCEV * 2817 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2818 const Loop *L, SCEV::NoWrapFlags Flags) { 2819 FoldingSetNodeID ID; 2820 ID.AddInteger(scAddRecExpr); 2821 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2822 ID.AddPointer(Ops[i]); 2823 ID.AddPointer(L); 2824 void *IP = nullptr; 2825 SCEVAddRecExpr *S = 2826 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2827 if (!S) { 2828 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2829 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2830 S = new (SCEVAllocator) 2831 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2832 UniqueSCEVs.InsertNode(S, IP); 2833 addToLoopUseLists(S); 2834 } 2835 setNoWrapFlags(S, Flags); 2836 return S; 2837 } 2838 2839 const SCEV * 2840 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2841 SCEV::NoWrapFlags Flags) { 2842 FoldingSetNodeID ID; 2843 ID.AddInteger(scMulExpr); 2844 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2845 ID.AddPointer(Ops[i]); 2846 void *IP = nullptr; 2847 SCEVMulExpr *S = 2848 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2849 if (!S) { 2850 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2851 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2852 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2853 O, Ops.size()); 2854 UniqueSCEVs.InsertNode(S, IP); 2855 addToLoopUseLists(S); 2856 } 2857 S->setNoWrapFlags(Flags); 2858 return S; 2859 } 2860 2861 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2862 uint64_t k = i*j; 2863 if (j > 1 && k / j != i) Overflow = true; 2864 return k; 2865 } 2866 2867 /// Compute the result of "n choose k", the binomial coefficient. If an 2868 /// intermediate computation overflows, Overflow will be set and the return will 2869 /// be garbage. Overflow is not cleared on absence of overflow. 2870 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2871 // We use the multiplicative formula: 2872 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2873 // At each iteration, we take the n-th term of the numeral and divide by the 2874 // (k-n)th term of the denominator. This division will always produce an 2875 // integral result, and helps reduce the chance of overflow in the 2876 // intermediate computations. However, we can still overflow even when the 2877 // final result would fit. 2878 2879 if (n == 0 || n == k) return 1; 2880 if (k > n) return 0; 2881 2882 if (k > n/2) 2883 k = n-k; 2884 2885 uint64_t r = 1; 2886 for (uint64_t i = 1; i <= k; ++i) { 2887 r = umul_ov(r, n-(i-1), Overflow); 2888 r /= i; 2889 } 2890 return r; 2891 } 2892 2893 /// Determine if any of the operands in this SCEV are a constant or if 2894 /// any of the add or multiply expressions in this SCEV contain a constant. 2895 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2896 struct FindConstantInAddMulChain { 2897 bool FoundConstant = false; 2898 2899 bool follow(const SCEV *S) { 2900 FoundConstant |= isa<SCEVConstant>(S); 2901 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2902 } 2903 2904 bool isDone() const { 2905 return FoundConstant; 2906 } 2907 }; 2908 2909 FindConstantInAddMulChain F; 2910 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2911 ST.visitAll(StartExpr); 2912 return F.FoundConstant; 2913 } 2914 2915 /// Get a canonical multiply expression, or something simpler if possible. 2916 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2917 SCEV::NoWrapFlags OrigFlags, 2918 unsigned Depth) { 2919 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 2920 "only nuw or nsw allowed"); 2921 assert(!Ops.empty() && "Cannot get empty mul!"); 2922 if (Ops.size() == 1) return Ops[0]; 2923 #ifndef NDEBUG 2924 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2925 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2926 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2927 "SCEVMulExpr operand types don't match!"); 2928 #endif 2929 2930 // Sort by complexity, this groups all similar expression types together. 2931 GroupByComplexity(Ops, &LI, DT); 2932 2933 // If there are any constants, fold them together. 2934 unsigned Idx = 0; 2935 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2936 ++Idx; 2937 assert(Idx < Ops.size()); 2938 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2939 // We found two constants, fold them together! 2940 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 2941 if (Ops.size() == 2) return Ops[0]; 2942 Ops.erase(Ops.begin()+1); // Erase the folded element 2943 LHSC = cast<SCEVConstant>(Ops[0]); 2944 } 2945 2946 // If we have a multiply of zero, it will always be zero. 2947 if (LHSC->getValue()->isZero()) 2948 return LHSC; 2949 2950 // If we are left with a constant one being multiplied, strip it off. 2951 if (LHSC->getValue()->isOne()) { 2952 Ops.erase(Ops.begin()); 2953 --Idx; 2954 } 2955 2956 if (Ops.size() == 1) 2957 return Ops[0]; 2958 } 2959 2960 // Delay expensive flag strengthening until necessary. 2961 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2962 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 2963 }; 2964 2965 // Limit recursion calls depth. 2966 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2967 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 2968 2969 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { 2970 // Don't strengthen flags if we have no new information. 2971 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 2972 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 2973 Mul->setNoWrapFlags(ComputeFlags(Ops)); 2974 return S; 2975 } 2976 2977 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2978 if (Ops.size() == 2) { 2979 // C1*(C2+V) -> C1*C2 + C1*V 2980 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2981 // If any of Add's ops are Adds or Muls with a constant, apply this 2982 // transformation as well. 2983 // 2984 // TODO: There are some cases where this transformation is not 2985 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2986 // this transformation should be narrowed down. 2987 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2988 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2989 SCEV::FlagAnyWrap, Depth + 1), 2990 getMulExpr(LHSC, Add->getOperand(1), 2991 SCEV::FlagAnyWrap, Depth + 1), 2992 SCEV::FlagAnyWrap, Depth + 1); 2993 2994 if (Ops[0]->isAllOnesValue()) { 2995 // If we have a mul by -1 of an add, try distributing the -1 among the 2996 // add operands. 2997 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2998 SmallVector<const SCEV *, 4> NewOps; 2999 bool AnyFolded = false; 3000 for (const SCEV *AddOp : Add->operands()) { 3001 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 3002 Depth + 1); 3003 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 3004 NewOps.push_back(Mul); 3005 } 3006 if (AnyFolded) 3007 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 3008 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 3009 // Negation preserves a recurrence's no self-wrap property. 3010 SmallVector<const SCEV *, 4> Operands; 3011 for (const SCEV *AddRecOp : AddRec->operands()) 3012 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3013 Depth + 1)); 3014 3015 return getAddRecExpr(Operands, AddRec->getLoop(), 3016 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3017 } 3018 } 3019 } 3020 } 3021 3022 // Skip over the add expression until we get to a multiply. 3023 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3024 ++Idx; 3025 3026 // If there are mul operands inline them all into this expression. 3027 if (Idx < Ops.size()) { 3028 bool DeletedMul = false; 3029 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3030 if (Ops.size() > MulOpsInlineThreshold) 3031 break; 3032 // If we have an mul, expand the mul operands onto the end of the 3033 // operands list. 3034 Ops.erase(Ops.begin()+Idx); 3035 Ops.append(Mul->op_begin(), Mul->op_end()); 3036 DeletedMul = true; 3037 } 3038 3039 // If we deleted at least one mul, we added operands to the end of the 3040 // list, and they are not necessarily sorted. Recurse to resort and 3041 // resimplify any operands we just acquired. 3042 if (DeletedMul) 3043 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3044 } 3045 3046 // If there are any add recurrences in the operands list, see if any other 3047 // added values are loop invariant. If so, we can fold them into the 3048 // recurrence. 3049 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3050 ++Idx; 3051 3052 // Scan over all recurrences, trying to fold loop invariants into them. 3053 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3054 // Scan all of the other operands to this mul and add them to the vector 3055 // if they are loop invariant w.r.t. the recurrence. 3056 SmallVector<const SCEV *, 8> LIOps; 3057 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3058 const Loop *AddRecLoop = AddRec->getLoop(); 3059 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3060 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3061 LIOps.push_back(Ops[i]); 3062 Ops.erase(Ops.begin()+i); 3063 --i; --e; 3064 } 3065 3066 // If we found some loop invariants, fold them into the recurrence. 3067 if (!LIOps.empty()) { 3068 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3069 SmallVector<const SCEV *, 4> NewOps; 3070 NewOps.reserve(AddRec->getNumOperands()); 3071 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3072 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3073 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3074 SCEV::FlagAnyWrap, Depth + 1)); 3075 3076 // Build the new addrec. Propagate the NUW and NSW flags if both the 3077 // outer mul and the inner addrec are guaranteed to have no overflow. 3078 // 3079 // No self-wrap cannot be guaranteed after changing the step size, but 3080 // will be inferred if either NUW or NSW is true. 3081 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 3082 const SCEV *NewRec = getAddRecExpr( 3083 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 3084 3085 // If all of the other operands were loop invariant, we are done. 3086 if (Ops.size() == 1) return NewRec; 3087 3088 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3089 for (unsigned i = 0;; ++i) 3090 if (Ops[i] == AddRec) { 3091 Ops[i] = NewRec; 3092 break; 3093 } 3094 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3095 } 3096 3097 // Okay, if there weren't any loop invariants to be folded, check to see 3098 // if there are multiple AddRec's with the same loop induction variable 3099 // being multiplied together. If so, we can fold them. 3100 3101 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3102 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3103 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3104 // ]]],+,...up to x=2n}. 3105 // Note that the arguments to choose() are always integers with values 3106 // known at compile time, never SCEV objects. 3107 // 3108 // The implementation avoids pointless extra computations when the two 3109 // addrec's are of different length (mathematically, it's equivalent to 3110 // an infinite stream of zeros on the right). 3111 bool OpsModified = false; 3112 for (unsigned OtherIdx = Idx+1; 3113 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3114 ++OtherIdx) { 3115 const SCEVAddRecExpr *OtherAddRec = 3116 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3117 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3118 continue; 3119 3120 // Limit max number of arguments to avoid creation of unreasonably big 3121 // SCEVAddRecs with very complex operands. 3122 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3123 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3124 continue; 3125 3126 bool Overflow = false; 3127 Type *Ty = AddRec->getType(); 3128 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3129 SmallVector<const SCEV*, 7> AddRecOps; 3130 for (int x = 0, xe = AddRec->getNumOperands() + 3131 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3132 SmallVector <const SCEV *, 7> SumOps; 3133 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3134 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3135 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3136 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3137 z < ze && !Overflow; ++z) { 3138 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3139 uint64_t Coeff; 3140 if (LargerThan64Bits) 3141 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3142 else 3143 Coeff = Coeff1*Coeff2; 3144 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3145 const SCEV *Term1 = AddRec->getOperand(y-z); 3146 const SCEV *Term2 = OtherAddRec->getOperand(z); 3147 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3148 SCEV::FlagAnyWrap, Depth + 1)); 3149 } 3150 } 3151 if (SumOps.empty()) 3152 SumOps.push_back(getZero(Ty)); 3153 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3154 } 3155 if (!Overflow) { 3156 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3157 SCEV::FlagAnyWrap); 3158 if (Ops.size() == 2) return NewAddRec; 3159 Ops[Idx] = NewAddRec; 3160 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3161 OpsModified = true; 3162 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3163 if (!AddRec) 3164 break; 3165 } 3166 } 3167 if (OpsModified) 3168 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3169 3170 // Otherwise couldn't fold anything into this recurrence. Move onto the 3171 // next one. 3172 } 3173 3174 // Okay, it looks like we really DO need an mul expr. Check to see if we 3175 // already have one, otherwise create a new one. 3176 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3177 } 3178 3179 /// Represents an unsigned remainder expression based on unsigned division. 3180 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3181 const SCEV *RHS) { 3182 assert(getEffectiveSCEVType(LHS->getType()) == 3183 getEffectiveSCEVType(RHS->getType()) && 3184 "SCEVURemExpr operand types don't match!"); 3185 3186 // Short-circuit easy cases 3187 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3188 // If constant is one, the result is trivial 3189 if (RHSC->getValue()->isOne()) 3190 return getZero(LHS->getType()); // X urem 1 --> 0 3191 3192 // If constant is a power of two, fold into a zext(trunc(LHS)). 3193 if (RHSC->getAPInt().isPowerOf2()) { 3194 Type *FullTy = LHS->getType(); 3195 Type *TruncTy = 3196 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3197 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3198 } 3199 } 3200 3201 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3202 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3203 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3204 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3205 } 3206 3207 /// Get a canonical unsigned division expression, or something simpler if 3208 /// possible. 3209 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3210 const SCEV *RHS) { 3211 assert(getEffectiveSCEVType(LHS->getType()) == 3212 getEffectiveSCEVType(RHS->getType()) && 3213 "SCEVUDivExpr operand types don't match!"); 3214 3215 FoldingSetNodeID ID; 3216 ID.AddInteger(scUDivExpr); 3217 ID.AddPointer(LHS); 3218 ID.AddPointer(RHS); 3219 void *IP = nullptr; 3220 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3221 return S; 3222 3223 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3224 if (RHSC->getValue()->isOne()) 3225 return LHS; // X udiv 1 --> x 3226 // If the denominator is zero, the result of the udiv is undefined. Don't 3227 // try to analyze it, because the resolution chosen here may differ from 3228 // the resolution chosen in other parts of the compiler. 3229 if (!RHSC->getValue()->isZero()) { 3230 // Determine if the division can be folded into the operands of 3231 // its operands. 3232 // TODO: Generalize this to non-constants by using known-bits information. 3233 Type *Ty = LHS->getType(); 3234 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3235 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3236 // For non-power-of-two values, effectively round the value up to the 3237 // nearest power of two. 3238 if (!RHSC->getAPInt().isPowerOf2()) 3239 ++MaxShiftAmt; 3240 IntegerType *ExtTy = 3241 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3242 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3243 if (const SCEVConstant *Step = 3244 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3245 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3246 const APInt &StepInt = Step->getAPInt(); 3247 const APInt &DivInt = RHSC->getAPInt(); 3248 if (!StepInt.urem(DivInt) && 3249 getZeroExtendExpr(AR, ExtTy) == 3250 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3251 getZeroExtendExpr(Step, ExtTy), 3252 AR->getLoop(), SCEV::FlagAnyWrap)) { 3253 SmallVector<const SCEV *, 4> Operands; 3254 for (const SCEV *Op : AR->operands()) 3255 Operands.push_back(getUDivExpr(Op, RHS)); 3256 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3257 } 3258 /// Get a canonical UDivExpr for a recurrence. 3259 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3260 // We can currently only fold X%N if X is constant. 3261 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3262 if (StartC && !DivInt.urem(StepInt) && 3263 getZeroExtendExpr(AR, ExtTy) == 3264 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3265 getZeroExtendExpr(Step, ExtTy), 3266 AR->getLoop(), SCEV::FlagAnyWrap)) { 3267 const APInt &StartInt = StartC->getAPInt(); 3268 const APInt &StartRem = StartInt.urem(StepInt); 3269 if (StartRem != 0) { 3270 const SCEV *NewLHS = 3271 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3272 AR->getLoop(), SCEV::FlagNW); 3273 if (LHS != NewLHS) { 3274 LHS = NewLHS; 3275 3276 // Reset the ID to include the new LHS, and check if it is 3277 // already cached. 3278 ID.clear(); 3279 ID.AddInteger(scUDivExpr); 3280 ID.AddPointer(LHS); 3281 ID.AddPointer(RHS); 3282 IP = nullptr; 3283 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3284 return S; 3285 } 3286 } 3287 } 3288 } 3289 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3290 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3291 SmallVector<const SCEV *, 4> Operands; 3292 for (const SCEV *Op : M->operands()) 3293 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3294 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3295 // Find an operand that's safely divisible. 3296 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3297 const SCEV *Op = M->getOperand(i); 3298 const SCEV *Div = getUDivExpr(Op, RHSC); 3299 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3300 Operands = SmallVector<const SCEV *, 4>(M->operands()); 3301 Operands[i] = Div; 3302 return getMulExpr(Operands); 3303 } 3304 } 3305 } 3306 3307 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3308 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3309 if (auto *DivisorConstant = 3310 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3311 bool Overflow = false; 3312 APInt NewRHS = 3313 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3314 if (Overflow) { 3315 return getConstant(RHSC->getType(), 0, false); 3316 } 3317 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3318 } 3319 } 3320 3321 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3322 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3323 SmallVector<const SCEV *, 4> Operands; 3324 for (const SCEV *Op : A->operands()) 3325 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3326 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3327 Operands.clear(); 3328 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3329 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3330 if (isa<SCEVUDivExpr>(Op) || 3331 getMulExpr(Op, RHS) != A->getOperand(i)) 3332 break; 3333 Operands.push_back(Op); 3334 } 3335 if (Operands.size() == A->getNumOperands()) 3336 return getAddExpr(Operands); 3337 } 3338 } 3339 3340 // Fold if both operands are constant. 3341 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3342 Constant *LHSCV = LHSC->getValue(); 3343 Constant *RHSCV = RHSC->getValue(); 3344 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3345 RHSCV))); 3346 } 3347 } 3348 } 3349 3350 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3351 // changes). Make sure we get a new one. 3352 IP = nullptr; 3353 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3354 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3355 LHS, RHS); 3356 UniqueSCEVs.InsertNode(S, IP); 3357 addToLoopUseLists(S); 3358 return S; 3359 } 3360 3361 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3362 APInt A = C1->getAPInt().abs(); 3363 APInt B = C2->getAPInt().abs(); 3364 uint32_t ABW = A.getBitWidth(); 3365 uint32_t BBW = B.getBitWidth(); 3366 3367 if (ABW > BBW) 3368 B = B.zext(ABW); 3369 else if (ABW < BBW) 3370 A = A.zext(BBW); 3371 3372 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3373 } 3374 3375 /// Get a canonical unsigned division expression, or something simpler if 3376 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3377 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3378 /// it's not exact because the udiv may be clearing bits. 3379 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3380 const SCEV *RHS) { 3381 // TODO: we could try to find factors in all sorts of things, but for now we 3382 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3383 // end of this file for inspiration. 3384 3385 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3386 if (!Mul || !Mul->hasNoUnsignedWrap()) 3387 return getUDivExpr(LHS, RHS); 3388 3389 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3390 // If the mulexpr multiplies by a constant, then that constant must be the 3391 // first element of the mulexpr. 3392 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3393 if (LHSCst == RHSCst) { 3394 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands())); 3395 return getMulExpr(Operands); 3396 } 3397 3398 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3399 // that there's a factor provided by one of the other terms. We need to 3400 // check. 3401 APInt Factor = gcd(LHSCst, RHSCst); 3402 if (!Factor.isIntN(1)) { 3403 LHSCst = 3404 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3405 RHSCst = 3406 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3407 SmallVector<const SCEV *, 2> Operands; 3408 Operands.push_back(LHSCst); 3409 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3410 LHS = getMulExpr(Operands); 3411 RHS = RHSCst; 3412 Mul = dyn_cast<SCEVMulExpr>(LHS); 3413 if (!Mul) 3414 return getUDivExactExpr(LHS, RHS); 3415 } 3416 } 3417 } 3418 3419 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3420 if (Mul->getOperand(i) == RHS) { 3421 SmallVector<const SCEV *, 2> Operands; 3422 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3423 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3424 return getMulExpr(Operands); 3425 } 3426 } 3427 3428 return getUDivExpr(LHS, RHS); 3429 } 3430 3431 /// Get an add recurrence expression for the specified loop. Simplify the 3432 /// expression as much as possible. 3433 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3434 const Loop *L, 3435 SCEV::NoWrapFlags Flags) { 3436 SmallVector<const SCEV *, 4> Operands; 3437 Operands.push_back(Start); 3438 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3439 if (StepChrec->getLoop() == L) { 3440 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3441 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3442 } 3443 3444 Operands.push_back(Step); 3445 return getAddRecExpr(Operands, L, Flags); 3446 } 3447 3448 /// Get an add recurrence expression for the specified loop. Simplify the 3449 /// expression as much as possible. 3450 const SCEV * 3451 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3452 const Loop *L, SCEV::NoWrapFlags Flags) { 3453 if (Operands.size() == 1) return Operands[0]; 3454 #ifndef NDEBUG 3455 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3456 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3457 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3458 "SCEVAddRecExpr operand types don't match!"); 3459 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3460 assert(isLoopInvariant(Operands[i], L) && 3461 "SCEVAddRecExpr operand is not loop-invariant!"); 3462 #endif 3463 3464 if (Operands.back()->isZero()) { 3465 Operands.pop_back(); 3466 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3467 } 3468 3469 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3470 // use that information to infer NUW and NSW flags. However, computing a 3471 // BE count requires calling getAddRecExpr, so we may not yet have a 3472 // meaningful BE count at this point (and if we don't, we'd be stuck 3473 // with a SCEVCouldNotCompute as the cached BE count). 3474 3475 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3476 3477 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3478 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3479 const Loop *NestedLoop = NestedAR->getLoop(); 3480 if (L->contains(NestedLoop) 3481 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3482 : (!NestedLoop->contains(L) && 3483 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3484 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands()); 3485 Operands[0] = NestedAR->getStart(); 3486 // AddRecs require their operands be loop-invariant with respect to their 3487 // loops. Don't perform this transformation if it would break this 3488 // requirement. 3489 bool AllInvariant = all_of( 3490 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3491 3492 if (AllInvariant) { 3493 // Create a recurrence for the outer loop with the same step size. 3494 // 3495 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3496 // inner recurrence has the same property. 3497 SCEV::NoWrapFlags OuterFlags = 3498 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3499 3500 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3501 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3502 return isLoopInvariant(Op, NestedLoop); 3503 }); 3504 3505 if (AllInvariant) { 3506 // Ok, both add recurrences are valid after the transformation. 3507 // 3508 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3509 // the outer recurrence has the same property. 3510 SCEV::NoWrapFlags InnerFlags = 3511 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3512 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3513 } 3514 } 3515 // Reset Operands to its original state. 3516 Operands[0] = NestedAR; 3517 } 3518 } 3519 3520 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3521 // already have one, otherwise create a new one. 3522 return getOrCreateAddRecExpr(Operands, L, Flags); 3523 } 3524 3525 const SCEV * 3526 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3527 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3528 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3529 // getSCEV(Base)->getType() has the same address space as Base->getType() 3530 // because SCEV::getType() preserves the address space. 3531 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3532 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3533 // instruction to its SCEV, because the Instruction may be guarded by control 3534 // flow and the no-overflow bits may not be valid for the expression in any 3535 // context. This can be fixed similarly to how these flags are handled for 3536 // adds. 3537 SCEV::NoWrapFlags OffsetWrap = 3538 GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3539 3540 Type *CurTy = GEP->getType(); 3541 bool FirstIter = true; 3542 SmallVector<const SCEV *, 4> Offsets; 3543 for (const SCEV *IndexExpr : IndexExprs) { 3544 // Compute the (potentially symbolic) offset in bytes for this index. 3545 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3546 // For a struct, add the member offset. 3547 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3548 unsigned FieldNo = Index->getZExtValue(); 3549 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3550 Offsets.push_back(FieldOffset); 3551 3552 // Update CurTy to the type of the field at Index. 3553 CurTy = STy->getTypeAtIndex(Index); 3554 } else { 3555 // Update CurTy to its element type. 3556 if (FirstIter) { 3557 assert(isa<PointerType>(CurTy) && 3558 "The first index of a GEP indexes a pointer"); 3559 CurTy = GEP->getSourceElementType(); 3560 FirstIter = false; 3561 } else { 3562 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3563 } 3564 // For an array, add the element offset, explicitly scaled. 3565 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3566 // Getelementptr indices are signed. 3567 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3568 3569 // Multiply the index by the element size to compute the element offset. 3570 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3571 Offsets.push_back(LocalOffset); 3572 } 3573 } 3574 3575 // Handle degenerate case of GEP without offsets. 3576 if (Offsets.empty()) 3577 return BaseExpr; 3578 3579 // Add the offsets together, assuming nsw if inbounds. 3580 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3581 // Add the base address and the offset. We cannot use the nsw flag, as the 3582 // base address is unsigned. However, if we know that the offset is 3583 // non-negative, we can use nuw. 3584 SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset) 3585 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3586 return getAddExpr(BaseExpr, Offset, BaseWrap); 3587 } 3588 3589 std::tuple<SCEV *, FoldingSetNodeID, void *> 3590 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3591 ArrayRef<const SCEV *> Ops) { 3592 FoldingSetNodeID ID; 3593 void *IP = nullptr; 3594 ID.AddInteger(SCEVType); 3595 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3596 ID.AddPointer(Ops[i]); 3597 return std::tuple<SCEV *, FoldingSetNodeID, void *>( 3598 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3599 } 3600 3601 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3602 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3603 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3604 } 3605 3606 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3607 SmallVectorImpl<const SCEV *> &Ops) { 3608 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3609 if (Ops.size() == 1) return Ops[0]; 3610 #ifndef NDEBUG 3611 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3612 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3613 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3614 "Operand types don't match!"); 3615 #endif 3616 3617 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3618 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3619 3620 // Sort by complexity, this groups all similar expression types together. 3621 GroupByComplexity(Ops, &LI, DT); 3622 3623 // Check if we have created the same expression before. 3624 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3625 return S; 3626 } 3627 3628 // If there are any constants, fold them together. 3629 unsigned Idx = 0; 3630 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3631 ++Idx; 3632 assert(Idx < Ops.size()); 3633 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3634 if (Kind == scSMaxExpr) 3635 return APIntOps::smax(LHS, RHS); 3636 else if (Kind == scSMinExpr) 3637 return APIntOps::smin(LHS, RHS); 3638 else if (Kind == scUMaxExpr) 3639 return APIntOps::umax(LHS, RHS); 3640 else if (Kind == scUMinExpr) 3641 return APIntOps::umin(LHS, RHS); 3642 llvm_unreachable("Unknown SCEV min/max opcode"); 3643 }; 3644 3645 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3646 // We found two constants, fold them together! 3647 ConstantInt *Fold = ConstantInt::get( 3648 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3649 Ops[0] = getConstant(Fold); 3650 Ops.erase(Ops.begin()+1); // Erase the folded element 3651 if (Ops.size() == 1) return Ops[0]; 3652 LHSC = cast<SCEVConstant>(Ops[0]); 3653 } 3654 3655 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3656 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3657 3658 if (IsMax ? IsMinV : IsMaxV) { 3659 // If we are left with a constant minimum(/maximum)-int, strip it off. 3660 Ops.erase(Ops.begin()); 3661 --Idx; 3662 } else if (IsMax ? IsMaxV : IsMinV) { 3663 // If we have a max(/min) with a constant maximum(/minimum)-int, 3664 // it will always be the extremum. 3665 return LHSC; 3666 } 3667 3668 if (Ops.size() == 1) return Ops[0]; 3669 } 3670 3671 // Find the first operation of the same kind 3672 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3673 ++Idx; 3674 3675 // Check to see if one of the operands is of the same kind. If so, expand its 3676 // operands onto our operand list, and recurse to simplify. 3677 if (Idx < Ops.size()) { 3678 bool DeletedAny = false; 3679 while (Ops[Idx]->getSCEVType() == Kind) { 3680 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3681 Ops.erase(Ops.begin()+Idx); 3682 Ops.append(SMME->op_begin(), SMME->op_end()); 3683 DeletedAny = true; 3684 } 3685 3686 if (DeletedAny) 3687 return getMinMaxExpr(Kind, Ops); 3688 } 3689 3690 // Okay, check to see if the same value occurs in the operand list twice. If 3691 // so, delete one. Since we sorted the list, these values are required to 3692 // be adjacent. 3693 llvm::CmpInst::Predicate GEPred = 3694 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3695 llvm::CmpInst::Predicate LEPred = 3696 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3697 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3698 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3699 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3700 if (Ops[i] == Ops[i + 1] || 3701 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3702 // X op Y op Y --> X op Y 3703 // X op Y --> X, if we know X, Y are ordered appropriately 3704 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3705 --i; 3706 --e; 3707 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3708 Ops[i + 1])) { 3709 // X op Y --> Y, if we know X, Y are ordered appropriately 3710 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3711 --i; 3712 --e; 3713 } 3714 } 3715 3716 if (Ops.size() == 1) return Ops[0]; 3717 3718 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3719 3720 // Okay, it looks like we really DO need an expr. Check to see if we 3721 // already have one, otherwise create a new one. 3722 const SCEV *ExistingSCEV; 3723 FoldingSetNodeID ID; 3724 void *IP; 3725 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3726 if (ExistingSCEV) 3727 return ExistingSCEV; 3728 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3729 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3730 SCEV *S = new (SCEVAllocator) 3731 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3732 3733 UniqueSCEVs.InsertNode(S, IP); 3734 addToLoopUseLists(S); 3735 return S; 3736 } 3737 3738 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3739 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3740 return getSMaxExpr(Ops); 3741 } 3742 3743 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3744 return getMinMaxExpr(scSMaxExpr, Ops); 3745 } 3746 3747 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3748 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3749 return getUMaxExpr(Ops); 3750 } 3751 3752 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3753 return getMinMaxExpr(scUMaxExpr, Ops); 3754 } 3755 3756 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3757 const SCEV *RHS) { 3758 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3759 return getSMinExpr(Ops); 3760 } 3761 3762 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3763 return getMinMaxExpr(scSMinExpr, Ops); 3764 } 3765 3766 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3767 const SCEV *RHS) { 3768 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3769 return getUMinExpr(Ops); 3770 } 3771 3772 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3773 return getMinMaxExpr(scUMinExpr, Ops); 3774 } 3775 3776 const SCEV * 3777 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 3778 ScalableVectorType *ScalableTy) { 3779 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 3780 Constant *One = ConstantInt::get(IntTy, 1); 3781 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 3782 // Note that the expression we created is the final expression, we don't 3783 // want to simplify it any further Also, if we call a normal getSCEV(), 3784 // we'll end up in an endless recursion. So just create an SCEVUnknown. 3785 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 3786 } 3787 3788 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3789 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 3790 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 3791 // We can bypass creating a target-independent constant expression and then 3792 // folding it back into a ConstantInt. This is just a compile-time 3793 // optimization. 3794 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3795 } 3796 3797 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 3798 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 3799 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 3800 // We can bypass creating a target-independent constant expression and then 3801 // folding it back into a ConstantInt. This is just a compile-time 3802 // optimization. 3803 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 3804 } 3805 3806 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3807 StructType *STy, 3808 unsigned FieldNo) { 3809 // We can bypass creating a target-independent constant expression and then 3810 // folding it back into a ConstantInt. This is just a compile-time 3811 // optimization. 3812 return getConstant( 3813 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3814 } 3815 3816 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3817 // Don't attempt to do anything other than create a SCEVUnknown object 3818 // here. createSCEV only calls getUnknown after checking for all other 3819 // interesting possibilities, and any other code that calls getUnknown 3820 // is doing so in order to hide a value from SCEV canonicalization. 3821 3822 FoldingSetNodeID ID; 3823 ID.AddInteger(scUnknown); 3824 ID.AddPointer(V); 3825 void *IP = nullptr; 3826 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3827 assert(cast<SCEVUnknown>(S)->getValue() == V && 3828 "Stale SCEVUnknown in uniquing map!"); 3829 return S; 3830 } 3831 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3832 FirstUnknown); 3833 FirstUnknown = cast<SCEVUnknown>(S); 3834 UniqueSCEVs.InsertNode(S, IP); 3835 return S; 3836 } 3837 3838 //===----------------------------------------------------------------------===// 3839 // Basic SCEV Analysis and PHI Idiom Recognition Code 3840 // 3841 3842 /// Test if values of the given type are analyzable within the SCEV 3843 /// framework. This primarily includes integer types, and it can optionally 3844 /// include pointer types if the ScalarEvolution class has access to 3845 /// target-specific information. 3846 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3847 // Integers and pointers are always SCEVable. 3848 return Ty->isIntOrPtrTy(); 3849 } 3850 3851 /// Return the size in bits of the specified type, for which isSCEVable must 3852 /// return true. 3853 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3854 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3855 if (Ty->isPointerTy()) 3856 return getDataLayout().getIndexTypeSizeInBits(Ty); 3857 return getDataLayout().getTypeSizeInBits(Ty); 3858 } 3859 3860 /// Return a type with the same bitwidth as the given type and which represents 3861 /// how SCEV will treat the given type, for which isSCEVable must return 3862 /// true. For pointer types, this is the pointer index sized integer type. 3863 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3864 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3865 3866 if (Ty->isIntegerTy()) 3867 return Ty; 3868 3869 // The only other support type is pointer. 3870 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3871 return getDataLayout().getIndexType(Ty); 3872 } 3873 3874 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3875 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3876 } 3877 3878 const SCEV *ScalarEvolution::getCouldNotCompute() { 3879 return CouldNotCompute.get(); 3880 } 3881 3882 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3883 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3884 auto *SU = dyn_cast<SCEVUnknown>(S); 3885 return SU && SU->getValue() == nullptr; 3886 }); 3887 3888 return !ContainsNulls; 3889 } 3890 3891 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3892 HasRecMapType::iterator I = HasRecMap.find(S); 3893 if (I != HasRecMap.end()) 3894 return I->second; 3895 3896 bool FoundAddRec = 3897 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3898 HasRecMap.insert({S, FoundAddRec}); 3899 return FoundAddRec; 3900 } 3901 3902 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3903 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3904 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3905 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3906 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3907 if (!Add) 3908 return {S, nullptr}; 3909 3910 if (Add->getNumOperands() != 2) 3911 return {S, nullptr}; 3912 3913 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3914 if (!ConstOp) 3915 return {S, nullptr}; 3916 3917 return {Add->getOperand(1), ConstOp->getValue()}; 3918 } 3919 3920 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3921 /// by the value and offset from any ValueOffsetPair in the set. 3922 ScalarEvolution::ValueOffsetPairSetVector * 3923 ScalarEvolution::getSCEVValues(const SCEV *S) { 3924 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3925 if (SI == ExprValueMap.end()) 3926 return nullptr; 3927 #ifndef NDEBUG 3928 if (VerifySCEVMap) { 3929 // Check there is no dangling Value in the set returned. 3930 for (const auto &VE : SI->second) 3931 assert(ValueExprMap.count(VE.first)); 3932 } 3933 #endif 3934 return &SI->second; 3935 } 3936 3937 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3938 /// cannot be used separately. eraseValueFromMap should be used to remove 3939 /// V from ValueExprMap and ExprValueMap at the same time. 3940 void ScalarEvolution::eraseValueFromMap(Value *V) { 3941 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3942 if (I != ValueExprMap.end()) { 3943 const SCEV *S = I->second; 3944 // Remove {V, 0} from the set of ExprValueMap[S] 3945 if (auto *SV = getSCEVValues(S)) 3946 SV->remove({V, nullptr}); 3947 3948 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3949 const SCEV *Stripped; 3950 ConstantInt *Offset; 3951 std::tie(Stripped, Offset) = splitAddExpr(S); 3952 if (Offset != nullptr) { 3953 if (auto *SV = getSCEVValues(Stripped)) 3954 SV->remove({V, Offset}); 3955 } 3956 ValueExprMap.erase(V); 3957 } 3958 } 3959 3960 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3961 /// TODO: In reality it is better to check the poison recursively 3962 /// but this is better than nothing. 3963 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3964 if (auto *I = dyn_cast<Instruction>(V)) { 3965 if (isa<OverflowingBinaryOperator>(I)) { 3966 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3967 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3968 return true; 3969 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3970 return true; 3971 } 3972 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3973 return true; 3974 } 3975 return false; 3976 } 3977 3978 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3979 /// create a new one. 3980 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3981 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3982 3983 const SCEV *S = getExistingSCEV(V); 3984 if (S == nullptr) { 3985 S = createSCEV(V); 3986 // During PHI resolution, it is possible to create two SCEVs for the same 3987 // V, so it is needed to double check whether V->S is inserted into 3988 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3989 std::pair<ValueExprMapType::iterator, bool> Pair = 3990 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3991 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3992 ExprValueMap[S].insert({V, nullptr}); 3993 3994 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3995 // ExprValueMap. 3996 const SCEV *Stripped = S; 3997 ConstantInt *Offset = nullptr; 3998 std::tie(Stripped, Offset) = splitAddExpr(S); 3999 // If stripped is SCEVUnknown, don't bother to save 4000 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 4001 // increase the complexity of the expansion code. 4002 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 4003 // because it may generate add/sub instead of GEP in SCEV expansion. 4004 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 4005 !isa<GetElementPtrInst>(V)) 4006 ExprValueMap[Stripped].insert({V, Offset}); 4007 } 4008 } 4009 return S; 4010 } 4011 4012 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 4013 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4014 4015 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4016 if (I != ValueExprMap.end()) { 4017 const SCEV *S = I->second; 4018 if (checkValidity(S)) 4019 return S; 4020 eraseValueFromMap(V); 4021 forgetMemoizedResults(S); 4022 } 4023 return nullptr; 4024 } 4025 4026 /// Return a SCEV corresponding to -V = -1*V 4027 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4028 SCEV::NoWrapFlags Flags) { 4029 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4030 return getConstant( 4031 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4032 4033 Type *Ty = V->getType(); 4034 Ty = getEffectiveSCEVType(Ty); 4035 return getMulExpr(V, getMinusOne(Ty), Flags); 4036 } 4037 4038 /// If Expr computes ~A, return A else return nullptr 4039 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4040 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4041 if (!Add || Add->getNumOperands() != 2 || 4042 !Add->getOperand(0)->isAllOnesValue()) 4043 return nullptr; 4044 4045 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4046 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4047 !AddRHS->getOperand(0)->isAllOnesValue()) 4048 return nullptr; 4049 4050 return AddRHS->getOperand(1); 4051 } 4052 4053 /// Return a SCEV corresponding to ~V = -1-V 4054 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4055 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4056 return getConstant( 4057 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4058 4059 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4060 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4061 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4062 SmallVector<const SCEV *, 2> MatchedOperands; 4063 for (const SCEV *Operand : MME->operands()) { 4064 const SCEV *Matched = MatchNotExpr(Operand); 4065 if (!Matched) 4066 return (const SCEV *)nullptr; 4067 MatchedOperands.push_back(Matched); 4068 } 4069 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 4070 MatchedOperands); 4071 }; 4072 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4073 return Replaced; 4074 } 4075 4076 Type *Ty = V->getType(); 4077 Ty = getEffectiveSCEVType(Ty); 4078 return getMinusSCEV(getMinusOne(Ty), V); 4079 } 4080 4081 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4082 SCEV::NoWrapFlags Flags, 4083 unsigned Depth) { 4084 // Fast path: X - X --> 0. 4085 if (LHS == RHS) 4086 return getZero(LHS->getType()); 4087 4088 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4089 // makes it so that we cannot make much use of NUW. 4090 auto AddFlags = SCEV::FlagAnyWrap; 4091 const bool RHSIsNotMinSigned = 4092 !getSignedRangeMin(RHS).isMinSignedValue(); 4093 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4094 // Let M be the minimum representable signed value. Then (-1)*RHS 4095 // signed-wraps if and only if RHS is M. That can happen even for 4096 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4097 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4098 // (-1)*RHS, we need to prove that RHS != M. 4099 // 4100 // If LHS is non-negative and we know that LHS - RHS does not 4101 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4102 // either by proving that RHS > M or that LHS >= 0. 4103 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4104 AddFlags = SCEV::FlagNSW; 4105 } 4106 } 4107 4108 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4109 // RHS is NSW and LHS >= 0. 4110 // 4111 // The difficulty here is that the NSW flag may have been proven 4112 // relative to a loop that is to be found in a recurrence in LHS and 4113 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4114 // larger scope than intended. 4115 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4116 4117 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4118 } 4119 4120 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4121 unsigned Depth) { 4122 Type *SrcTy = V->getType(); 4123 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4124 "Cannot truncate or zero extend with non-integer arguments!"); 4125 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4126 return V; // No conversion 4127 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4128 return getTruncateExpr(V, Ty, Depth); 4129 return getZeroExtendExpr(V, Ty, Depth); 4130 } 4131 4132 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4133 unsigned Depth) { 4134 Type *SrcTy = V->getType(); 4135 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4136 "Cannot truncate or zero extend with non-integer arguments!"); 4137 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4138 return V; // No conversion 4139 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4140 return getTruncateExpr(V, Ty, Depth); 4141 return getSignExtendExpr(V, Ty, Depth); 4142 } 4143 4144 const SCEV * 4145 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4146 Type *SrcTy = V->getType(); 4147 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4148 "Cannot noop or zero extend with non-integer arguments!"); 4149 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4150 "getNoopOrZeroExtend cannot truncate!"); 4151 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4152 return V; // No conversion 4153 return getZeroExtendExpr(V, Ty); 4154 } 4155 4156 const SCEV * 4157 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4158 Type *SrcTy = V->getType(); 4159 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4160 "Cannot noop or sign extend with non-integer arguments!"); 4161 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4162 "getNoopOrSignExtend cannot truncate!"); 4163 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4164 return V; // No conversion 4165 return getSignExtendExpr(V, Ty); 4166 } 4167 4168 const SCEV * 4169 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4170 Type *SrcTy = V->getType(); 4171 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4172 "Cannot noop or any extend with non-integer arguments!"); 4173 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4174 "getNoopOrAnyExtend cannot truncate!"); 4175 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4176 return V; // No conversion 4177 return getAnyExtendExpr(V, Ty); 4178 } 4179 4180 const SCEV * 4181 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4182 Type *SrcTy = V->getType(); 4183 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4184 "Cannot truncate or noop with non-integer arguments!"); 4185 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4186 "getTruncateOrNoop cannot extend!"); 4187 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4188 return V; // No conversion 4189 return getTruncateExpr(V, Ty); 4190 } 4191 4192 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4193 const SCEV *RHS) { 4194 const SCEV *PromotedLHS = LHS; 4195 const SCEV *PromotedRHS = RHS; 4196 4197 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4198 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4199 else 4200 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4201 4202 return getUMaxExpr(PromotedLHS, PromotedRHS); 4203 } 4204 4205 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4206 const SCEV *RHS) { 4207 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4208 return getUMinFromMismatchedTypes(Ops); 4209 } 4210 4211 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4212 SmallVectorImpl<const SCEV *> &Ops) { 4213 assert(!Ops.empty() && "At least one operand must be!"); 4214 // Trivial case. 4215 if (Ops.size() == 1) 4216 return Ops[0]; 4217 4218 // Find the max type first. 4219 Type *MaxType = nullptr; 4220 for (auto *S : Ops) 4221 if (MaxType) 4222 MaxType = getWiderType(MaxType, S->getType()); 4223 else 4224 MaxType = S->getType(); 4225 assert(MaxType && "Failed to find maximum type!"); 4226 4227 // Extend all ops to max type. 4228 SmallVector<const SCEV *, 2> PromotedOps; 4229 for (auto *S : Ops) 4230 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4231 4232 // Generate umin. 4233 return getUMinExpr(PromotedOps); 4234 } 4235 4236 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4237 // A pointer operand may evaluate to a nonpointer expression, such as null. 4238 if (!V->getType()->isPointerTy()) 4239 return V; 4240 4241 while (true) { 4242 if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) { 4243 V = Cast->getOperand(); 4244 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4245 const SCEV *PtrOp = nullptr; 4246 for (const SCEV *NAryOp : NAry->operands()) { 4247 if (NAryOp->getType()->isPointerTy()) { 4248 // Cannot find the base of an expression with multiple pointer ops. 4249 if (PtrOp) 4250 return V; 4251 PtrOp = NAryOp; 4252 } 4253 } 4254 if (!PtrOp) // All operands were non-pointer. 4255 return V; 4256 V = PtrOp; 4257 } else // Not something we can look further into. 4258 return V; 4259 } 4260 } 4261 4262 /// Push users of the given Instruction onto the given Worklist. 4263 static void 4264 PushDefUseChildren(Instruction *I, 4265 SmallVectorImpl<Instruction *> &Worklist) { 4266 // Push the def-use children onto the Worklist stack. 4267 for (User *U : I->users()) 4268 Worklist.push_back(cast<Instruction>(U)); 4269 } 4270 4271 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4272 SmallVector<Instruction *, 16> Worklist; 4273 PushDefUseChildren(PN, Worklist); 4274 4275 SmallPtrSet<Instruction *, 8> Visited; 4276 Visited.insert(PN); 4277 while (!Worklist.empty()) { 4278 Instruction *I = Worklist.pop_back_val(); 4279 if (!Visited.insert(I).second) 4280 continue; 4281 4282 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4283 if (It != ValueExprMap.end()) { 4284 const SCEV *Old = It->second; 4285 4286 // Short-circuit the def-use traversal if the symbolic name 4287 // ceases to appear in expressions. 4288 if (Old != SymName && !hasOperand(Old, SymName)) 4289 continue; 4290 4291 // SCEVUnknown for a PHI either means that it has an unrecognized 4292 // structure, it's a PHI that's in the progress of being computed 4293 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4294 // additional loop trip count information isn't going to change anything. 4295 // In the second case, createNodeForPHI will perform the necessary 4296 // updates on its own when it gets to that point. In the third, we do 4297 // want to forget the SCEVUnknown. 4298 if (!isa<PHINode>(I) || 4299 !isa<SCEVUnknown>(Old) || 4300 (I != PN && Old == SymName)) { 4301 eraseValueFromMap(It->first); 4302 forgetMemoizedResults(Old); 4303 } 4304 } 4305 4306 PushDefUseChildren(I, Worklist); 4307 } 4308 } 4309 4310 namespace { 4311 4312 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4313 /// expression in case its Loop is L. If it is not L then 4314 /// if IgnoreOtherLoops is true then use AddRec itself 4315 /// otherwise rewrite cannot be done. 4316 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4317 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4318 public: 4319 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4320 bool IgnoreOtherLoops = true) { 4321 SCEVInitRewriter Rewriter(L, SE); 4322 const SCEV *Result = Rewriter.visit(S); 4323 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4324 return SE.getCouldNotCompute(); 4325 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4326 ? SE.getCouldNotCompute() 4327 : Result; 4328 } 4329 4330 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4331 if (!SE.isLoopInvariant(Expr, L)) 4332 SeenLoopVariantSCEVUnknown = true; 4333 return Expr; 4334 } 4335 4336 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4337 // Only re-write AddRecExprs for this loop. 4338 if (Expr->getLoop() == L) 4339 return Expr->getStart(); 4340 SeenOtherLoops = true; 4341 return Expr; 4342 } 4343 4344 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4345 4346 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4347 4348 private: 4349 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4350 : SCEVRewriteVisitor(SE), L(L) {} 4351 4352 const Loop *L; 4353 bool SeenLoopVariantSCEVUnknown = false; 4354 bool SeenOtherLoops = false; 4355 }; 4356 4357 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4358 /// increment expression in case its Loop is L. If it is not L then 4359 /// use AddRec itself. 4360 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4361 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4362 public: 4363 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4364 SCEVPostIncRewriter Rewriter(L, SE); 4365 const SCEV *Result = Rewriter.visit(S); 4366 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4367 ? SE.getCouldNotCompute() 4368 : Result; 4369 } 4370 4371 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4372 if (!SE.isLoopInvariant(Expr, L)) 4373 SeenLoopVariantSCEVUnknown = true; 4374 return Expr; 4375 } 4376 4377 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4378 // Only re-write AddRecExprs for this loop. 4379 if (Expr->getLoop() == L) 4380 return Expr->getPostIncExpr(SE); 4381 SeenOtherLoops = true; 4382 return Expr; 4383 } 4384 4385 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4386 4387 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4388 4389 private: 4390 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4391 : SCEVRewriteVisitor(SE), L(L) {} 4392 4393 const Loop *L; 4394 bool SeenLoopVariantSCEVUnknown = false; 4395 bool SeenOtherLoops = false; 4396 }; 4397 4398 /// This class evaluates the compare condition by matching it against the 4399 /// condition of loop latch. If there is a match we assume a true value 4400 /// for the condition while building SCEV nodes. 4401 class SCEVBackedgeConditionFolder 4402 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4403 public: 4404 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4405 ScalarEvolution &SE) { 4406 bool IsPosBECond = false; 4407 Value *BECond = nullptr; 4408 if (BasicBlock *Latch = L->getLoopLatch()) { 4409 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4410 if (BI && BI->isConditional()) { 4411 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4412 "Both outgoing branches should not target same header!"); 4413 BECond = BI->getCondition(); 4414 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4415 } else { 4416 return S; 4417 } 4418 } 4419 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4420 return Rewriter.visit(S); 4421 } 4422 4423 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4424 const SCEV *Result = Expr; 4425 bool InvariantF = SE.isLoopInvariant(Expr, L); 4426 4427 if (!InvariantF) { 4428 Instruction *I = cast<Instruction>(Expr->getValue()); 4429 switch (I->getOpcode()) { 4430 case Instruction::Select: { 4431 SelectInst *SI = cast<SelectInst>(I); 4432 Optional<const SCEV *> Res = 4433 compareWithBackedgeCondition(SI->getCondition()); 4434 if (Res.hasValue()) { 4435 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4436 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4437 } 4438 break; 4439 } 4440 default: { 4441 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4442 if (Res.hasValue()) 4443 Result = Res.getValue(); 4444 break; 4445 } 4446 } 4447 } 4448 return Result; 4449 } 4450 4451 private: 4452 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4453 bool IsPosBECond, ScalarEvolution &SE) 4454 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4455 IsPositiveBECond(IsPosBECond) {} 4456 4457 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4458 4459 const Loop *L; 4460 /// Loop back condition. 4461 Value *BackedgeCond = nullptr; 4462 /// Set to true if loop back is on positive branch condition. 4463 bool IsPositiveBECond; 4464 }; 4465 4466 Optional<const SCEV *> 4467 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4468 4469 // If value matches the backedge condition for loop latch, 4470 // then return a constant evolution node based on loopback 4471 // branch taken. 4472 if (BackedgeCond == IC) 4473 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4474 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4475 return None; 4476 } 4477 4478 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4479 public: 4480 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4481 ScalarEvolution &SE) { 4482 SCEVShiftRewriter Rewriter(L, SE); 4483 const SCEV *Result = Rewriter.visit(S); 4484 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4485 } 4486 4487 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4488 // Only allow AddRecExprs for this loop. 4489 if (!SE.isLoopInvariant(Expr, L)) 4490 Valid = false; 4491 return Expr; 4492 } 4493 4494 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4495 if (Expr->getLoop() == L && Expr->isAffine()) 4496 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4497 Valid = false; 4498 return Expr; 4499 } 4500 4501 bool isValid() { return Valid; } 4502 4503 private: 4504 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4505 : SCEVRewriteVisitor(SE), L(L) {} 4506 4507 const Loop *L; 4508 bool Valid = true; 4509 }; 4510 4511 } // end anonymous namespace 4512 4513 SCEV::NoWrapFlags 4514 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4515 if (!AR->isAffine()) 4516 return SCEV::FlagAnyWrap; 4517 4518 using OBO = OverflowingBinaryOperator; 4519 4520 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4521 4522 if (!AR->hasNoSignedWrap()) { 4523 ConstantRange AddRecRange = getSignedRange(AR); 4524 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4525 4526 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4527 Instruction::Add, IncRange, OBO::NoSignedWrap); 4528 if (NSWRegion.contains(AddRecRange)) 4529 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4530 } 4531 4532 if (!AR->hasNoUnsignedWrap()) { 4533 ConstantRange AddRecRange = getUnsignedRange(AR); 4534 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4535 4536 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4537 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4538 if (NUWRegion.contains(AddRecRange)) 4539 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4540 } 4541 4542 return Result; 4543 } 4544 4545 SCEV::NoWrapFlags 4546 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4547 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4548 4549 if (AR->hasNoSignedWrap()) 4550 return Result; 4551 4552 if (!AR->isAffine()) 4553 return Result; 4554 4555 const SCEV *Step = AR->getStepRecurrence(*this); 4556 const Loop *L = AR->getLoop(); 4557 4558 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4559 // Note that this serves two purposes: It filters out loops that are 4560 // simply not analyzable, and it covers the case where this code is 4561 // being called from within backedge-taken count analysis, such that 4562 // attempting to ask for the backedge-taken count would likely result 4563 // in infinite recursion. In the later case, the analysis code will 4564 // cope with a conservative value, and it will take care to purge 4565 // that value once it has finished. 4566 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4567 4568 // Normally, in the cases we can prove no-overflow via a 4569 // backedge guarding condition, we can also compute a backedge 4570 // taken count for the loop. The exceptions are assumptions and 4571 // guards present in the loop -- SCEV is not great at exploiting 4572 // these to compute max backedge taken counts, but can still use 4573 // these to prove lack of overflow. Use this fact to avoid 4574 // doing extra work that may not pay off. 4575 4576 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4577 AC.assumptions().empty()) 4578 return Result; 4579 4580 // If the backedge is guarded by a comparison with the pre-inc value the 4581 // addrec is safe. Also, if the entry is guarded by a comparison with the 4582 // start value and the backedge is guarded by a comparison with the post-inc 4583 // value, the addrec is safe. 4584 ICmpInst::Predicate Pred; 4585 const SCEV *OverflowLimit = 4586 getSignedOverflowLimitForStep(Step, &Pred, this); 4587 if (OverflowLimit && 4588 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4589 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4590 Result = setFlags(Result, SCEV::FlagNSW); 4591 } 4592 return Result; 4593 } 4594 SCEV::NoWrapFlags 4595 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4596 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4597 4598 if (AR->hasNoUnsignedWrap()) 4599 return Result; 4600 4601 if (!AR->isAffine()) 4602 return Result; 4603 4604 const SCEV *Step = AR->getStepRecurrence(*this); 4605 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4606 const Loop *L = AR->getLoop(); 4607 4608 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4609 // Note that this serves two purposes: It filters out loops that are 4610 // simply not analyzable, and it covers the case where this code is 4611 // being called from within backedge-taken count analysis, such that 4612 // attempting to ask for the backedge-taken count would likely result 4613 // in infinite recursion. In the later case, the analysis code will 4614 // cope with a conservative value, and it will take care to purge 4615 // that value once it has finished. 4616 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4617 4618 // Normally, in the cases we can prove no-overflow via a 4619 // backedge guarding condition, we can also compute a backedge 4620 // taken count for the loop. The exceptions are assumptions and 4621 // guards present in the loop -- SCEV is not great at exploiting 4622 // these to compute max backedge taken counts, but can still use 4623 // these to prove lack of overflow. Use this fact to avoid 4624 // doing extra work that may not pay off. 4625 4626 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4627 AC.assumptions().empty()) 4628 return Result; 4629 4630 // If the backedge is guarded by a comparison with the pre-inc value the 4631 // addrec is safe. Also, if the entry is guarded by a comparison with the 4632 // start value and the backedge is guarded by a comparison with the post-inc 4633 // value, the addrec is safe. 4634 if (isKnownPositive(Step)) { 4635 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 4636 getUnsignedRangeMax(Step)); 4637 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 4638 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 4639 Result = setFlags(Result, SCEV::FlagNUW); 4640 } 4641 } 4642 4643 return Result; 4644 } 4645 4646 namespace { 4647 4648 /// Represents an abstract binary operation. This may exist as a 4649 /// normal instruction or constant expression, or may have been 4650 /// derived from an expression tree. 4651 struct BinaryOp { 4652 unsigned Opcode; 4653 Value *LHS; 4654 Value *RHS; 4655 bool IsNSW = false; 4656 bool IsNUW = false; 4657 4658 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4659 /// constant expression. 4660 Operator *Op = nullptr; 4661 4662 explicit BinaryOp(Operator *Op) 4663 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4664 Op(Op) { 4665 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4666 IsNSW = OBO->hasNoSignedWrap(); 4667 IsNUW = OBO->hasNoUnsignedWrap(); 4668 } 4669 } 4670 4671 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4672 bool IsNUW = false) 4673 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4674 }; 4675 4676 } // end anonymous namespace 4677 4678 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4679 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4680 auto *Op = dyn_cast<Operator>(V); 4681 if (!Op) 4682 return None; 4683 4684 // Implementation detail: all the cleverness here should happen without 4685 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4686 // SCEV expressions when possible, and we should not break that. 4687 4688 switch (Op->getOpcode()) { 4689 case Instruction::Add: 4690 case Instruction::Sub: 4691 case Instruction::Mul: 4692 case Instruction::UDiv: 4693 case Instruction::URem: 4694 case Instruction::And: 4695 case Instruction::Or: 4696 case Instruction::AShr: 4697 case Instruction::Shl: 4698 return BinaryOp(Op); 4699 4700 case Instruction::Xor: 4701 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4702 // If the RHS of the xor is a signmask, then this is just an add. 4703 // Instcombine turns add of signmask into xor as a strength reduction step. 4704 if (RHSC->getValue().isSignMask()) 4705 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4706 return BinaryOp(Op); 4707 4708 case Instruction::LShr: 4709 // Turn logical shift right of a constant into a unsigned divide. 4710 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4711 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4712 4713 // If the shift count is not less than the bitwidth, the result of 4714 // the shift is undefined. Don't try to analyze it, because the 4715 // resolution chosen here may differ from the resolution chosen in 4716 // other parts of the compiler. 4717 if (SA->getValue().ult(BitWidth)) { 4718 Constant *X = 4719 ConstantInt::get(SA->getContext(), 4720 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4721 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4722 } 4723 } 4724 return BinaryOp(Op); 4725 4726 case Instruction::ExtractValue: { 4727 auto *EVI = cast<ExtractValueInst>(Op); 4728 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4729 break; 4730 4731 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4732 if (!WO) 4733 break; 4734 4735 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4736 bool Signed = WO->isSigned(); 4737 // TODO: Should add nuw/nsw flags for mul as well. 4738 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4739 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4740 4741 // Now that we know that all uses of the arithmetic-result component of 4742 // CI are guarded by the overflow check, we can go ahead and pretend 4743 // that the arithmetic is non-overflowing. 4744 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4745 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4746 } 4747 4748 default: 4749 break; 4750 } 4751 4752 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4753 // semantics as a Sub, return a binary sub expression. 4754 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4755 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4756 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4757 4758 return None; 4759 } 4760 4761 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4762 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4763 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4764 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4765 /// follows one of the following patterns: 4766 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4767 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4768 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4769 /// we return the type of the truncation operation, and indicate whether the 4770 /// truncated type should be treated as signed/unsigned by setting 4771 /// \p Signed to true/false, respectively. 4772 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4773 bool &Signed, ScalarEvolution &SE) { 4774 // The case where Op == SymbolicPHI (that is, with no type conversions on 4775 // the way) is handled by the regular add recurrence creating logic and 4776 // would have already been triggered in createAddRecForPHI. Reaching it here 4777 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4778 // because one of the other operands of the SCEVAddExpr updating this PHI is 4779 // not invariant). 4780 // 4781 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4782 // this case predicates that allow us to prove that Op == SymbolicPHI will 4783 // be added. 4784 if (Op == SymbolicPHI) 4785 return nullptr; 4786 4787 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4788 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4789 if (SourceBits != NewBits) 4790 return nullptr; 4791 4792 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4793 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4794 if (!SExt && !ZExt) 4795 return nullptr; 4796 const SCEVTruncateExpr *Trunc = 4797 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4798 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4799 if (!Trunc) 4800 return nullptr; 4801 const SCEV *X = Trunc->getOperand(); 4802 if (X != SymbolicPHI) 4803 return nullptr; 4804 Signed = SExt != nullptr; 4805 return Trunc->getType(); 4806 } 4807 4808 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4809 if (!PN->getType()->isIntegerTy()) 4810 return nullptr; 4811 const Loop *L = LI.getLoopFor(PN->getParent()); 4812 if (!L || L->getHeader() != PN->getParent()) 4813 return nullptr; 4814 return L; 4815 } 4816 4817 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4818 // computation that updates the phi follows the following pattern: 4819 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4820 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4821 // If so, try to see if it can be rewritten as an AddRecExpr under some 4822 // Predicates. If successful, return them as a pair. Also cache the results 4823 // of the analysis. 4824 // 4825 // Example usage scenario: 4826 // Say the Rewriter is called for the following SCEV: 4827 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4828 // where: 4829 // %X = phi i64 (%Start, %BEValue) 4830 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4831 // and call this function with %SymbolicPHI = %X. 4832 // 4833 // The analysis will find that the value coming around the backedge has 4834 // the following SCEV: 4835 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4836 // Upon concluding that this matches the desired pattern, the function 4837 // will return the pair {NewAddRec, SmallPredsVec} where: 4838 // NewAddRec = {%Start,+,%Step} 4839 // SmallPredsVec = {P1, P2, P3} as follows: 4840 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4841 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4842 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4843 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4844 // under the predicates {P1,P2,P3}. 4845 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4846 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4847 // 4848 // TODO's: 4849 // 4850 // 1) Extend the Induction descriptor to also support inductions that involve 4851 // casts: When needed (namely, when we are called in the context of the 4852 // vectorizer induction analysis), a Set of cast instructions will be 4853 // populated by this method, and provided back to isInductionPHI. This is 4854 // needed to allow the vectorizer to properly record them to be ignored by 4855 // the cost model and to avoid vectorizing them (otherwise these casts, 4856 // which are redundant under the runtime overflow checks, will be 4857 // vectorized, which can be costly). 4858 // 4859 // 2) Support additional induction/PHISCEV patterns: We also want to support 4860 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4861 // after the induction update operation (the induction increment): 4862 // 4863 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4864 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4865 // 4866 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4867 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4868 // 4869 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4870 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4871 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4872 SmallVector<const SCEVPredicate *, 3> Predicates; 4873 4874 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4875 // return an AddRec expression under some predicate. 4876 4877 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4878 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4879 assert(L && "Expecting an integer loop header phi"); 4880 4881 // The loop may have multiple entrances or multiple exits; we can analyze 4882 // this phi as an addrec if it has a unique entry value and a unique 4883 // backedge value. 4884 Value *BEValueV = nullptr, *StartValueV = nullptr; 4885 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4886 Value *V = PN->getIncomingValue(i); 4887 if (L->contains(PN->getIncomingBlock(i))) { 4888 if (!BEValueV) { 4889 BEValueV = V; 4890 } else if (BEValueV != V) { 4891 BEValueV = nullptr; 4892 break; 4893 } 4894 } else if (!StartValueV) { 4895 StartValueV = V; 4896 } else if (StartValueV != V) { 4897 StartValueV = nullptr; 4898 break; 4899 } 4900 } 4901 if (!BEValueV || !StartValueV) 4902 return None; 4903 4904 const SCEV *BEValue = getSCEV(BEValueV); 4905 4906 // If the value coming around the backedge is an add with the symbolic 4907 // value we just inserted, possibly with casts that we can ignore under 4908 // an appropriate runtime guard, then we found a simple induction variable! 4909 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4910 if (!Add) 4911 return None; 4912 4913 // If there is a single occurrence of the symbolic value, possibly 4914 // casted, replace it with a recurrence. 4915 unsigned FoundIndex = Add->getNumOperands(); 4916 Type *TruncTy = nullptr; 4917 bool Signed; 4918 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4919 if ((TruncTy = 4920 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4921 if (FoundIndex == e) { 4922 FoundIndex = i; 4923 break; 4924 } 4925 4926 if (FoundIndex == Add->getNumOperands()) 4927 return None; 4928 4929 // Create an add with everything but the specified operand. 4930 SmallVector<const SCEV *, 8> Ops; 4931 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4932 if (i != FoundIndex) 4933 Ops.push_back(Add->getOperand(i)); 4934 const SCEV *Accum = getAddExpr(Ops); 4935 4936 // The runtime checks will not be valid if the step amount is 4937 // varying inside the loop. 4938 if (!isLoopInvariant(Accum, L)) 4939 return None; 4940 4941 // *** Part2: Create the predicates 4942 4943 // Analysis was successful: we have a phi-with-cast pattern for which we 4944 // can return an AddRec expression under the following predicates: 4945 // 4946 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4947 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4948 // P2: An Equal predicate that guarantees that 4949 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4950 // P3: An Equal predicate that guarantees that 4951 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4952 // 4953 // As we next prove, the above predicates guarantee that: 4954 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4955 // 4956 // 4957 // More formally, we want to prove that: 4958 // Expr(i+1) = Start + (i+1) * Accum 4959 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4960 // 4961 // Given that: 4962 // 1) Expr(0) = Start 4963 // 2) Expr(1) = Start + Accum 4964 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4965 // 3) Induction hypothesis (step i): 4966 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4967 // 4968 // Proof: 4969 // Expr(i+1) = 4970 // = Start + (i+1)*Accum 4971 // = (Start + i*Accum) + Accum 4972 // = Expr(i) + Accum 4973 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4974 // :: from step i 4975 // 4976 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4977 // 4978 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4979 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4980 // + Accum :: from P3 4981 // 4982 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4983 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4984 // 4985 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4986 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4987 // 4988 // By induction, the same applies to all iterations 1<=i<n: 4989 // 4990 4991 // Create a truncated addrec for which we will add a no overflow check (P1). 4992 const SCEV *StartVal = getSCEV(StartValueV); 4993 const SCEV *PHISCEV = 4994 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4995 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4996 4997 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4998 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4999 // will be constant. 5000 // 5001 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 5002 // add P1. 5003 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 5004 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 5005 Signed ? SCEVWrapPredicate::IncrementNSSW 5006 : SCEVWrapPredicate::IncrementNUSW; 5007 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 5008 Predicates.push_back(AddRecPred); 5009 } 5010 5011 // Create the Equal Predicates P2,P3: 5012 5013 // It is possible that the predicates P2 and/or P3 are computable at 5014 // compile time due to StartVal and/or Accum being constants. 5015 // If either one is, then we can check that now and escape if either P2 5016 // or P3 is false. 5017 5018 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 5019 // for each of StartVal and Accum 5020 auto getExtendedExpr = [&](const SCEV *Expr, 5021 bool CreateSignExtend) -> const SCEV * { 5022 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 5023 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 5024 const SCEV *ExtendedExpr = 5025 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 5026 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 5027 return ExtendedExpr; 5028 }; 5029 5030 // Given: 5031 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 5032 // = getExtendedExpr(Expr) 5033 // Determine whether the predicate P: Expr == ExtendedExpr 5034 // is known to be false at compile time 5035 auto PredIsKnownFalse = [&](const SCEV *Expr, 5036 const SCEV *ExtendedExpr) -> bool { 5037 return Expr != ExtendedExpr && 5038 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 5039 }; 5040 5041 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 5042 if (PredIsKnownFalse(StartVal, StartExtended)) { 5043 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 5044 return None; 5045 } 5046 5047 // The Step is always Signed (because the overflow checks are either 5048 // NSSW or NUSW) 5049 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 5050 if (PredIsKnownFalse(Accum, AccumExtended)) { 5051 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 5052 return None; 5053 } 5054 5055 auto AppendPredicate = [&](const SCEV *Expr, 5056 const SCEV *ExtendedExpr) -> void { 5057 if (Expr != ExtendedExpr && 5058 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 5059 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 5060 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 5061 Predicates.push_back(Pred); 5062 } 5063 }; 5064 5065 AppendPredicate(StartVal, StartExtended); 5066 AppendPredicate(Accum, AccumExtended); 5067 5068 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 5069 // which the casts had been folded away. The caller can rewrite SymbolicPHI 5070 // into NewAR if it will also add the runtime overflow checks specified in 5071 // Predicates. 5072 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 5073 5074 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 5075 std::make_pair(NewAR, Predicates); 5076 // Remember the result of the analysis for this SCEV at this locayyytion. 5077 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 5078 return PredRewrite; 5079 } 5080 5081 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5082 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5083 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5084 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5085 if (!L) 5086 return None; 5087 5088 // Check to see if we already analyzed this PHI. 5089 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5090 if (I != PredicatedSCEVRewrites.end()) { 5091 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5092 I->second; 5093 // Analysis was done before and failed to create an AddRec: 5094 if (Rewrite.first == SymbolicPHI) 5095 return None; 5096 // Analysis was done before and succeeded to create an AddRec under 5097 // a predicate: 5098 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5099 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5100 return Rewrite; 5101 } 5102 5103 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5104 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5105 5106 // Record in the cache that the analysis failed 5107 if (!Rewrite) { 5108 SmallVector<const SCEVPredicate *, 3> Predicates; 5109 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5110 return None; 5111 } 5112 5113 return Rewrite; 5114 } 5115 5116 // FIXME: This utility is currently required because the Rewriter currently 5117 // does not rewrite this expression: 5118 // {0, +, (sext ix (trunc iy to ix) to iy)} 5119 // into {0, +, %step}, 5120 // even when the following Equal predicate exists: 5121 // "%step == (sext ix (trunc iy to ix) to iy)". 5122 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5123 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5124 if (AR1 == AR2) 5125 return true; 5126 5127 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5128 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 5129 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 5130 return false; 5131 return true; 5132 }; 5133 5134 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5135 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5136 return false; 5137 return true; 5138 } 5139 5140 /// A helper function for createAddRecFromPHI to handle simple cases. 5141 /// 5142 /// This function tries to find an AddRec expression for the simplest (yet most 5143 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5144 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5145 /// technique for finding the AddRec expression. 5146 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5147 Value *BEValueV, 5148 Value *StartValueV) { 5149 const Loop *L = LI.getLoopFor(PN->getParent()); 5150 assert(L && L->getHeader() == PN->getParent()); 5151 assert(BEValueV && StartValueV); 5152 5153 auto BO = MatchBinaryOp(BEValueV, DT); 5154 if (!BO) 5155 return nullptr; 5156 5157 if (BO->Opcode != Instruction::Add) 5158 return nullptr; 5159 5160 const SCEV *Accum = nullptr; 5161 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5162 Accum = getSCEV(BO->RHS); 5163 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5164 Accum = getSCEV(BO->LHS); 5165 5166 if (!Accum) 5167 return nullptr; 5168 5169 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5170 if (BO->IsNUW) 5171 Flags = setFlags(Flags, SCEV::FlagNUW); 5172 if (BO->IsNSW) 5173 Flags = setFlags(Flags, SCEV::FlagNSW); 5174 5175 const SCEV *StartVal = getSCEV(StartValueV); 5176 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5177 5178 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5179 5180 // We can add Flags to the post-inc expression only if we 5181 // know that it is *undefined behavior* for BEValueV to 5182 // overflow. 5183 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5184 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5185 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5186 5187 return PHISCEV; 5188 } 5189 5190 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5191 const Loop *L = LI.getLoopFor(PN->getParent()); 5192 if (!L || L->getHeader() != PN->getParent()) 5193 return nullptr; 5194 5195 // The loop may have multiple entrances or multiple exits; we can analyze 5196 // this phi as an addrec if it has a unique entry value and a unique 5197 // backedge value. 5198 Value *BEValueV = nullptr, *StartValueV = nullptr; 5199 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5200 Value *V = PN->getIncomingValue(i); 5201 if (L->contains(PN->getIncomingBlock(i))) { 5202 if (!BEValueV) { 5203 BEValueV = V; 5204 } else if (BEValueV != V) { 5205 BEValueV = nullptr; 5206 break; 5207 } 5208 } else if (!StartValueV) { 5209 StartValueV = V; 5210 } else if (StartValueV != V) { 5211 StartValueV = nullptr; 5212 break; 5213 } 5214 } 5215 if (!BEValueV || !StartValueV) 5216 return nullptr; 5217 5218 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5219 "PHI node already processed?"); 5220 5221 // First, try to find AddRec expression without creating a fictituos symbolic 5222 // value for PN. 5223 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5224 return S; 5225 5226 // Handle PHI node value symbolically. 5227 const SCEV *SymbolicName = getUnknown(PN); 5228 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5229 5230 // Using this symbolic name for the PHI, analyze the value coming around 5231 // the back-edge. 5232 const SCEV *BEValue = getSCEV(BEValueV); 5233 5234 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5235 // has a special value for the first iteration of the loop. 5236 5237 // If the value coming around the backedge is an add with the symbolic 5238 // value we just inserted, then we found a simple induction variable! 5239 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5240 // If there is a single occurrence of the symbolic value, replace it 5241 // with a recurrence. 5242 unsigned FoundIndex = Add->getNumOperands(); 5243 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5244 if (Add->getOperand(i) == SymbolicName) 5245 if (FoundIndex == e) { 5246 FoundIndex = i; 5247 break; 5248 } 5249 5250 if (FoundIndex != Add->getNumOperands()) { 5251 // Create an add with everything but the specified operand. 5252 SmallVector<const SCEV *, 8> Ops; 5253 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5254 if (i != FoundIndex) 5255 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5256 L, *this)); 5257 const SCEV *Accum = getAddExpr(Ops); 5258 5259 // This is not a valid addrec if the step amount is varying each 5260 // loop iteration, but is not itself an addrec in this loop. 5261 if (isLoopInvariant(Accum, L) || 5262 (isa<SCEVAddRecExpr>(Accum) && 5263 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5264 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5265 5266 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5267 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5268 if (BO->IsNUW) 5269 Flags = setFlags(Flags, SCEV::FlagNUW); 5270 if (BO->IsNSW) 5271 Flags = setFlags(Flags, SCEV::FlagNSW); 5272 } 5273 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5274 // If the increment is an inbounds GEP, then we know the address 5275 // space cannot be wrapped around. We cannot make any guarantee 5276 // about signed or unsigned overflow because pointers are 5277 // unsigned but we may have a negative index from the base 5278 // pointer. We can guarantee that no unsigned wrap occurs if the 5279 // indices form a positive value. 5280 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5281 Flags = setFlags(Flags, SCEV::FlagNW); 5282 5283 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5284 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5285 Flags = setFlags(Flags, SCEV::FlagNUW); 5286 } 5287 5288 // We cannot transfer nuw and nsw flags from subtraction 5289 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5290 // for instance. 5291 } 5292 5293 const SCEV *StartVal = getSCEV(StartValueV); 5294 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5295 5296 // Okay, for the entire analysis of this edge we assumed the PHI 5297 // to be symbolic. We now need to go back and purge all of the 5298 // entries for the scalars that use the symbolic expression. 5299 forgetSymbolicName(PN, SymbolicName); 5300 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5301 5302 // We can add Flags to the post-inc expression only if we 5303 // know that it is *undefined behavior* for BEValueV to 5304 // overflow. 5305 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5306 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5307 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5308 5309 return PHISCEV; 5310 } 5311 } 5312 } else { 5313 // Otherwise, this could be a loop like this: 5314 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5315 // In this case, j = {1,+,1} and BEValue is j. 5316 // Because the other in-value of i (0) fits the evolution of BEValue 5317 // i really is an addrec evolution. 5318 // 5319 // We can generalize this saying that i is the shifted value of BEValue 5320 // by one iteration: 5321 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5322 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5323 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5324 if (Shifted != getCouldNotCompute() && 5325 Start != getCouldNotCompute()) { 5326 const SCEV *StartVal = getSCEV(StartValueV); 5327 if (Start == StartVal) { 5328 // Okay, for the entire analysis of this edge we assumed the PHI 5329 // to be symbolic. We now need to go back and purge all of the 5330 // entries for the scalars that use the symbolic expression. 5331 forgetSymbolicName(PN, SymbolicName); 5332 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5333 return Shifted; 5334 } 5335 } 5336 } 5337 5338 // Remove the temporary PHI node SCEV that has been inserted while intending 5339 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5340 // as it will prevent later (possibly simpler) SCEV expressions to be added 5341 // to the ValueExprMap. 5342 eraseValueFromMap(PN); 5343 5344 return nullptr; 5345 } 5346 5347 // Checks if the SCEV S is available at BB. S is considered available at BB 5348 // if S can be materialized at BB without introducing a fault. 5349 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5350 BasicBlock *BB) { 5351 struct CheckAvailable { 5352 bool TraversalDone = false; 5353 bool Available = true; 5354 5355 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5356 BasicBlock *BB = nullptr; 5357 DominatorTree &DT; 5358 5359 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5360 : L(L), BB(BB), DT(DT) {} 5361 5362 bool setUnavailable() { 5363 TraversalDone = true; 5364 Available = false; 5365 return false; 5366 } 5367 5368 bool follow(const SCEV *S) { 5369 switch (S->getSCEVType()) { 5370 case scConstant: 5371 case scPtrToInt: 5372 case scTruncate: 5373 case scZeroExtend: 5374 case scSignExtend: 5375 case scAddExpr: 5376 case scMulExpr: 5377 case scUMaxExpr: 5378 case scSMaxExpr: 5379 case scUMinExpr: 5380 case scSMinExpr: 5381 // These expressions are available if their operand(s) is/are. 5382 return true; 5383 5384 case scAddRecExpr: { 5385 // We allow add recurrences that are on the loop BB is in, or some 5386 // outer loop. This guarantees availability because the value of the 5387 // add recurrence at BB is simply the "current" value of the induction 5388 // variable. We can relax this in the future; for instance an add 5389 // recurrence on a sibling dominating loop is also available at BB. 5390 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5391 if (L && (ARLoop == L || ARLoop->contains(L))) 5392 return true; 5393 5394 return setUnavailable(); 5395 } 5396 5397 case scUnknown: { 5398 // For SCEVUnknown, we check for simple dominance. 5399 const auto *SU = cast<SCEVUnknown>(S); 5400 Value *V = SU->getValue(); 5401 5402 if (isa<Argument>(V)) 5403 return false; 5404 5405 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5406 return false; 5407 5408 return setUnavailable(); 5409 } 5410 5411 case scUDivExpr: 5412 case scCouldNotCompute: 5413 // We do not try to smart about these at all. 5414 return setUnavailable(); 5415 } 5416 llvm_unreachable("Unknown SCEV kind!"); 5417 } 5418 5419 bool isDone() { return TraversalDone; } 5420 }; 5421 5422 CheckAvailable CA(L, BB, DT); 5423 SCEVTraversal<CheckAvailable> ST(CA); 5424 5425 ST.visitAll(S); 5426 return CA.Available; 5427 } 5428 5429 // Try to match a control flow sequence that branches out at BI and merges back 5430 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5431 // match. 5432 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5433 Value *&C, Value *&LHS, Value *&RHS) { 5434 C = BI->getCondition(); 5435 5436 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5437 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5438 5439 if (!LeftEdge.isSingleEdge()) 5440 return false; 5441 5442 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5443 5444 Use &LeftUse = Merge->getOperandUse(0); 5445 Use &RightUse = Merge->getOperandUse(1); 5446 5447 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5448 LHS = LeftUse; 5449 RHS = RightUse; 5450 return true; 5451 } 5452 5453 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5454 LHS = RightUse; 5455 RHS = LeftUse; 5456 return true; 5457 } 5458 5459 return false; 5460 } 5461 5462 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5463 auto IsReachable = 5464 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5465 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5466 const Loop *L = LI.getLoopFor(PN->getParent()); 5467 5468 // We don't want to break LCSSA, even in a SCEV expression tree. 5469 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5470 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5471 return nullptr; 5472 5473 // Try to match 5474 // 5475 // br %cond, label %left, label %right 5476 // left: 5477 // br label %merge 5478 // right: 5479 // br label %merge 5480 // merge: 5481 // V = phi [ %x, %left ], [ %y, %right ] 5482 // 5483 // as "select %cond, %x, %y" 5484 5485 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5486 assert(IDom && "At least the entry block should dominate PN"); 5487 5488 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5489 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5490 5491 if (BI && BI->isConditional() && 5492 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5493 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5494 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5495 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5496 } 5497 5498 return nullptr; 5499 } 5500 5501 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5502 if (const SCEV *S = createAddRecFromPHI(PN)) 5503 return S; 5504 5505 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5506 return S; 5507 5508 // If the PHI has a single incoming value, follow that value, unless the 5509 // PHI's incoming blocks are in a different loop, in which case doing so 5510 // risks breaking LCSSA form. Instcombine would normally zap these, but 5511 // it doesn't have DominatorTree information, so it may miss cases. 5512 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5513 if (LI.replacementPreservesLCSSAForm(PN, V)) 5514 return getSCEV(V); 5515 5516 // If it's not a loop phi, we can't handle it yet. 5517 return getUnknown(PN); 5518 } 5519 5520 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5521 Value *Cond, 5522 Value *TrueVal, 5523 Value *FalseVal) { 5524 // Handle "constant" branch or select. This can occur for instance when a 5525 // loop pass transforms an inner loop and moves on to process the outer loop. 5526 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5527 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5528 5529 // Try to match some simple smax or umax patterns. 5530 auto *ICI = dyn_cast<ICmpInst>(Cond); 5531 if (!ICI) 5532 return getUnknown(I); 5533 5534 Value *LHS = ICI->getOperand(0); 5535 Value *RHS = ICI->getOperand(1); 5536 5537 switch (ICI->getPredicate()) { 5538 case ICmpInst::ICMP_SLT: 5539 case ICmpInst::ICMP_SLE: 5540 std::swap(LHS, RHS); 5541 LLVM_FALLTHROUGH; 5542 case ICmpInst::ICMP_SGT: 5543 case ICmpInst::ICMP_SGE: 5544 // a >s b ? a+x : b+x -> smax(a, b)+x 5545 // a >s b ? b+x : a+x -> smin(a, b)+x 5546 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5547 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5548 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5549 const SCEV *LA = getSCEV(TrueVal); 5550 const SCEV *RA = getSCEV(FalseVal); 5551 const SCEV *LDiff = getMinusSCEV(LA, LS); 5552 const SCEV *RDiff = getMinusSCEV(RA, RS); 5553 if (LDiff == RDiff) 5554 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5555 LDiff = getMinusSCEV(LA, RS); 5556 RDiff = getMinusSCEV(RA, LS); 5557 if (LDiff == RDiff) 5558 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5559 } 5560 break; 5561 case ICmpInst::ICMP_ULT: 5562 case ICmpInst::ICMP_ULE: 5563 std::swap(LHS, RHS); 5564 LLVM_FALLTHROUGH; 5565 case ICmpInst::ICMP_UGT: 5566 case ICmpInst::ICMP_UGE: 5567 // a >u b ? a+x : b+x -> umax(a, b)+x 5568 // a >u b ? b+x : a+x -> umin(a, b)+x 5569 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5570 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5571 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5572 const SCEV *LA = getSCEV(TrueVal); 5573 const SCEV *RA = getSCEV(FalseVal); 5574 const SCEV *LDiff = getMinusSCEV(LA, LS); 5575 const SCEV *RDiff = getMinusSCEV(RA, RS); 5576 if (LDiff == RDiff) 5577 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5578 LDiff = getMinusSCEV(LA, RS); 5579 RDiff = getMinusSCEV(RA, LS); 5580 if (LDiff == RDiff) 5581 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5582 } 5583 break; 5584 case ICmpInst::ICMP_NE: 5585 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5586 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5587 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5588 const SCEV *One = getOne(I->getType()); 5589 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5590 const SCEV *LA = getSCEV(TrueVal); 5591 const SCEV *RA = getSCEV(FalseVal); 5592 const SCEV *LDiff = getMinusSCEV(LA, LS); 5593 const SCEV *RDiff = getMinusSCEV(RA, One); 5594 if (LDiff == RDiff) 5595 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5596 } 5597 break; 5598 case ICmpInst::ICMP_EQ: 5599 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5600 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5601 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5602 const SCEV *One = getOne(I->getType()); 5603 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5604 const SCEV *LA = getSCEV(TrueVal); 5605 const SCEV *RA = getSCEV(FalseVal); 5606 const SCEV *LDiff = getMinusSCEV(LA, One); 5607 const SCEV *RDiff = getMinusSCEV(RA, LS); 5608 if (LDiff == RDiff) 5609 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5610 } 5611 break; 5612 default: 5613 break; 5614 } 5615 5616 return getUnknown(I); 5617 } 5618 5619 /// Expand GEP instructions into add and multiply operations. This allows them 5620 /// to be analyzed by regular SCEV code. 5621 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5622 // Don't attempt to analyze GEPs over unsized objects. 5623 if (!GEP->getSourceElementType()->isSized()) 5624 return getUnknown(GEP); 5625 5626 SmallVector<const SCEV *, 4> IndexExprs; 5627 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5628 IndexExprs.push_back(getSCEV(*Index)); 5629 return getGEPExpr(GEP, IndexExprs); 5630 } 5631 5632 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5633 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5634 return C->getAPInt().countTrailingZeros(); 5635 5636 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5637 return GetMinTrailingZeros(I->getOperand()); 5638 5639 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5640 return std::min(GetMinTrailingZeros(T->getOperand()), 5641 (uint32_t)getTypeSizeInBits(T->getType())); 5642 5643 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5644 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5645 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5646 ? getTypeSizeInBits(E->getType()) 5647 : OpRes; 5648 } 5649 5650 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5651 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5652 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5653 ? getTypeSizeInBits(E->getType()) 5654 : OpRes; 5655 } 5656 5657 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5658 // The result is the min of all operands results. 5659 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5660 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5661 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5662 return MinOpRes; 5663 } 5664 5665 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5666 // The result is the sum of all operands results. 5667 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5668 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5669 for (unsigned i = 1, e = M->getNumOperands(); 5670 SumOpRes != BitWidth && i != e; ++i) 5671 SumOpRes = 5672 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5673 return SumOpRes; 5674 } 5675 5676 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5677 // The result is the min of all operands results. 5678 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5679 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5680 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5681 return MinOpRes; 5682 } 5683 5684 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5685 // The result is the min of all operands results. 5686 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5687 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5688 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5689 return MinOpRes; 5690 } 5691 5692 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5693 // The result is the min of all operands results. 5694 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5695 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5696 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5697 return MinOpRes; 5698 } 5699 5700 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5701 // For a SCEVUnknown, ask ValueTracking. 5702 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5703 return Known.countMinTrailingZeros(); 5704 } 5705 5706 // SCEVUDivExpr 5707 return 0; 5708 } 5709 5710 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5711 auto I = MinTrailingZerosCache.find(S); 5712 if (I != MinTrailingZerosCache.end()) 5713 return I->second; 5714 5715 uint32_t Result = GetMinTrailingZerosImpl(S); 5716 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5717 assert(InsertPair.second && "Should insert a new key"); 5718 return InsertPair.first->second; 5719 } 5720 5721 /// Helper method to assign a range to V from metadata present in the IR. 5722 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5723 if (Instruction *I = dyn_cast<Instruction>(V)) 5724 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5725 return getConstantRangeFromMetadata(*MD); 5726 5727 return None; 5728 } 5729 5730 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 5731 SCEV::NoWrapFlags Flags) { 5732 if (AddRec->getNoWrapFlags(Flags) != Flags) { 5733 AddRec->setNoWrapFlags(Flags); 5734 UnsignedRanges.erase(AddRec); 5735 SignedRanges.erase(AddRec); 5736 } 5737 } 5738 5739 ConstantRange ScalarEvolution:: 5740 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 5741 const DataLayout &DL = getDataLayout(); 5742 5743 unsigned BitWidth = getTypeSizeInBits(U->getType()); 5744 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 5745 5746 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 5747 // use information about the trip count to improve our available range. Note 5748 // that the trip count independent cases are already handled by known bits. 5749 // WARNING: The definition of recurrence used here is subtly different than 5750 // the one used by AddRec (and thus most of this file). Step is allowed to 5751 // be arbitrarily loop varying here, where AddRec allows only loop invariant 5752 // and other addrecs in the same loop (for non-affine addrecs). The code 5753 // below intentionally handles the case where step is not loop invariant. 5754 auto *P = dyn_cast<PHINode>(U->getValue()); 5755 if (!P) 5756 return FullSet; 5757 5758 // Make sure that no Phi input comes from an unreachable block. Otherwise, 5759 // even the values that are not available in these blocks may come from them, 5760 // and this leads to false-positive recurrence test. 5761 for (auto *Pred : predecessors(P->getParent())) 5762 if (!DT.isReachableFromEntry(Pred)) 5763 return FullSet; 5764 5765 BinaryOperator *BO; 5766 Value *Start, *Step; 5767 if (!matchSimpleRecurrence(P, BO, Start, Step)) 5768 return FullSet; 5769 5770 // If we found a recurrence in reachable code, we must be in a loop. Note 5771 // that BO might be in some subloop of L, and that's completely okay. 5772 auto *L = LI.getLoopFor(P->getParent()); 5773 assert(L && L->getHeader() == P->getParent()); 5774 if (!L->contains(BO->getParent())) 5775 // NOTE: This bailout should be an assert instead. However, asserting 5776 // the condition here exposes a case where LoopFusion is querying SCEV 5777 // with malformed loop information during the midst of the transform. 5778 // There doesn't appear to be an obvious fix, so for the moment bailout 5779 // until the caller issue can be fixed. PR49566 tracks the bug. 5780 return FullSet; 5781 5782 // TODO: Extend to other opcodes such as mul, and div 5783 switch (BO->getOpcode()) { 5784 default: 5785 return FullSet; 5786 case Instruction::AShr: 5787 case Instruction::LShr: 5788 case Instruction::Shl: 5789 break; 5790 }; 5791 5792 if (BO->getOperand(0) != P) 5793 // TODO: Handle the power function forms some day. 5794 return FullSet; 5795 5796 unsigned TC = getSmallConstantMaxTripCount(L); 5797 if (!TC || TC >= BitWidth) 5798 return FullSet; 5799 5800 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 5801 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 5802 assert(KnownStart.getBitWidth() == BitWidth && 5803 KnownStep.getBitWidth() == BitWidth); 5804 5805 // Compute total shift amount, being careful of overflow and bitwidths. 5806 auto MaxShiftAmt = KnownStep.getMaxValue(); 5807 APInt TCAP(BitWidth, TC-1); 5808 bool Overflow = false; 5809 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 5810 if (Overflow) 5811 return FullSet; 5812 5813 switch (BO->getOpcode()) { 5814 default: 5815 llvm_unreachable("filtered out above"); 5816 case Instruction::AShr: { 5817 // For each ashr, three cases: 5818 // shift = 0 => unchanged value 5819 // saturation => 0 or -1 5820 // other => a value closer to zero (of the same sign) 5821 // Thus, the end value is closer to zero than the start. 5822 auto KnownEnd = KnownBits::ashr(KnownStart, 5823 KnownBits::makeConstant(TotalShift)); 5824 if (KnownStart.isNonNegative()) 5825 // Analogous to lshr (simply not yet canonicalized) 5826 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5827 KnownStart.getMaxValue() + 1); 5828 if (KnownStart.isNegative()) 5829 // End >=u Start && End <=s Start 5830 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 5831 KnownEnd.getMaxValue() + 1); 5832 break; 5833 } 5834 case Instruction::LShr: { 5835 // For each lshr, three cases: 5836 // shift = 0 => unchanged value 5837 // saturation => 0 5838 // other => a smaller positive number 5839 // Thus, the low end of the unsigned range is the last value produced. 5840 auto KnownEnd = KnownBits::lshr(KnownStart, 5841 KnownBits::makeConstant(TotalShift)); 5842 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5843 KnownStart.getMaxValue() + 1); 5844 } 5845 case Instruction::Shl: { 5846 // Iff no bits are shifted out, value increases on every shift. 5847 auto KnownEnd = KnownBits::shl(KnownStart, 5848 KnownBits::makeConstant(TotalShift)); 5849 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 5850 return ConstantRange(KnownStart.getMinValue(), 5851 KnownEnd.getMaxValue() + 1); 5852 break; 5853 } 5854 }; 5855 return FullSet; 5856 } 5857 5858 /// Determine the range for a particular SCEV. If SignHint is 5859 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5860 /// with a "cleaner" unsigned (resp. signed) representation. 5861 const ConstantRange & 5862 ScalarEvolution::getRangeRef(const SCEV *S, 5863 ScalarEvolution::RangeSignHint SignHint) { 5864 DenseMap<const SCEV *, ConstantRange> &Cache = 5865 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5866 : SignedRanges; 5867 ConstantRange::PreferredRangeType RangeType = 5868 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5869 ? ConstantRange::Unsigned : ConstantRange::Signed; 5870 5871 // See if we've computed this range already. 5872 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5873 if (I != Cache.end()) 5874 return I->second; 5875 5876 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5877 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5878 5879 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5880 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5881 using OBO = OverflowingBinaryOperator; 5882 5883 // If the value has known zeros, the maximum value will have those known zeros 5884 // as well. 5885 uint32_t TZ = GetMinTrailingZeros(S); 5886 if (TZ != 0) { 5887 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5888 ConservativeResult = 5889 ConstantRange(APInt::getMinValue(BitWidth), 5890 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5891 else 5892 ConservativeResult = ConstantRange( 5893 APInt::getSignedMinValue(BitWidth), 5894 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5895 } 5896 5897 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5898 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5899 unsigned WrapType = OBO::AnyWrap; 5900 if (Add->hasNoSignedWrap()) 5901 WrapType |= OBO::NoSignedWrap; 5902 if (Add->hasNoUnsignedWrap()) 5903 WrapType |= OBO::NoUnsignedWrap; 5904 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5905 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 5906 WrapType, RangeType); 5907 return setRange(Add, SignHint, 5908 ConservativeResult.intersectWith(X, RangeType)); 5909 } 5910 5911 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5912 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5913 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5914 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5915 return setRange(Mul, SignHint, 5916 ConservativeResult.intersectWith(X, RangeType)); 5917 } 5918 5919 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5920 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5921 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5922 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5923 return setRange(SMax, SignHint, 5924 ConservativeResult.intersectWith(X, RangeType)); 5925 } 5926 5927 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5928 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5929 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5930 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5931 return setRange(UMax, SignHint, 5932 ConservativeResult.intersectWith(X, RangeType)); 5933 } 5934 5935 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5936 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5937 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5938 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5939 return setRange(SMin, SignHint, 5940 ConservativeResult.intersectWith(X, RangeType)); 5941 } 5942 5943 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5944 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5945 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5946 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5947 return setRange(UMin, SignHint, 5948 ConservativeResult.intersectWith(X, RangeType)); 5949 } 5950 5951 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5952 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5953 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5954 return setRange(UDiv, SignHint, 5955 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5956 } 5957 5958 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5959 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5960 return setRange(ZExt, SignHint, 5961 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5962 RangeType)); 5963 } 5964 5965 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5966 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5967 return setRange(SExt, SignHint, 5968 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5969 RangeType)); 5970 } 5971 5972 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 5973 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 5974 return setRange(PtrToInt, SignHint, X); 5975 } 5976 5977 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5978 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5979 return setRange(Trunc, SignHint, 5980 ConservativeResult.intersectWith(X.truncate(BitWidth), 5981 RangeType)); 5982 } 5983 5984 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5985 // If there's no unsigned wrap, the value will never be less than its 5986 // initial value. 5987 if (AddRec->hasNoUnsignedWrap()) { 5988 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 5989 if (!UnsignedMinValue.isNullValue()) 5990 ConservativeResult = ConservativeResult.intersectWith( 5991 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 5992 } 5993 5994 // If there's no signed wrap, and all the operands except initial value have 5995 // the same sign or zero, the value won't ever be: 5996 // 1: smaller than initial value if operands are non negative, 5997 // 2: bigger than initial value if operands are non positive. 5998 // For both cases, value can not cross signed min/max boundary. 5999 if (AddRec->hasNoSignedWrap()) { 6000 bool AllNonNeg = true; 6001 bool AllNonPos = true; 6002 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 6003 if (!isKnownNonNegative(AddRec->getOperand(i))) 6004 AllNonNeg = false; 6005 if (!isKnownNonPositive(AddRec->getOperand(i))) 6006 AllNonPos = false; 6007 } 6008 if (AllNonNeg) 6009 ConservativeResult = ConservativeResult.intersectWith( 6010 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 6011 APInt::getSignedMinValue(BitWidth)), 6012 RangeType); 6013 else if (AllNonPos) 6014 ConservativeResult = ConservativeResult.intersectWith( 6015 ConstantRange::getNonEmpty( 6016 APInt::getSignedMinValue(BitWidth), 6017 getSignedRangeMax(AddRec->getStart()) + 1), 6018 RangeType); 6019 } 6020 6021 // TODO: non-affine addrec 6022 if (AddRec->isAffine()) { 6023 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 6024 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 6025 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 6026 auto RangeFromAffine = getRangeForAffineAR( 6027 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6028 BitWidth); 6029 ConservativeResult = 6030 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 6031 6032 auto RangeFromFactoring = getRangeViaFactoring( 6033 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6034 BitWidth); 6035 ConservativeResult = 6036 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 6037 } 6038 6039 // Now try symbolic BE count and more powerful methods. 6040 if (UseExpensiveRangeSharpening) { 6041 const SCEV *SymbolicMaxBECount = 6042 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 6043 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 6044 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6045 AddRec->hasNoSelfWrap()) { 6046 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 6047 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 6048 ConservativeResult = 6049 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 6050 } 6051 } 6052 } 6053 6054 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 6055 } 6056 6057 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6058 6059 // Check if the IR explicitly contains !range metadata. 6060 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 6061 if (MDRange.hasValue()) 6062 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 6063 RangeType); 6064 6065 // Use facts about recurrences in the underlying IR. Note that add 6066 // recurrences are AddRecExprs and thus don't hit this path. This 6067 // primarily handles shift recurrences. 6068 auto CR = getRangeForUnknownRecurrence(U); 6069 ConservativeResult = ConservativeResult.intersectWith(CR); 6070 6071 // See if ValueTracking can give us a useful range. 6072 const DataLayout &DL = getDataLayout(); 6073 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6074 if (Known.getBitWidth() != BitWidth) 6075 Known = Known.zextOrTrunc(BitWidth); 6076 6077 // ValueTracking may be able to compute a tighter result for the number of 6078 // sign bits than for the value of those sign bits. 6079 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6080 if (U->getType()->isPointerTy()) { 6081 // If the pointer size is larger than the index size type, this can cause 6082 // NS to be larger than BitWidth. So compensate for this. 6083 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6084 int ptrIdxDiff = ptrSize - BitWidth; 6085 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6086 NS -= ptrIdxDiff; 6087 } 6088 6089 if (NS > 1) { 6090 // If we know any of the sign bits, we know all of the sign bits. 6091 if (!Known.Zero.getHiBits(NS).isNullValue()) 6092 Known.Zero.setHighBits(NS); 6093 if (!Known.One.getHiBits(NS).isNullValue()) 6094 Known.One.setHighBits(NS); 6095 } 6096 6097 if (Known.getMinValue() != Known.getMaxValue() + 1) 6098 ConservativeResult = ConservativeResult.intersectWith( 6099 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6100 RangeType); 6101 if (NS > 1) 6102 ConservativeResult = ConservativeResult.intersectWith( 6103 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6104 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6105 RangeType); 6106 6107 // A range of Phi is a subset of union of all ranges of its input. 6108 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 6109 // Make sure that we do not run over cycled Phis. 6110 if (PendingPhiRanges.insert(Phi).second) { 6111 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 6112 for (auto &Op : Phi->operands()) { 6113 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 6114 RangeFromOps = RangeFromOps.unionWith(OpRange); 6115 // No point to continue if we already have a full set. 6116 if (RangeFromOps.isFullSet()) 6117 break; 6118 } 6119 ConservativeResult = 6120 ConservativeResult.intersectWith(RangeFromOps, RangeType); 6121 bool Erased = PendingPhiRanges.erase(Phi); 6122 assert(Erased && "Failed to erase Phi properly?"); 6123 (void) Erased; 6124 } 6125 } 6126 6127 return setRange(U, SignHint, std::move(ConservativeResult)); 6128 } 6129 6130 return setRange(S, SignHint, std::move(ConservativeResult)); 6131 } 6132 6133 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6134 // values that the expression can take. Initially, the expression has a value 6135 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6136 // argument defines if we treat Step as signed or unsigned. 6137 static ConstantRange getRangeForAffineARHelper(APInt Step, 6138 const ConstantRange &StartRange, 6139 const APInt &MaxBECount, 6140 unsigned BitWidth, bool Signed) { 6141 // If either Step or MaxBECount is 0, then the expression won't change, and we 6142 // just need to return the initial range. 6143 if (Step == 0 || MaxBECount == 0) 6144 return StartRange; 6145 6146 // If we don't know anything about the initial value (i.e. StartRange is 6147 // FullRange), then we don't know anything about the final range either. 6148 // Return FullRange. 6149 if (StartRange.isFullSet()) 6150 return ConstantRange::getFull(BitWidth); 6151 6152 // If Step is signed and negative, then we use its absolute value, but we also 6153 // note that we're moving in the opposite direction. 6154 bool Descending = Signed && Step.isNegative(); 6155 6156 if (Signed) 6157 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6158 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6159 // This equations hold true due to the well-defined wrap-around behavior of 6160 // APInt. 6161 Step = Step.abs(); 6162 6163 // Check if Offset is more than full span of BitWidth. If it is, the 6164 // expression is guaranteed to overflow. 6165 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6166 return ConstantRange::getFull(BitWidth); 6167 6168 // Offset is by how much the expression can change. Checks above guarantee no 6169 // overflow here. 6170 APInt Offset = Step * MaxBECount; 6171 6172 // Minimum value of the final range will match the minimal value of StartRange 6173 // if the expression is increasing and will be decreased by Offset otherwise. 6174 // Maximum value of the final range will match the maximal value of StartRange 6175 // if the expression is decreasing and will be increased by Offset otherwise. 6176 APInt StartLower = StartRange.getLower(); 6177 APInt StartUpper = StartRange.getUpper() - 1; 6178 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6179 : (StartUpper + std::move(Offset)); 6180 6181 // It's possible that the new minimum/maximum value will fall into the initial 6182 // range (due to wrap around). This means that the expression can take any 6183 // value in this bitwidth, and we have to return full range. 6184 if (StartRange.contains(MovedBoundary)) 6185 return ConstantRange::getFull(BitWidth); 6186 6187 APInt NewLower = 6188 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6189 APInt NewUpper = 6190 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6191 NewUpper += 1; 6192 6193 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6194 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6195 } 6196 6197 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6198 const SCEV *Step, 6199 const SCEV *MaxBECount, 6200 unsigned BitWidth) { 6201 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6202 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6203 "Precondition!"); 6204 6205 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6206 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6207 6208 // First, consider step signed. 6209 ConstantRange StartSRange = getSignedRange(Start); 6210 ConstantRange StepSRange = getSignedRange(Step); 6211 6212 // If Step can be both positive and negative, we need to find ranges for the 6213 // maximum absolute step values in both directions and union them. 6214 ConstantRange SR = 6215 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6216 MaxBECountValue, BitWidth, /* Signed = */ true); 6217 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6218 StartSRange, MaxBECountValue, 6219 BitWidth, /* Signed = */ true)); 6220 6221 // Next, consider step unsigned. 6222 ConstantRange UR = getRangeForAffineARHelper( 6223 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6224 MaxBECountValue, BitWidth, /* Signed = */ false); 6225 6226 // Finally, intersect signed and unsigned ranges. 6227 return SR.intersectWith(UR, ConstantRange::Smallest); 6228 } 6229 6230 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6231 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6232 ScalarEvolution::RangeSignHint SignHint) { 6233 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6234 assert(AddRec->hasNoSelfWrap() && 6235 "This only works for non-self-wrapping AddRecs!"); 6236 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6237 const SCEV *Step = AddRec->getStepRecurrence(*this); 6238 // Only deal with constant step to save compile time. 6239 if (!isa<SCEVConstant>(Step)) 6240 return ConstantRange::getFull(BitWidth); 6241 // Let's make sure that we can prove that we do not self-wrap during 6242 // MaxBECount iterations. We need this because MaxBECount is a maximum 6243 // iteration count estimate, and we might infer nw from some exit for which we 6244 // do not know max exit count (or any other side reasoning). 6245 // TODO: Turn into assert at some point. 6246 if (getTypeSizeInBits(MaxBECount->getType()) > 6247 getTypeSizeInBits(AddRec->getType())) 6248 return ConstantRange::getFull(BitWidth); 6249 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6250 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6251 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6252 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6253 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6254 MaxItersWithoutWrap)) 6255 return ConstantRange::getFull(BitWidth); 6256 6257 ICmpInst::Predicate LEPred = 6258 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6259 ICmpInst::Predicate GEPred = 6260 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6261 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6262 6263 // We know that there is no self-wrap. Let's take Start and End values and 6264 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6265 // the iteration. They either lie inside the range [Min(Start, End), 6266 // Max(Start, End)] or outside it: 6267 // 6268 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6269 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6270 // 6271 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6272 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6273 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6274 // Start <= End and step is positive, or Start >= End and step is negative. 6275 const SCEV *Start = AddRec->getStart(); 6276 ConstantRange StartRange = getRangeRef(Start, SignHint); 6277 ConstantRange EndRange = getRangeRef(End, SignHint); 6278 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6279 // If they already cover full iteration space, we will know nothing useful 6280 // even if we prove what we want to prove. 6281 if (RangeBetween.isFullSet()) 6282 return RangeBetween; 6283 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6284 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6285 : RangeBetween.isWrappedSet(); 6286 if (IsWrappedSet) 6287 return ConstantRange::getFull(BitWidth); 6288 6289 if (isKnownPositive(Step) && 6290 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6291 return RangeBetween; 6292 else if (isKnownNegative(Step) && 6293 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6294 return RangeBetween; 6295 return ConstantRange::getFull(BitWidth); 6296 } 6297 6298 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6299 const SCEV *Step, 6300 const SCEV *MaxBECount, 6301 unsigned BitWidth) { 6302 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6303 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6304 6305 struct SelectPattern { 6306 Value *Condition = nullptr; 6307 APInt TrueValue; 6308 APInt FalseValue; 6309 6310 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6311 const SCEV *S) { 6312 Optional<unsigned> CastOp; 6313 APInt Offset(BitWidth, 0); 6314 6315 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6316 "Should be!"); 6317 6318 // Peel off a constant offset: 6319 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6320 // In the future we could consider being smarter here and handle 6321 // {Start+Step,+,Step} too. 6322 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6323 return; 6324 6325 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6326 S = SA->getOperand(1); 6327 } 6328 6329 // Peel off a cast operation 6330 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6331 CastOp = SCast->getSCEVType(); 6332 S = SCast->getOperand(); 6333 } 6334 6335 using namespace llvm::PatternMatch; 6336 6337 auto *SU = dyn_cast<SCEVUnknown>(S); 6338 const APInt *TrueVal, *FalseVal; 6339 if (!SU || 6340 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6341 m_APInt(FalseVal)))) { 6342 Condition = nullptr; 6343 return; 6344 } 6345 6346 TrueValue = *TrueVal; 6347 FalseValue = *FalseVal; 6348 6349 // Re-apply the cast we peeled off earlier 6350 if (CastOp.hasValue()) 6351 switch (*CastOp) { 6352 default: 6353 llvm_unreachable("Unknown SCEV cast type!"); 6354 6355 case scTruncate: 6356 TrueValue = TrueValue.trunc(BitWidth); 6357 FalseValue = FalseValue.trunc(BitWidth); 6358 break; 6359 case scZeroExtend: 6360 TrueValue = TrueValue.zext(BitWidth); 6361 FalseValue = FalseValue.zext(BitWidth); 6362 break; 6363 case scSignExtend: 6364 TrueValue = TrueValue.sext(BitWidth); 6365 FalseValue = FalseValue.sext(BitWidth); 6366 break; 6367 } 6368 6369 // Re-apply the constant offset we peeled off earlier 6370 TrueValue += Offset; 6371 FalseValue += Offset; 6372 } 6373 6374 bool isRecognized() { return Condition != nullptr; } 6375 }; 6376 6377 SelectPattern StartPattern(*this, BitWidth, Start); 6378 if (!StartPattern.isRecognized()) 6379 return ConstantRange::getFull(BitWidth); 6380 6381 SelectPattern StepPattern(*this, BitWidth, Step); 6382 if (!StepPattern.isRecognized()) 6383 return ConstantRange::getFull(BitWidth); 6384 6385 if (StartPattern.Condition != StepPattern.Condition) { 6386 // We don't handle this case today; but we could, by considering four 6387 // possibilities below instead of two. I'm not sure if there are cases where 6388 // that will help over what getRange already does, though. 6389 return ConstantRange::getFull(BitWidth); 6390 } 6391 6392 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6393 // construct arbitrary general SCEV expressions here. This function is called 6394 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6395 // say) can end up caching a suboptimal value. 6396 6397 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6398 // C2352 and C2512 (otherwise it isn't needed). 6399 6400 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6401 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6402 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6403 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6404 6405 ConstantRange TrueRange = 6406 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6407 ConstantRange FalseRange = 6408 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6409 6410 return TrueRange.unionWith(FalseRange); 6411 } 6412 6413 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6414 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6415 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6416 6417 // Return early if there are no flags to propagate to the SCEV. 6418 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6419 if (BinOp->hasNoUnsignedWrap()) 6420 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6421 if (BinOp->hasNoSignedWrap()) 6422 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6423 if (Flags == SCEV::FlagAnyWrap) 6424 return SCEV::FlagAnyWrap; 6425 6426 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6427 } 6428 6429 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6430 // Here we check that I is in the header of the innermost loop containing I, 6431 // since we only deal with instructions in the loop header. The actual loop we 6432 // need to check later will come from an add recurrence, but getting that 6433 // requires computing the SCEV of the operands, which can be expensive. This 6434 // check we can do cheaply to rule out some cases early. 6435 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6436 if (InnermostContainingLoop == nullptr || 6437 InnermostContainingLoop->getHeader() != I->getParent()) 6438 return false; 6439 6440 // Only proceed if we can prove that I does not yield poison. 6441 if (!programUndefinedIfPoison(I)) 6442 return false; 6443 6444 // At this point we know that if I is executed, then it does not wrap 6445 // according to at least one of NSW or NUW. If I is not executed, then we do 6446 // not know if the calculation that I represents would wrap. Multiple 6447 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6448 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6449 // derived from other instructions that map to the same SCEV. We cannot make 6450 // that guarantee for cases where I is not executed. So we need to find the 6451 // loop that I is considered in relation to and prove that I is executed for 6452 // every iteration of that loop. That implies that the value that I 6453 // calculates does not wrap anywhere in the loop, so then we can apply the 6454 // flags to the SCEV. 6455 // 6456 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6457 // from different loops, so that we know which loop to prove that I is 6458 // executed in. 6459 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6460 // I could be an extractvalue from a call to an overflow intrinsic. 6461 // TODO: We can do better here in some cases. 6462 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6463 return false; 6464 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6465 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6466 bool AllOtherOpsLoopInvariant = true; 6467 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6468 ++OtherOpIndex) { 6469 if (OtherOpIndex != OpIndex) { 6470 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6471 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6472 AllOtherOpsLoopInvariant = false; 6473 break; 6474 } 6475 } 6476 } 6477 if (AllOtherOpsLoopInvariant && 6478 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6479 return true; 6480 } 6481 } 6482 return false; 6483 } 6484 6485 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6486 // If we know that \c I can never be poison period, then that's enough. 6487 if (isSCEVExprNeverPoison(I)) 6488 return true; 6489 6490 // For an add recurrence specifically, we assume that infinite loops without 6491 // side effects are undefined behavior, and then reason as follows: 6492 // 6493 // If the add recurrence is poison in any iteration, it is poison on all 6494 // future iterations (since incrementing poison yields poison). If the result 6495 // of the add recurrence is fed into the loop latch condition and the loop 6496 // does not contain any throws or exiting blocks other than the latch, we now 6497 // have the ability to "choose" whether the backedge is taken or not (by 6498 // choosing a sufficiently evil value for the poison feeding into the branch) 6499 // for every iteration including and after the one in which \p I first became 6500 // poison. There are two possibilities (let's call the iteration in which \p 6501 // I first became poison as K): 6502 // 6503 // 1. In the set of iterations including and after K, the loop body executes 6504 // no side effects. In this case executing the backege an infinte number 6505 // of times will yield undefined behavior. 6506 // 6507 // 2. In the set of iterations including and after K, the loop body executes 6508 // at least one side effect. In this case, that specific instance of side 6509 // effect is control dependent on poison, which also yields undefined 6510 // behavior. 6511 6512 auto *ExitingBB = L->getExitingBlock(); 6513 auto *LatchBB = L->getLoopLatch(); 6514 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6515 return false; 6516 6517 SmallPtrSet<const Instruction *, 16> Pushed; 6518 SmallVector<const Instruction *, 8> PoisonStack; 6519 6520 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6521 // things that are known to be poison under that assumption go on the 6522 // PoisonStack. 6523 Pushed.insert(I); 6524 PoisonStack.push_back(I); 6525 6526 bool LatchControlDependentOnPoison = false; 6527 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6528 const Instruction *Poison = PoisonStack.pop_back_val(); 6529 6530 for (auto *PoisonUser : Poison->users()) { 6531 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6532 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6533 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6534 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6535 assert(BI->isConditional() && "Only possibility!"); 6536 if (BI->getParent() == LatchBB) { 6537 LatchControlDependentOnPoison = true; 6538 break; 6539 } 6540 } 6541 } 6542 } 6543 6544 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6545 } 6546 6547 ScalarEvolution::LoopProperties 6548 ScalarEvolution::getLoopProperties(const Loop *L) { 6549 using LoopProperties = ScalarEvolution::LoopProperties; 6550 6551 auto Itr = LoopPropertiesCache.find(L); 6552 if (Itr == LoopPropertiesCache.end()) { 6553 auto HasSideEffects = [](Instruction *I) { 6554 if (auto *SI = dyn_cast<StoreInst>(I)) 6555 return !SI->isSimple(); 6556 6557 return I->mayHaveSideEffects(); 6558 }; 6559 6560 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6561 /*HasNoSideEffects*/ true}; 6562 6563 for (auto *BB : L->getBlocks()) 6564 for (auto &I : *BB) { 6565 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6566 LP.HasNoAbnormalExits = false; 6567 if (HasSideEffects(&I)) 6568 LP.HasNoSideEffects = false; 6569 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6570 break; // We're already as pessimistic as we can get. 6571 } 6572 6573 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6574 assert(InsertPair.second && "We just checked!"); 6575 Itr = InsertPair.first; 6576 } 6577 6578 return Itr->second; 6579 } 6580 6581 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) { 6582 if (!L->getHeader()->getParent()->mustProgress() && 6583 !hasMustProgress(L)) 6584 return false; 6585 6586 // A loop without side effects must be finite. 6587 // TODO: The check used here is very conservative. It's only *specific* 6588 // side effects which are well defined in infinite loops. 6589 return loopHasNoSideEffects(L); 6590 } 6591 6592 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6593 if (!isSCEVable(V->getType())) 6594 return getUnknown(V); 6595 6596 if (Instruction *I = dyn_cast<Instruction>(V)) { 6597 // Don't attempt to analyze instructions in blocks that aren't 6598 // reachable. Such instructions don't matter, and they aren't required 6599 // to obey basic rules for definitions dominating uses which this 6600 // analysis depends on. 6601 if (!DT.isReachableFromEntry(I->getParent())) 6602 return getUnknown(UndefValue::get(V->getType())); 6603 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6604 return getConstant(CI); 6605 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6606 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6607 else if (!isa<ConstantExpr>(V)) 6608 return getUnknown(V); 6609 6610 Operator *U = cast<Operator>(V); 6611 if (auto BO = MatchBinaryOp(U, DT)) { 6612 switch (BO->Opcode) { 6613 case Instruction::Add: { 6614 // The simple thing to do would be to just call getSCEV on both operands 6615 // and call getAddExpr with the result. However if we're looking at a 6616 // bunch of things all added together, this can be quite inefficient, 6617 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6618 // Instead, gather up all the operands and make a single getAddExpr call. 6619 // LLVM IR canonical form means we need only traverse the left operands. 6620 SmallVector<const SCEV *, 4> AddOps; 6621 do { 6622 if (BO->Op) { 6623 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6624 AddOps.push_back(OpSCEV); 6625 break; 6626 } 6627 6628 // If a NUW or NSW flag can be applied to the SCEV for this 6629 // addition, then compute the SCEV for this addition by itself 6630 // with a separate call to getAddExpr. We need to do that 6631 // instead of pushing the operands of the addition onto AddOps, 6632 // since the flags are only known to apply to this particular 6633 // addition - they may not apply to other additions that can be 6634 // formed with operands from AddOps. 6635 const SCEV *RHS = getSCEV(BO->RHS); 6636 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6637 if (Flags != SCEV::FlagAnyWrap) { 6638 const SCEV *LHS = getSCEV(BO->LHS); 6639 if (BO->Opcode == Instruction::Sub) 6640 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6641 else 6642 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6643 break; 6644 } 6645 } 6646 6647 if (BO->Opcode == Instruction::Sub) 6648 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6649 else 6650 AddOps.push_back(getSCEV(BO->RHS)); 6651 6652 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6653 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6654 NewBO->Opcode != Instruction::Sub)) { 6655 AddOps.push_back(getSCEV(BO->LHS)); 6656 break; 6657 } 6658 BO = NewBO; 6659 } while (true); 6660 6661 return getAddExpr(AddOps); 6662 } 6663 6664 case Instruction::Mul: { 6665 SmallVector<const SCEV *, 4> MulOps; 6666 do { 6667 if (BO->Op) { 6668 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6669 MulOps.push_back(OpSCEV); 6670 break; 6671 } 6672 6673 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6674 if (Flags != SCEV::FlagAnyWrap) { 6675 MulOps.push_back( 6676 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6677 break; 6678 } 6679 } 6680 6681 MulOps.push_back(getSCEV(BO->RHS)); 6682 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6683 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6684 MulOps.push_back(getSCEV(BO->LHS)); 6685 break; 6686 } 6687 BO = NewBO; 6688 } while (true); 6689 6690 return getMulExpr(MulOps); 6691 } 6692 case Instruction::UDiv: 6693 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6694 case Instruction::URem: 6695 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6696 case Instruction::Sub: { 6697 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6698 if (BO->Op) 6699 Flags = getNoWrapFlagsFromUB(BO->Op); 6700 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6701 } 6702 case Instruction::And: 6703 // For an expression like x&255 that merely masks off the high bits, 6704 // use zext(trunc(x)) as the SCEV expression. 6705 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6706 if (CI->isZero()) 6707 return getSCEV(BO->RHS); 6708 if (CI->isMinusOne()) 6709 return getSCEV(BO->LHS); 6710 const APInt &A = CI->getValue(); 6711 6712 // Instcombine's ShrinkDemandedConstant may strip bits out of 6713 // constants, obscuring what would otherwise be a low-bits mask. 6714 // Use computeKnownBits to compute what ShrinkDemandedConstant 6715 // knew about to reconstruct a low-bits mask value. 6716 unsigned LZ = A.countLeadingZeros(); 6717 unsigned TZ = A.countTrailingZeros(); 6718 unsigned BitWidth = A.getBitWidth(); 6719 KnownBits Known(BitWidth); 6720 computeKnownBits(BO->LHS, Known, getDataLayout(), 6721 0, &AC, nullptr, &DT); 6722 6723 APInt EffectiveMask = 6724 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6725 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6726 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6727 const SCEV *LHS = getSCEV(BO->LHS); 6728 const SCEV *ShiftedLHS = nullptr; 6729 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6730 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6731 // For an expression like (x * 8) & 8, simplify the multiply. 6732 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6733 unsigned GCD = std::min(MulZeros, TZ); 6734 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6735 SmallVector<const SCEV*, 4> MulOps; 6736 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6737 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6738 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6739 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6740 } 6741 } 6742 if (!ShiftedLHS) 6743 ShiftedLHS = getUDivExpr(LHS, MulCount); 6744 return getMulExpr( 6745 getZeroExtendExpr( 6746 getTruncateExpr(ShiftedLHS, 6747 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6748 BO->LHS->getType()), 6749 MulCount); 6750 } 6751 } 6752 break; 6753 6754 case Instruction::Or: 6755 // If the RHS of the Or is a constant, we may have something like: 6756 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6757 // optimizations will transparently handle this case. 6758 // 6759 // In order for this transformation to be safe, the LHS must be of the 6760 // form X*(2^n) and the Or constant must be less than 2^n. 6761 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6762 const SCEV *LHS = getSCEV(BO->LHS); 6763 const APInt &CIVal = CI->getValue(); 6764 if (GetMinTrailingZeros(LHS) >= 6765 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6766 // Build a plain add SCEV. 6767 return getAddExpr(LHS, getSCEV(CI), 6768 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6769 } 6770 } 6771 break; 6772 6773 case Instruction::Xor: 6774 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6775 // If the RHS of xor is -1, then this is a not operation. 6776 if (CI->isMinusOne()) 6777 return getNotSCEV(getSCEV(BO->LHS)); 6778 6779 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6780 // This is a variant of the check for xor with -1, and it handles 6781 // the case where instcombine has trimmed non-demanded bits out 6782 // of an xor with -1. 6783 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6784 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6785 if (LBO->getOpcode() == Instruction::And && 6786 LCI->getValue() == CI->getValue()) 6787 if (const SCEVZeroExtendExpr *Z = 6788 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6789 Type *UTy = BO->LHS->getType(); 6790 const SCEV *Z0 = Z->getOperand(); 6791 Type *Z0Ty = Z0->getType(); 6792 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6793 6794 // If C is a low-bits mask, the zero extend is serving to 6795 // mask off the high bits. Complement the operand and 6796 // re-apply the zext. 6797 if (CI->getValue().isMask(Z0TySize)) 6798 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6799 6800 // If C is a single bit, it may be in the sign-bit position 6801 // before the zero-extend. In this case, represent the xor 6802 // using an add, which is equivalent, and re-apply the zext. 6803 APInt Trunc = CI->getValue().trunc(Z0TySize); 6804 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6805 Trunc.isSignMask()) 6806 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6807 UTy); 6808 } 6809 } 6810 break; 6811 6812 case Instruction::Shl: 6813 // Turn shift left of a constant amount into a multiply. 6814 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6815 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6816 6817 // If the shift count is not less than the bitwidth, the result of 6818 // the shift is undefined. Don't try to analyze it, because the 6819 // resolution chosen here may differ from the resolution chosen in 6820 // other parts of the compiler. 6821 if (SA->getValue().uge(BitWidth)) 6822 break; 6823 6824 // We can safely preserve the nuw flag in all cases. It's also safe to 6825 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6826 // requires special handling. It can be preserved as long as we're not 6827 // left shifting by bitwidth - 1. 6828 auto Flags = SCEV::FlagAnyWrap; 6829 if (BO->Op) { 6830 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6831 if ((MulFlags & SCEV::FlagNSW) && 6832 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6833 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6834 if (MulFlags & SCEV::FlagNUW) 6835 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6836 } 6837 6838 Constant *X = ConstantInt::get( 6839 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6840 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6841 } 6842 break; 6843 6844 case Instruction::AShr: { 6845 // AShr X, C, where C is a constant. 6846 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6847 if (!CI) 6848 break; 6849 6850 Type *OuterTy = BO->LHS->getType(); 6851 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6852 // If the shift count is not less than the bitwidth, the result of 6853 // the shift is undefined. Don't try to analyze it, because the 6854 // resolution chosen here may differ from the resolution chosen in 6855 // other parts of the compiler. 6856 if (CI->getValue().uge(BitWidth)) 6857 break; 6858 6859 if (CI->isZero()) 6860 return getSCEV(BO->LHS); // shift by zero --> noop 6861 6862 uint64_t AShrAmt = CI->getZExtValue(); 6863 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6864 6865 Operator *L = dyn_cast<Operator>(BO->LHS); 6866 if (L && L->getOpcode() == Instruction::Shl) { 6867 // X = Shl A, n 6868 // Y = AShr X, m 6869 // Both n and m are constant. 6870 6871 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6872 if (L->getOperand(1) == BO->RHS) 6873 // For a two-shift sext-inreg, i.e. n = m, 6874 // use sext(trunc(x)) as the SCEV expression. 6875 return getSignExtendExpr( 6876 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6877 6878 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6879 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6880 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6881 if (ShlAmt > AShrAmt) { 6882 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6883 // expression. We already checked that ShlAmt < BitWidth, so 6884 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6885 // ShlAmt - AShrAmt < Amt. 6886 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6887 ShlAmt - AShrAmt); 6888 return getSignExtendExpr( 6889 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6890 getConstant(Mul)), OuterTy); 6891 } 6892 } 6893 } 6894 break; 6895 } 6896 } 6897 } 6898 6899 switch (U->getOpcode()) { 6900 case Instruction::Trunc: 6901 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6902 6903 case Instruction::ZExt: 6904 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6905 6906 case Instruction::SExt: 6907 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6908 // The NSW flag of a subtract does not always survive the conversion to 6909 // A + (-1)*B. By pushing sign extension onto its operands we are much 6910 // more likely to preserve NSW and allow later AddRec optimisations. 6911 // 6912 // NOTE: This is effectively duplicating this logic from getSignExtend: 6913 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6914 // but by that point the NSW information has potentially been lost. 6915 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6916 Type *Ty = U->getType(); 6917 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6918 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6919 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6920 } 6921 } 6922 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6923 6924 case Instruction::BitCast: 6925 // BitCasts are no-op casts so we just eliminate the cast. 6926 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6927 return getSCEV(U->getOperand(0)); 6928 break; 6929 6930 case Instruction::PtrToInt: { 6931 // Pointer to integer cast is straight-forward, so do model it. 6932 const SCEV *Op = getSCEV(U->getOperand(0)); 6933 Type *DstIntTy = U->getType(); 6934 // But only if effective SCEV (integer) type is wide enough to represent 6935 // all possible pointer values. 6936 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 6937 if (isa<SCEVCouldNotCompute>(IntOp)) 6938 return getUnknown(V); 6939 return IntOp; 6940 } 6941 case Instruction::IntToPtr: 6942 // Just don't deal with inttoptr casts. 6943 return getUnknown(V); 6944 6945 case Instruction::SDiv: 6946 // If both operands are non-negative, this is just an udiv. 6947 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6948 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6949 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6950 break; 6951 6952 case Instruction::SRem: 6953 // If both operands are non-negative, this is just an urem. 6954 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6955 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6956 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6957 break; 6958 6959 case Instruction::GetElementPtr: 6960 return createNodeForGEP(cast<GEPOperator>(U)); 6961 6962 case Instruction::PHI: 6963 return createNodeForPHI(cast<PHINode>(U)); 6964 6965 case Instruction::Select: 6966 // U can also be a select constant expr, which let fall through. Since 6967 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6968 // constant expressions cannot have instructions as operands, we'd have 6969 // returned getUnknown for a select constant expressions anyway. 6970 if (isa<Instruction>(U)) 6971 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6972 U->getOperand(1), U->getOperand(2)); 6973 break; 6974 6975 case Instruction::Call: 6976 case Instruction::Invoke: 6977 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 6978 return getSCEV(RV); 6979 6980 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 6981 switch (II->getIntrinsicID()) { 6982 case Intrinsic::abs: 6983 return getAbsExpr( 6984 getSCEV(II->getArgOperand(0)), 6985 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 6986 case Intrinsic::umax: 6987 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 6988 getSCEV(II->getArgOperand(1))); 6989 case Intrinsic::umin: 6990 return getUMinExpr(getSCEV(II->getArgOperand(0)), 6991 getSCEV(II->getArgOperand(1))); 6992 case Intrinsic::smax: 6993 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 6994 getSCEV(II->getArgOperand(1))); 6995 case Intrinsic::smin: 6996 return getSMinExpr(getSCEV(II->getArgOperand(0)), 6997 getSCEV(II->getArgOperand(1))); 6998 case Intrinsic::usub_sat: { 6999 const SCEV *X = getSCEV(II->getArgOperand(0)); 7000 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7001 const SCEV *ClampedY = getUMinExpr(X, Y); 7002 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 7003 } 7004 case Intrinsic::uadd_sat: { 7005 const SCEV *X = getSCEV(II->getArgOperand(0)); 7006 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7007 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 7008 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 7009 } 7010 case Intrinsic::start_loop_iterations: 7011 // A start_loop_iterations is just equivalent to the first operand for 7012 // SCEV purposes. 7013 return getSCEV(II->getArgOperand(0)); 7014 default: 7015 break; 7016 } 7017 } 7018 break; 7019 } 7020 7021 return getUnknown(V); 7022 } 7023 7024 //===----------------------------------------------------------------------===// 7025 // Iteration Count Computation Code 7026 // 7027 7028 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) { 7029 // Get the trip count from the BE count by adding 1. Overflow, results 7030 // in zero which means "unknown". 7031 return getAddExpr(ExitCount, getOne(ExitCount->getType())); 7032 } 7033 7034 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 7035 if (!ExitCount) 7036 return 0; 7037 7038 ConstantInt *ExitConst = ExitCount->getValue(); 7039 7040 // Guard against huge trip counts. 7041 if (ExitConst->getValue().getActiveBits() > 32) 7042 return 0; 7043 7044 // In case of integer overflow, this returns 0, which is correct. 7045 return ((unsigned)ExitConst->getZExtValue()) + 1; 7046 } 7047 7048 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 7049 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 7050 return getConstantTripCount(ExitCount); 7051 } 7052 7053 unsigned 7054 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 7055 const BasicBlock *ExitingBlock) { 7056 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7057 assert(L->isLoopExiting(ExitingBlock) && 7058 "Exiting block must actually branch out of the loop!"); 7059 const SCEVConstant *ExitCount = 7060 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 7061 return getConstantTripCount(ExitCount); 7062 } 7063 7064 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 7065 const auto *MaxExitCount = 7066 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 7067 return getConstantTripCount(MaxExitCount); 7068 } 7069 7070 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 7071 SmallVector<BasicBlock *, 8> ExitingBlocks; 7072 L->getExitingBlocks(ExitingBlocks); 7073 7074 Optional<unsigned> Res = None; 7075 for (auto *ExitingBB : ExitingBlocks) { 7076 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 7077 if (!Res) 7078 Res = Multiple; 7079 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 7080 } 7081 return Res.getValueOr(1); 7082 } 7083 7084 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7085 const SCEV *ExitCount) { 7086 if (ExitCount == getCouldNotCompute()) 7087 return 1; 7088 7089 // Get the trip count 7090 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7091 7092 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7093 if (!TC) 7094 // Attempt to factor more general cases. Returns the greatest power of 7095 // two divisor. If overflow happens, the trip count expression is still 7096 // divisible by the greatest power of 2 divisor returned. 7097 return 1U << std::min((uint32_t)31, 7098 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7099 7100 ConstantInt *Result = TC->getValue(); 7101 7102 // Guard against huge trip counts (this requires checking 7103 // for zero to handle the case where the trip count == -1 and the 7104 // addition wraps). 7105 if (!Result || Result->getValue().getActiveBits() > 32 || 7106 Result->getValue().getActiveBits() == 0) 7107 return 1; 7108 7109 return (unsigned)Result->getZExtValue(); 7110 } 7111 7112 /// Returns the largest constant divisor of the trip count of this loop as a 7113 /// normal unsigned value, if possible. This means that the actual trip count is 7114 /// always a multiple of the returned value (don't forget the trip count could 7115 /// very well be zero as well!). 7116 /// 7117 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7118 /// multiple of a constant (which is also the case if the trip count is simply 7119 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7120 /// if the trip count is very large (>= 2^32). 7121 /// 7122 /// As explained in the comments for getSmallConstantTripCount, this assumes 7123 /// that control exits the loop via ExitingBlock. 7124 unsigned 7125 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7126 const BasicBlock *ExitingBlock) { 7127 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7128 assert(L->isLoopExiting(ExitingBlock) && 7129 "Exiting block must actually branch out of the loop!"); 7130 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7131 return getSmallConstantTripMultiple(L, ExitCount); 7132 } 7133 7134 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7135 const BasicBlock *ExitingBlock, 7136 ExitCountKind Kind) { 7137 switch (Kind) { 7138 case Exact: 7139 case SymbolicMaximum: 7140 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7141 case ConstantMaximum: 7142 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7143 }; 7144 llvm_unreachable("Invalid ExitCountKind!"); 7145 } 7146 7147 const SCEV * 7148 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7149 SCEVUnionPredicate &Preds) { 7150 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7151 } 7152 7153 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7154 ExitCountKind Kind) { 7155 switch (Kind) { 7156 case Exact: 7157 return getBackedgeTakenInfo(L).getExact(L, this); 7158 case ConstantMaximum: 7159 return getBackedgeTakenInfo(L).getConstantMax(this); 7160 case SymbolicMaximum: 7161 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7162 }; 7163 llvm_unreachable("Invalid ExitCountKind!"); 7164 } 7165 7166 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7167 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7168 } 7169 7170 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7171 static void 7172 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 7173 BasicBlock *Header = L->getHeader(); 7174 7175 // Push all Loop-header PHIs onto the Worklist stack. 7176 for (PHINode &PN : Header->phis()) 7177 Worklist.push_back(&PN); 7178 } 7179 7180 const ScalarEvolution::BackedgeTakenInfo & 7181 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7182 auto &BTI = getBackedgeTakenInfo(L); 7183 if (BTI.hasFullInfo()) 7184 return BTI; 7185 7186 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7187 7188 if (!Pair.second) 7189 return Pair.first->second; 7190 7191 BackedgeTakenInfo Result = 7192 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7193 7194 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7195 } 7196 7197 ScalarEvolution::BackedgeTakenInfo & 7198 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7199 // Initially insert an invalid entry for this loop. If the insertion 7200 // succeeds, proceed to actually compute a backedge-taken count and 7201 // update the value. The temporary CouldNotCompute value tells SCEV 7202 // code elsewhere that it shouldn't attempt to request a new 7203 // backedge-taken count, which could result in infinite recursion. 7204 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7205 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7206 if (!Pair.second) 7207 return Pair.first->second; 7208 7209 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7210 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7211 // must be cleared in this scope. 7212 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7213 7214 // In product build, there are no usage of statistic. 7215 (void)NumTripCountsComputed; 7216 (void)NumTripCountsNotComputed; 7217 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7218 const SCEV *BEExact = Result.getExact(L, this); 7219 if (BEExact != getCouldNotCompute()) { 7220 assert(isLoopInvariant(BEExact, L) && 7221 isLoopInvariant(Result.getConstantMax(this), L) && 7222 "Computed backedge-taken count isn't loop invariant for loop!"); 7223 ++NumTripCountsComputed; 7224 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7225 isa<PHINode>(L->getHeader()->begin())) { 7226 // Only count loops that have phi nodes as not being computable. 7227 ++NumTripCountsNotComputed; 7228 } 7229 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7230 7231 // Now that we know more about the trip count for this loop, forget any 7232 // existing SCEV values for PHI nodes in this loop since they are only 7233 // conservative estimates made without the benefit of trip count 7234 // information. This is similar to the code in forgetLoop, except that 7235 // it handles SCEVUnknown PHI nodes specially. 7236 if (Result.hasAnyInfo()) { 7237 SmallVector<Instruction *, 16> Worklist; 7238 PushLoopPHIs(L, Worklist); 7239 7240 SmallPtrSet<Instruction *, 8> Discovered; 7241 while (!Worklist.empty()) { 7242 Instruction *I = Worklist.pop_back_val(); 7243 7244 ValueExprMapType::iterator It = 7245 ValueExprMap.find_as(static_cast<Value *>(I)); 7246 if (It != ValueExprMap.end()) { 7247 const SCEV *Old = It->second; 7248 7249 // SCEVUnknown for a PHI either means that it has an unrecognized 7250 // structure, or it's a PHI that's in the progress of being computed 7251 // by createNodeForPHI. In the former case, additional loop trip 7252 // count information isn't going to change anything. In the later 7253 // case, createNodeForPHI will perform the necessary updates on its 7254 // own when it gets to that point. 7255 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 7256 eraseValueFromMap(It->first); 7257 forgetMemoizedResults(Old); 7258 } 7259 if (PHINode *PN = dyn_cast<PHINode>(I)) 7260 ConstantEvolutionLoopExitValue.erase(PN); 7261 } 7262 7263 // Since we don't need to invalidate anything for correctness and we're 7264 // only invalidating to make SCEV's results more precise, we get to stop 7265 // early to avoid invalidating too much. This is especially important in 7266 // cases like: 7267 // 7268 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 7269 // loop0: 7270 // %pn0 = phi 7271 // ... 7272 // loop1: 7273 // %pn1 = phi 7274 // ... 7275 // 7276 // where both loop0 and loop1's backedge taken count uses the SCEV 7277 // expression for %v. If we don't have the early stop below then in cases 7278 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 7279 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 7280 // count for loop1, effectively nullifying SCEV's trip count cache. 7281 for (auto *U : I->users()) 7282 if (auto *I = dyn_cast<Instruction>(U)) { 7283 auto *LoopForUser = LI.getLoopFor(I->getParent()); 7284 if (LoopForUser && L->contains(LoopForUser) && 7285 Discovered.insert(I).second) 7286 Worklist.push_back(I); 7287 } 7288 } 7289 } 7290 7291 // Re-lookup the insert position, since the call to 7292 // computeBackedgeTakenCount above could result in a 7293 // recusive call to getBackedgeTakenInfo (on a different 7294 // loop), which would invalidate the iterator computed 7295 // earlier. 7296 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7297 } 7298 7299 void ScalarEvolution::forgetAllLoops() { 7300 // This method is intended to forget all info about loops. It should 7301 // invalidate caches as if the following happened: 7302 // - The trip counts of all loops have changed arbitrarily 7303 // - Every llvm::Value has been updated in place to produce a different 7304 // result. 7305 BackedgeTakenCounts.clear(); 7306 PredicatedBackedgeTakenCounts.clear(); 7307 LoopPropertiesCache.clear(); 7308 ConstantEvolutionLoopExitValue.clear(); 7309 ValueExprMap.clear(); 7310 ValuesAtScopes.clear(); 7311 LoopDispositions.clear(); 7312 BlockDispositions.clear(); 7313 UnsignedRanges.clear(); 7314 SignedRanges.clear(); 7315 ExprValueMap.clear(); 7316 HasRecMap.clear(); 7317 MinTrailingZerosCache.clear(); 7318 PredicatedSCEVRewrites.clear(); 7319 } 7320 7321 void ScalarEvolution::forgetLoop(const Loop *L) { 7322 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7323 SmallVector<Instruction *, 32> Worklist; 7324 SmallPtrSet<Instruction *, 16> Visited; 7325 7326 // Iterate over all the loops and sub-loops to drop SCEV information. 7327 while (!LoopWorklist.empty()) { 7328 auto *CurrL = LoopWorklist.pop_back_val(); 7329 7330 // Drop any stored trip count value. 7331 BackedgeTakenCounts.erase(CurrL); 7332 PredicatedBackedgeTakenCounts.erase(CurrL); 7333 7334 // Drop information about predicated SCEV rewrites for this loop. 7335 for (auto I = PredicatedSCEVRewrites.begin(); 7336 I != PredicatedSCEVRewrites.end();) { 7337 std::pair<const SCEV *, const Loop *> Entry = I->first; 7338 if (Entry.second == CurrL) 7339 PredicatedSCEVRewrites.erase(I++); 7340 else 7341 ++I; 7342 } 7343 7344 auto LoopUsersItr = LoopUsers.find(CurrL); 7345 if (LoopUsersItr != LoopUsers.end()) { 7346 for (auto *S : LoopUsersItr->second) 7347 forgetMemoizedResults(S); 7348 LoopUsers.erase(LoopUsersItr); 7349 } 7350 7351 // Drop information about expressions based on loop-header PHIs. 7352 PushLoopPHIs(CurrL, Worklist); 7353 7354 while (!Worklist.empty()) { 7355 Instruction *I = Worklist.pop_back_val(); 7356 if (!Visited.insert(I).second) 7357 continue; 7358 7359 ValueExprMapType::iterator It = 7360 ValueExprMap.find_as(static_cast<Value *>(I)); 7361 if (It != ValueExprMap.end()) { 7362 eraseValueFromMap(It->first); 7363 forgetMemoizedResults(It->second); 7364 if (PHINode *PN = dyn_cast<PHINode>(I)) 7365 ConstantEvolutionLoopExitValue.erase(PN); 7366 } 7367 7368 PushDefUseChildren(I, Worklist); 7369 } 7370 7371 LoopPropertiesCache.erase(CurrL); 7372 // Forget all contained loops too, to avoid dangling entries in the 7373 // ValuesAtScopes map. 7374 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7375 } 7376 } 7377 7378 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7379 while (Loop *Parent = L->getParentLoop()) 7380 L = Parent; 7381 forgetLoop(L); 7382 } 7383 7384 void ScalarEvolution::forgetValue(Value *V) { 7385 Instruction *I = dyn_cast<Instruction>(V); 7386 if (!I) return; 7387 7388 // Drop information about expressions based on loop-header PHIs. 7389 SmallVector<Instruction *, 16> Worklist; 7390 Worklist.push_back(I); 7391 7392 SmallPtrSet<Instruction *, 8> Visited; 7393 while (!Worklist.empty()) { 7394 I = Worklist.pop_back_val(); 7395 if (!Visited.insert(I).second) 7396 continue; 7397 7398 ValueExprMapType::iterator It = 7399 ValueExprMap.find_as(static_cast<Value *>(I)); 7400 if (It != ValueExprMap.end()) { 7401 eraseValueFromMap(It->first); 7402 forgetMemoizedResults(It->second); 7403 if (PHINode *PN = dyn_cast<PHINode>(I)) 7404 ConstantEvolutionLoopExitValue.erase(PN); 7405 } 7406 7407 PushDefUseChildren(I, Worklist); 7408 } 7409 } 7410 7411 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7412 LoopDispositions.clear(); 7413 } 7414 7415 /// Get the exact loop backedge taken count considering all loop exits. A 7416 /// computable result can only be returned for loops with all exiting blocks 7417 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7418 /// is never skipped. This is a valid assumption as long as the loop exits via 7419 /// that test. For precise results, it is the caller's responsibility to specify 7420 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7421 const SCEV * 7422 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7423 SCEVUnionPredicate *Preds) const { 7424 // If any exits were not computable, the loop is not computable. 7425 if (!isComplete() || ExitNotTaken.empty()) 7426 return SE->getCouldNotCompute(); 7427 7428 const BasicBlock *Latch = L->getLoopLatch(); 7429 // All exiting blocks we have collected must dominate the only backedge. 7430 if (!Latch) 7431 return SE->getCouldNotCompute(); 7432 7433 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7434 // count is simply a minimum out of all these calculated exit counts. 7435 SmallVector<const SCEV *, 2> Ops; 7436 for (auto &ENT : ExitNotTaken) { 7437 const SCEV *BECount = ENT.ExactNotTaken; 7438 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7439 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7440 "We should only have known counts for exiting blocks that dominate " 7441 "latch!"); 7442 7443 Ops.push_back(BECount); 7444 7445 if (Preds && !ENT.hasAlwaysTruePredicate()) 7446 Preds->add(ENT.Predicate.get()); 7447 7448 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7449 "Predicate should be always true!"); 7450 } 7451 7452 return SE->getUMinFromMismatchedTypes(Ops); 7453 } 7454 7455 /// Get the exact not taken count for this loop exit. 7456 const SCEV * 7457 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7458 ScalarEvolution *SE) const { 7459 for (auto &ENT : ExitNotTaken) 7460 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7461 return ENT.ExactNotTaken; 7462 7463 return SE->getCouldNotCompute(); 7464 } 7465 7466 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7467 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7468 for (auto &ENT : ExitNotTaken) 7469 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7470 return ENT.MaxNotTaken; 7471 7472 return SE->getCouldNotCompute(); 7473 } 7474 7475 /// getConstantMax - Get the constant max backedge taken count for the loop. 7476 const SCEV * 7477 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7478 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7479 return !ENT.hasAlwaysTruePredicate(); 7480 }; 7481 7482 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax()) 7483 return SE->getCouldNotCompute(); 7484 7485 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7486 isa<SCEVConstant>(getConstantMax())) && 7487 "No point in having a non-constant max backedge taken count!"); 7488 return getConstantMax(); 7489 } 7490 7491 const SCEV * 7492 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 7493 ScalarEvolution *SE) { 7494 if (!SymbolicMax) 7495 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 7496 return SymbolicMax; 7497 } 7498 7499 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 7500 ScalarEvolution *SE) const { 7501 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7502 return !ENT.hasAlwaysTruePredicate(); 7503 }; 7504 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7505 } 7506 7507 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const { 7508 return Operands.contains(S); 7509 } 7510 7511 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7512 : ExactNotTaken(E), MaxNotTaken(E) { 7513 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7514 isa<SCEVConstant>(MaxNotTaken)) && 7515 "No point in having a non-constant max backedge taken count!"); 7516 } 7517 7518 ScalarEvolution::ExitLimit::ExitLimit( 7519 const SCEV *E, const SCEV *M, bool MaxOrZero, 7520 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7521 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7522 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7523 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7524 "Exact is not allowed to be less precise than Max"); 7525 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7526 isa<SCEVConstant>(MaxNotTaken)) && 7527 "No point in having a non-constant max backedge taken count!"); 7528 for (auto *PredSet : PredSetList) 7529 for (auto *P : *PredSet) 7530 addPredicate(P); 7531 } 7532 7533 ScalarEvolution::ExitLimit::ExitLimit( 7534 const SCEV *E, const SCEV *M, bool MaxOrZero, 7535 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7536 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7537 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7538 isa<SCEVConstant>(MaxNotTaken)) && 7539 "No point in having a non-constant max backedge taken count!"); 7540 } 7541 7542 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7543 bool MaxOrZero) 7544 : ExitLimit(E, M, MaxOrZero, None) { 7545 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7546 isa<SCEVConstant>(MaxNotTaken)) && 7547 "No point in having a non-constant max backedge taken count!"); 7548 } 7549 7550 class SCEVRecordOperands { 7551 SmallPtrSetImpl<const SCEV *> &Operands; 7552 7553 public: 7554 SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands) 7555 : Operands(Operands) {} 7556 bool follow(const SCEV *S) { 7557 Operands.insert(S); 7558 return true; 7559 } 7560 bool isDone() { return false; } 7561 }; 7562 7563 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7564 /// computable exit into a persistent ExitNotTakenInfo array. 7565 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7566 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 7567 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 7568 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 7569 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7570 7571 ExitNotTaken.reserve(ExitCounts.size()); 7572 std::transform( 7573 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7574 [&](const EdgeExitInfo &EEI) { 7575 BasicBlock *ExitBB = EEI.first; 7576 const ExitLimit &EL = EEI.second; 7577 if (EL.Predicates.empty()) 7578 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7579 nullptr); 7580 7581 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7582 for (auto *Pred : EL.Predicates) 7583 Predicate->add(Pred); 7584 7585 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7586 std::move(Predicate)); 7587 }); 7588 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 7589 isa<SCEVConstant>(ConstantMax)) && 7590 "No point in having a non-constant max backedge taken count!"); 7591 7592 SCEVRecordOperands RecordOperands(Operands); 7593 SCEVTraversal<SCEVRecordOperands> ST(RecordOperands); 7594 if (!isa<SCEVCouldNotCompute>(ConstantMax)) 7595 ST.visitAll(ConstantMax); 7596 for (auto &ENT : ExitNotTaken) 7597 if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken)) 7598 ST.visitAll(ENT.ExactNotTaken); 7599 } 7600 7601 /// Compute the number of times the backedge of the specified loop will execute. 7602 ScalarEvolution::BackedgeTakenInfo 7603 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7604 bool AllowPredicates) { 7605 SmallVector<BasicBlock *, 8> ExitingBlocks; 7606 L->getExitingBlocks(ExitingBlocks); 7607 7608 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7609 7610 SmallVector<EdgeExitInfo, 4> ExitCounts; 7611 bool CouldComputeBECount = true; 7612 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7613 const SCEV *MustExitMaxBECount = nullptr; 7614 const SCEV *MayExitMaxBECount = nullptr; 7615 bool MustExitMaxOrZero = false; 7616 7617 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7618 // and compute maxBECount. 7619 // Do a union of all the predicates here. 7620 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7621 BasicBlock *ExitBB = ExitingBlocks[i]; 7622 7623 // We canonicalize untaken exits to br (constant), ignore them so that 7624 // proving an exit untaken doesn't negatively impact our ability to reason 7625 // about the loop as whole. 7626 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7627 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7628 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7629 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7630 continue; 7631 } 7632 7633 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7634 7635 assert((AllowPredicates || EL.Predicates.empty()) && 7636 "Predicated exit limit when predicates are not allowed!"); 7637 7638 // 1. For each exit that can be computed, add an entry to ExitCounts. 7639 // CouldComputeBECount is true only if all exits can be computed. 7640 if (EL.ExactNotTaken == getCouldNotCompute()) 7641 // We couldn't compute an exact value for this exit, so 7642 // we won't be able to compute an exact value for the loop. 7643 CouldComputeBECount = false; 7644 else 7645 ExitCounts.emplace_back(ExitBB, EL); 7646 7647 // 2. Derive the loop's MaxBECount from each exit's max number of 7648 // non-exiting iterations. Partition the loop exits into two kinds: 7649 // LoopMustExits and LoopMayExits. 7650 // 7651 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7652 // is a LoopMayExit. If any computable LoopMustExit is found, then 7653 // MaxBECount is the minimum EL.MaxNotTaken of computable 7654 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7655 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7656 // computable EL.MaxNotTaken. 7657 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7658 DT.dominates(ExitBB, Latch)) { 7659 if (!MustExitMaxBECount) { 7660 MustExitMaxBECount = EL.MaxNotTaken; 7661 MustExitMaxOrZero = EL.MaxOrZero; 7662 } else { 7663 MustExitMaxBECount = 7664 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7665 } 7666 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7667 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7668 MayExitMaxBECount = EL.MaxNotTaken; 7669 else { 7670 MayExitMaxBECount = 7671 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7672 } 7673 } 7674 } 7675 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7676 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7677 // The loop backedge will be taken the maximum or zero times if there's 7678 // a single exit that must be taken the maximum or zero times. 7679 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7680 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7681 MaxBECount, MaxOrZero); 7682 } 7683 7684 ScalarEvolution::ExitLimit 7685 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7686 bool AllowPredicates) { 7687 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7688 // If our exiting block does not dominate the latch, then its connection with 7689 // loop's exit limit may be far from trivial. 7690 const BasicBlock *Latch = L->getLoopLatch(); 7691 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7692 return getCouldNotCompute(); 7693 7694 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7695 Instruction *Term = ExitingBlock->getTerminator(); 7696 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7697 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7698 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7699 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7700 "It should have one successor in loop and one exit block!"); 7701 // Proceed to the next level to examine the exit condition expression. 7702 return computeExitLimitFromCond( 7703 L, BI->getCondition(), ExitIfTrue, 7704 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7705 } 7706 7707 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7708 // For switch, make sure that there is a single exit from the loop. 7709 BasicBlock *Exit = nullptr; 7710 for (auto *SBB : successors(ExitingBlock)) 7711 if (!L->contains(SBB)) { 7712 if (Exit) // Multiple exit successors. 7713 return getCouldNotCompute(); 7714 Exit = SBB; 7715 } 7716 assert(Exit && "Exiting block must have at least one exit"); 7717 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7718 /*ControlsExit=*/IsOnlyExit); 7719 } 7720 7721 return getCouldNotCompute(); 7722 } 7723 7724 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7725 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7726 bool ControlsExit, bool AllowPredicates) { 7727 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7728 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7729 ControlsExit, AllowPredicates); 7730 } 7731 7732 Optional<ScalarEvolution::ExitLimit> 7733 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7734 bool ExitIfTrue, bool ControlsExit, 7735 bool AllowPredicates) { 7736 (void)this->L; 7737 (void)this->ExitIfTrue; 7738 (void)this->AllowPredicates; 7739 7740 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7741 this->AllowPredicates == AllowPredicates && 7742 "Variance in assumed invariant key components!"); 7743 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7744 if (Itr == TripCountMap.end()) 7745 return None; 7746 return Itr->second; 7747 } 7748 7749 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7750 bool ExitIfTrue, 7751 bool ControlsExit, 7752 bool AllowPredicates, 7753 const ExitLimit &EL) { 7754 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7755 this->AllowPredicates == AllowPredicates && 7756 "Variance in assumed invariant key components!"); 7757 7758 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7759 assert(InsertResult.second && "Expected successful insertion!"); 7760 (void)InsertResult; 7761 (void)ExitIfTrue; 7762 } 7763 7764 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7765 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7766 bool ControlsExit, bool AllowPredicates) { 7767 7768 if (auto MaybeEL = 7769 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7770 return *MaybeEL; 7771 7772 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7773 ControlsExit, AllowPredicates); 7774 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7775 return EL; 7776 } 7777 7778 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7779 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7780 bool ControlsExit, bool AllowPredicates) { 7781 // Handle BinOp conditions (And, Or). 7782 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 7783 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7784 return *LimitFromBinOp; 7785 7786 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7787 // Proceed to the next level to examine the icmp. 7788 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7789 ExitLimit EL = 7790 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7791 if (EL.hasFullInfo() || !AllowPredicates) 7792 return EL; 7793 7794 // Try again, but use SCEV predicates this time. 7795 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7796 /*AllowPredicates=*/true); 7797 } 7798 7799 // Check for a constant condition. These are normally stripped out by 7800 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7801 // preserve the CFG and is temporarily leaving constant conditions 7802 // in place. 7803 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7804 if (ExitIfTrue == !CI->getZExtValue()) 7805 // The backedge is always taken. 7806 return getCouldNotCompute(); 7807 else 7808 // The backedge is never taken. 7809 return getZero(CI->getType()); 7810 } 7811 7812 // If it's not an integer or pointer comparison then compute it the hard way. 7813 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7814 } 7815 7816 Optional<ScalarEvolution::ExitLimit> 7817 ScalarEvolution::computeExitLimitFromCondFromBinOp( 7818 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7819 bool ControlsExit, bool AllowPredicates) { 7820 // Check if the controlling expression for this loop is an And or Or. 7821 Value *Op0, *Op1; 7822 bool IsAnd = false; 7823 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 7824 IsAnd = true; 7825 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 7826 IsAnd = false; 7827 else 7828 return None; 7829 7830 // EitherMayExit is true in these two cases: 7831 // br (and Op0 Op1), loop, exit 7832 // br (or Op0 Op1), exit, loop 7833 bool EitherMayExit = IsAnd ^ ExitIfTrue; 7834 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 7835 ControlsExit && !EitherMayExit, 7836 AllowPredicates); 7837 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 7838 ControlsExit && !EitherMayExit, 7839 AllowPredicates); 7840 7841 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 7842 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 7843 if (isa<ConstantInt>(Op1)) 7844 return Op1 == NeutralElement ? EL0 : EL1; 7845 if (isa<ConstantInt>(Op0)) 7846 return Op0 == NeutralElement ? EL1 : EL0; 7847 7848 const SCEV *BECount = getCouldNotCompute(); 7849 const SCEV *MaxBECount = getCouldNotCompute(); 7850 if (EitherMayExit) { 7851 // Both conditions must be same for the loop to continue executing. 7852 // Choose the less conservative count. 7853 // If ExitCond is a short-circuit form (select), using 7854 // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general. 7855 // To see the detailed examples, please see 7856 // test/Analysis/ScalarEvolution/exit-count-select.ll 7857 bool PoisonSafe = isa<BinaryOperator>(ExitCond); 7858 if (!PoisonSafe) 7859 // Even if ExitCond is select, we can safely derive BECount using both 7860 // EL0 and EL1 in these cases: 7861 // (1) EL0.ExactNotTaken is non-zero 7862 // (2) EL1.ExactNotTaken is non-poison 7863 // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and 7864 // it cannot be umin(0, ..)) 7865 // The PoisonSafe assignment below is simplified and the assertion after 7866 // BECount calculation fully guarantees the condition (3). 7867 PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) || 7868 isa<SCEVConstant>(EL1.ExactNotTaken); 7869 if (EL0.ExactNotTaken != getCouldNotCompute() && 7870 EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) { 7871 BECount = 7872 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7873 7874 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 7875 // it should have been simplified to zero (see the condition (3) above) 7876 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 7877 BECount->isZero()); 7878 } 7879 if (EL0.MaxNotTaken == getCouldNotCompute()) 7880 MaxBECount = EL1.MaxNotTaken; 7881 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7882 MaxBECount = EL0.MaxNotTaken; 7883 else 7884 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7885 } else { 7886 // Both conditions must be same at the same time for the loop to exit. 7887 // For now, be conservative. 7888 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7889 BECount = EL0.ExactNotTaken; 7890 } 7891 7892 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7893 // to be more aggressive when computing BECount than when computing 7894 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7895 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7896 // to not. 7897 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7898 !isa<SCEVCouldNotCompute>(BECount)) 7899 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7900 7901 return ExitLimit(BECount, MaxBECount, false, 7902 { &EL0.Predicates, &EL1.Predicates }); 7903 } 7904 7905 ScalarEvolution::ExitLimit 7906 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7907 ICmpInst *ExitCond, 7908 bool ExitIfTrue, 7909 bool ControlsExit, 7910 bool AllowPredicates) { 7911 // If the condition was exit on true, convert the condition to exit on false 7912 ICmpInst::Predicate Pred; 7913 if (!ExitIfTrue) 7914 Pred = ExitCond->getPredicate(); 7915 else 7916 Pred = ExitCond->getInversePredicate(); 7917 const ICmpInst::Predicate OriginalPred = Pred; 7918 7919 // Handle common loops like: for (X = "string"; *X; ++X) 7920 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7921 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7922 ExitLimit ItCnt = 7923 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7924 if (ItCnt.hasAnyInfo()) 7925 return ItCnt; 7926 } 7927 7928 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7929 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7930 7931 // Try to evaluate any dependencies out of the loop. 7932 LHS = getSCEVAtScope(LHS, L); 7933 RHS = getSCEVAtScope(RHS, L); 7934 7935 // At this point, we would like to compute how many iterations of the 7936 // loop the predicate will return true for these inputs. 7937 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7938 // If there is a loop-invariant, force it into the RHS. 7939 std::swap(LHS, RHS); 7940 Pred = ICmpInst::getSwappedPredicate(Pred); 7941 } 7942 7943 // Simplify the operands before analyzing them. 7944 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7945 7946 // If we have a comparison of a chrec against a constant, try to use value 7947 // ranges to answer this query. 7948 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7949 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7950 if (AddRec->getLoop() == L) { 7951 // Form the constant range. 7952 ConstantRange CompRange = 7953 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7954 7955 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7956 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7957 } 7958 7959 switch (Pred) { 7960 case ICmpInst::ICMP_NE: { // while (X != Y) 7961 // Convert to: while (X-Y != 0) 7962 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7963 AllowPredicates); 7964 if (EL.hasAnyInfo()) return EL; 7965 break; 7966 } 7967 case ICmpInst::ICMP_EQ: { // while (X == Y) 7968 // Convert to: while (X-Y == 0) 7969 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7970 if (EL.hasAnyInfo()) return EL; 7971 break; 7972 } 7973 case ICmpInst::ICMP_SLT: 7974 case ICmpInst::ICMP_ULT: { // while (X < Y) 7975 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7976 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7977 AllowPredicates); 7978 if (EL.hasAnyInfo()) return EL; 7979 break; 7980 } 7981 case ICmpInst::ICMP_SGT: 7982 case ICmpInst::ICMP_UGT: { // while (X > Y) 7983 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7984 ExitLimit EL = 7985 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7986 AllowPredicates); 7987 if (EL.hasAnyInfo()) return EL; 7988 break; 7989 } 7990 default: 7991 break; 7992 } 7993 7994 auto *ExhaustiveCount = 7995 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7996 7997 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7998 return ExhaustiveCount; 7999 8000 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 8001 ExitCond->getOperand(1), L, OriginalPred); 8002 } 8003 8004 ScalarEvolution::ExitLimit 8005 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 8006 SwitchInst *Switch, 8007 BasicBlock *ExitingBlock, 8008 bool ControlsExit) { 8009 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 8010 8011 // Give up if the exit is the default dest of a switch. 8012 if (Switch->getDefaultDest() == ExitingBlock) 8013 return getCouldNotCompute(); 8014 8015 assert(L->contains(Switch->getDefaultDest()) && 8016 "Default case must not exit the loop!"); 8017 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 8018 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 8019 8020 // while (X != Y) --> while (X-Y != 0) 8021 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 8022 if (EL.hasAnyInfo()) 8023 return EL; 8024 8025 return getCouldNotCompute(); 8026 } 8027 8028 static ConstantInt * 8029 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 8030 ScalarEvolution &SE) { 8031 const SCEV *InVal = SE.getConstant(C); 8032 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 8033 assert(isa<SCEVConstant>(Val) && 8034 "Evaluation of SCEV at constant didn't fold correctly?"); 8035 return cast<SCEVConstant>(Val)->getValue(); 8036 } 8037 8038 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 8039 /// compute the backedge execution count. 8040 ScalarEvolution::ExitLimit 8041 ScalarEvolution::computeLoadConstantCompareExitLimit( 8042 LoadInst *LI, 8043 Constant *RHS, 8044 const Loop *L, 8045 ICmpInst::Predicate predicate) { 8046 if (LI->isVolatile()) return getCouldNotCompute(); 8047 8048 // Check to see if the loaded pointer is a getelementptr of a global. 8049 // TODO: Use SCEV instead of manually grubbing with GEPs. 8050 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 8051 if (!GEP) return getCouldNotCompute(); 8052 8053 // Make sure that it is really a constant global we are gepping, with an 8054 // initializer, and make sure the first IDX is really 0. 8055 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 8056 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 8057 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 8058 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 8059 return getCouldNotCompute(); 8060 8061 // Okay, we allow one non-constant index into the GEP instruction. 8062 Value *VarIdx = nullptr; 8063 std::vector<Constant*> Indexes; 8064 unsigned VarIdxNum = 0; 8065 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 8066 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 8067 Indexes.push_back(CI); 8068 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 8069 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 8070 VarIdx = GEP->getOperand(i); 8071 VarIdxNum = i-2; 8072 Indexes.push_back(nullptr); 8073 } 8074 8075 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 8076 if (!VarIdx) 8077 return getCouldNotCompute(); 8078 8079 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 8080 // Check to see if X is a loop variant variable value now. 8081 const SCEV *Idx = getSCEV(VarIdx); 8082 Idx = getSCEVAtScope(Idx, L); 8083 8084 // We can only recognize very limited forms of loop index expressions, in 8085 // particular, only affine AddRec's like {C1,+,C2}<L>. 8086 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 8087 if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() || 8088 isLoopInvariant(IdxExpr, L) || 8089 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 8090 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 8091 return getCouldNotCompute(); 8092 8093 unsigned MaxSteps = MaxBruteForceIterations; 8094 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 8095 ConstantInt *ItCst = ConstantInt::get( 8096 cast<IntegerType>(IdxExpr->getType()), IterationNum); 8097 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 8098 8099 // Form the GEP offset. 8100 Indexes[VarIdxNum] = Val; 8101 8102 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 8103 Indexes); 8104 if (!Result) break; // Cannot compute! 8105 8106 // Evaluate the condition for this iteration. 8107 Result = ConstantExpr::getICmp(predicate, Result, RHS); 8108 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 8109 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 8110 ++NumArrayLenItCounts; 8111 return getConstant(ItCst); // Found terminating iteration! 8112 } 8113 } 8114 return getCouldNotCompute(); 8115 } 8116 8117 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8118 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8119 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8120 if (!RHS) 8121 return getCouldNotCompute(); 8122 8123 const BasicBlock *Latch = L->getLoopLatch(); 8124 if (!Latch) 8125 return getCouldNotCompute(); 8126 8127 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8128 if (!Predecessor) 8129 return getCouldNotCompute(); 8130 8131 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8132 // Return LHS in OutLHS and shift_opt in OutOpCode. 8133 auto MatchPositiveShift = 8134 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8135 8136 using namespace PatternMatch; 8137 8138 ConstantInt *ShiftAmt; 8139 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8140 OutOpCode = Instruction::LShr; 8141 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8142 OutOpCode = Instruction::AShr; 8143 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8144 OutOpCode = Instruction::Shl; 8145 else 8146 return false; 8147 8148 return ShiftAmt->getValue().isStrictlyPositive(); 8149 }; 8150 8151 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8152 // 8153 // loop: 8154 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8155 // %iv.shifted = lshr i32 %iv, <positive constant> 8156 // 8157 // Return true on a successful match. Return the corresponding PHI node (%iv 8158 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8159 auto MatchShiftRecurrence = 8160 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8161 Optional<Instruction::BinaryOps> PostShiftOpCode; 8162 8163 { 8164 Instruction::BinaryOps OpC; 8165 Value *V; 8166 8167 // If we encounter a shift instruction, "peel off" the shift operation, 8168 // and remember that we did so. Later when we inspect %iv's backedge 8169 // value, we will make sure that the backedge value uses the same 8170 // operation. 8171 // 8172 // Note: the peeled shift operation does not have to be the same 8173 // instruction as the one feeding into the PHI's backedge value. We only 8174 // really care about it being the same *kind* of shift instruction -- 8175 // that's all that is required for our later inferences to hold. 8176 if (MatchPositiveShift(LHS, V, OpC)) { 8177 PostShiftOpCode = OpC; 8178 LHS = V; 8179 } 8180 } 8181 8182 PNOut = dyn_cast<PHINode>(LHS); 8183 if (!PNOut || PNOut->getParent() != L->getHeader()) 8184 return false; 8185 8186 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8187 Value *OpLHS; 8188 8189 return 8190 // The backedge value for the PHI node must be a shift by a positive 8191 // amount 8192 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8193 8194 // of the PHI node itself 8195 OpLHS == PNOut && 8196 8197 // and the kind of shift should be match the kind of shift we peeled 8198 // off, if any. 8199 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8200 }; 8201 8202 PHINode *PN; 8203 Instruction::BinaryOps OpCode; 8204 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8205 return getCouldNotCompute(); 8206 8207 const DataLayout &DL = getDataLayout(); 8208 8209 // The key rationale for this optimization is that for some kinds of shift 8210 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8211 // within a finite number of iterations. If the condition guarding the 8212 // backedge (in the sense that the backedge is taken if the condition is true) 8213 // is false for the value the shift recurrence stabilizes to, then we know 8214 // that the backedge is taken only a finite number of times. 8215 8216 ConstantInt *StableValue = nullptr; 8217 switch (OpCode) { 8218 default: 8219 llvm_unreachable("Impossible case!"); 8220 8221 case Instruction::AShr: { 8222 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8223 // bitwidth(K) iterations. 8224 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8225 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8226 Predecessor->getTerminator(), &DT); 8227 auto *Ty = cast<IntegerType>(RHS->getType()); 8228 if (Known.isNonNegative()) 8229 StableValue = ConstantInt::get(Ty, 0); 8230 else if (Known.isNegative()) 8231 StableValue = ConstantInt::get(Ty, -1, true); 8232 else 8233 return getCouldNotCompute(); 8234 8235 break; 8236 } 8237 case Instruction::LShr: 8238 case Instruction::Shl: 8239 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8240 // stabilize to 0 in at most bitwidth(K) iterations. 8241 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8242 break; 8243 } 8244 8245 auto *Result = 8246 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8247 assert(Result->getType()->isIntegerTy(1) && 8248 "Otherwise cannot be an operand to a branch instruction"); 8249 8250 if (Result->isZeroValue()) { 8251 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8252 const SCEV *UpperBound = 8253 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8254 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8255 } 8256 8257 return getCouldNotCompute(); 8258 } 8259 8260 /// Return true if we can constant fold an instruction of the specified type, 8261 /// assuming that all operands were constants. 8262 static bool CanConstantFold(const Instruction *I) { 8263 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8264 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8265 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8266 return true; 8267 8268 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8269 if (const Function *F = CI->getCalledFunction()) 8270 return canConstantFoldCallTo(CI, F); 8271 return false; 8272 } 8273 8274 /// Determine whether this instruction can constant evolve within this loop 8275 /// assuming its operands can all constant evolve. 8276 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8277 // An instruction outside of the loop can't be derived from a loop PHI. 8278 if (!L->contains(I)) return false; 8279 8280 if (isa<PHINode>(I)) { 8281 // We don't currently keep track of the control flow needed to evaluate 8282 // PHIs, so we cannot handle PHIs inside of loops. 8283 return L->getHeader() == I->getParent(); 8284 } 8285 8286 // If we won't be able to constant fold this expression even if the operands 8287 // are constants, bail early. 8288 return CanConstantFold(I); 8289 } 8290 8291 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8292 /// recursing through each instruction operand until reaching a loop header phi. 8293 static PHINode * 8294 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8295 DenseMap<Instruction *, PHINode *> &PHIMap, 8296 unsigned Depth) { 8297 if (Depth > MaxConstantEvolvingDepth) 8298 return nullptr; 8299 8300 // Otherwise, we can evaluate this instruction if all of its operands are 8301 // constant or derived from a PHI node themselves. 8302 PHINode *PHI = nullptr; 8303 for (Value *Op : UseInst->operands()) { 8304 if (isa<Constant>(Op)) continue; 8305 8306 Instruction *OpInst = dyn_cast<Instruction>(Op); 8307 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8308 8309 PHINode *P = dyn_cast<PHINode>(OpInst); 8310 if (!P) 8311 // If this operand is already visited, reuse the prior result. 8312 // We may have P != PHI if this is the deepest point at which the 8313 // inconsistent paths meet. 8314 P = PHIMap.lookup(OpInst); 8315 if (!P) { 8316 // Recurse and memoize the results, whether a phi is found or not. 8317 // This recursive call invalidates pointers into PHIMap. 8318 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8319 PHIMap[OpInst] = P; 8320 } 8321 if (!P) 8322 return nullptr; // Not evolving from PHI 8323 if (PHI && PHI != P) 8324 return nullptr; // Evolving from multiple different PHIs. 8325 PHI = P; 8326 } 8327 // This is a expression evolving from a constant PHI! 8328 return PHI; 8329 } 8330 8331 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8332 /// in the loop that V is derived from. We allow arbitrary operations along the 8333 /// way, but the operands of an operation must either be constants or a value 8334 /// derived from a constant PHI. If this expression does not fit with these 8335 /// constraints, return null. 8336 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8337 Instruction *I = dyn_cast<Instruction>(V); 8338 if (!I || !canConstantEvolve(I, L)) return nullptr; 8339 8340 if (PHINode *PN = dyn_cast<PHINode>(I)) 8341 return PN; 8342 8343 // Record non-constant instructions contained by the loop. 8344 DenseMap<Instruction *, PHINode *> PHIMap; 8345 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8346 } 8347 8348 /// EvaluateExpression - Given an expression that passes the 8349 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8350 /// in the loop has the value PHIVal. If we can't fold this expression for some 8351 /// reason, return null. 8352 static Constant *EvaluateExpression(Value *V, const Loop *L, 8353 DenseMap<Instruction *, Constant *> &Vals, 8354 const DataLayout &DL, 8355 const TargetLibraryInfo *TLI) { 8356 // Convenient constant check, but redundant for recursive calls. 8357 if (Constant *C = dyn_cast<Constant>(V)) return C; 8358 Instruction *I = dyn_cast<Instruction>(V); 8359 if (!I) return nullptr; 8360 8361 if (Constant *C = Vals.lookup(I)) return C; 8362 8363 // An instruction inside the loop depends on a value outside the loop that we 8364 // weren't given a mapping for, or a value such as a call inside the loop. 8365 if (!canConstantEvolve(I, L)) return nullptr; 8366 8367 // An unmapped PHI can be due to a branch or another loop inside this loop, 8368 // or due to this not being the initial iteration through a loop where we 8369 // couldn't compute the evolution of this particular PHI last time. 8370 if (isa<PHINode>(I)) return nullptr; 8371 8372 std::vector<Constant*> Operands(I->getNumOperands()); 8373 8374 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8375 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8376 if (!Operand) { 8377 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8378 if (!Operands[i]) return nullptr; 8379 continue; 8380 } 8381 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8382 Vals[Operand] = C; 8383 if (!C) return nullptr; 8384 Operands[i] = C; 8385 } 8386 8387 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8388 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8389 Operands[1], DL, TLI); 8390 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8391 if (!LI->isVolatile()) 8392 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8393 } 8394 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8395 } 8396 8397 8398 // If every incoming value to PN except the one for BB is a specific Constant, 8399 // return that, else return nullptr. 8400 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8401 Constant *IncomingVal = nullptr; 8402 8403 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8404 if (PN->getIncomingBlock(i) == BB) 8405 continue; 8406 8407 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8408 if (!CurrentVal) 8409 return nullptr; 8410 8411 if (IncomingVal != CurrentVal) { 8412 if (IncomingVal) 8413 return nullptr; 8414 IncomingVal = CurrentVal; 8415 } 8416 } 8417 8418 return IncomingVal; 8419 } 8420 8421 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8422 /// in the header of its containing loop, we know the loop executes a 8423 /// constant number of times, and the PHI node is just a recurrence 8424 /// involving constants, fold it. 8425 Constant * 8426 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8427 const APInt &BEs, 8428 const Loop *L) { 8429 auto I = ConstantEvolutionLoopExitValue.find(PN); 8430 if (I != ConstantEvolutionLoopExitValue.end()) 8431 return I->second; 8432 8433 if (BEs.ugt(MaxBruteForceIterations)) 8434 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8435 8436 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8437 8438 DenseMap<Instruction *, Constant *> CurrentIterVals; 8439 BasicBlock *Header = L->getHeader(); 8440 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8441 8442 BasicBlock *Latch = L->getLoopLatch(); 8443 if (!Latch) 8444 return nullptr; 8445 8446 for (PHINode &PHI : Header->phis()) { 8447 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8448 CurrentIterVals[&PHI] = StartCST; 8449 } 8450 if (!CurrentIterVals.count(PN)) 8451 return RetVal = nullptr; 8452 8453 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8454 8455 // Execute the loop symbolically to determine the exit value. 8456 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8457 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8458 8459 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8460 unsigned IterationNum = 0; 8461 const DataLayout &DL = getDataLayout(); 8462 for (; ; ++IterationNum) { 8463 if (IterationNum == NumIterations) 8464 return RetVal = CurrentIterVals[PN]; // Got exit value! 8465 8466 // Compute the value of the PHIs for the next iteration. 8467 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8468 DenseMap<Instruction *, Constant *> NextIterVals; 8469 Constant *NextPHI = 8470 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8471 if (!NextPHI) 8472 return nullptr; // Couldn't evaluate! 8473 NextIterVals[PN] = NextPHI; 8474 8475 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8476 8477 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8478 // cease to be able to evaluate one of them or if they stop evolving, 8479 // because that doesn't necessarily prevent us from computing PN. 8480 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8481 for (const auto &I : CurrentIterVals) { 8482 PHINode *PHI = dyn_cast<PHINode>(I.first); 8483 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8484 PHIsToCompute.emplace_back(PHI, I.second); 8485 } 8486 // We use two distinct loops because EvaluateExpression may invalidate any 8487 // iterators into CurrentIterVals. 8488 for (const auto &I : PHIsToCompute) { 8489 PHINode *PHI = I.first; 8490 Constant *&NextPHI = NextIterVals[PHI]; 8491 if (!NextPHI) { // Not already computed. 8492 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8493 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8494 } 8495 if (NextPHI != I.second) 8496 StoppedEvolving = false; 8497 } 8498 8499 // If all entries in CurrentIterVals == NextIterVals then we can stop 8500 // iterating, the loop can't continue to change. 8501 if (StoppedEvolving) 8502 return RetVal = CurrentIterVals[PN]; 8503 8504 CurrentIterVals.swap(NextIterVals); 8505 } 8506 } 8507 8508 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8509 Value *Cond, 8510 bool ExitWhen) { 8511 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8512 if (!PN) return getCouldNotCompute(); 8513 8514 // If the loop is canonicalized, the PHI will have exactly two entries. 8515 // That's the only form we support here. 8516 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8517 8518 DenseMap<Instruction *, Constant *> CurrentIterVals; 8519 BasicBlock *Header = L->getHeader(); 8520 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8521 8522 BasicBlock *Latch = L->getLoopLatch(); 8523 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8524 8525 for (PHINode &PHI : Header->phis()) { 8526 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8527 CurrentIterVals[&PHI] = StartCST; 8528 } 8529 if (!CurrentIterVals.count(PN)) 8530 return getCouldNotCompute(); 8531 8532 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8533 // the loop symbolically to determine when the condition gets a value of 8534 // "ExitWhen". 8535 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8536 const DataLayout &DL = getDataLayout(); 8537 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8538 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8539 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8540 8541 // Couldn't symbolically evaluate. 8542 if (!CondVal) return getCouldNotCompute(); 8543 8544 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8545 ++NumBruteForceTripCountsComputed; 8546 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8547 } 8548 8549 // Update all the PHI nodes for the next iteration. 8550 DenseMap<Instruction *, Constant *> NextIterVals; 8551 8552 // Create a list of which PHIs we need to compute. We want to do this before 8553 // calling EvaluateExpression on them because that may invalidate iterators 8554 // into CurrentIterVals. 8555 SmallVector<PHINode *, 8> PHIsToCompute; 8556 for (const auto &I : CurrentIterVals) { 8557 PHINode *PHI = dyn_cast<PHINode>(I.first); 8558 if (!PHI || PHI->getParent() != Header) continue; 8559 PHIsToCompute.push_back(PHI); 8560 } 8561 for (PHINode *PHI : PHIsToCompute) { 8562 Constant *&NextPHI = NextIterVals[PHI]; 8563 if (NextPHI) continue; // Already computed! 8564 8565 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8566 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8567 } 8568 CurrentIterVals.swap(NextIterVals); 8569 } 8570 8571 // Too many iterations were needed to evaluate. 8572 return getCouldNotCompute(); 8573 } 8574 8575 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8576 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8577 ValuesAtScopes[V]; 8578 // Check to see if we've folded this expression at this loop before. 8579 for (auto &LS : Values) 8580 if (LS.first == L) 8581 return LS.second ? LS.second : V; 8582 8583 Values.emplace_back(L, nullptr); 8584 8585 // Otherwise compute it. 8586 const SCEV *C = computeSCEVAtScope(V, L); 8587 for (auto &LS : reverse(ValuesAtScopes[V])) 8588 if (LS.first == L) { 8589 LS.second = C; 8590 break; 8591 } 8592 return C; 8593 } 8594 8595 /// This builds up a Constant using the ConstantExpr interface. That way, we 8596 /// will return Constants for objects which aren't represented by a 8597 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8598 /// Returns NULL if the SCEV isn't representable as a Constant. 8599 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8600 switch (V->getSCEVType()) { 8601 case scCouldNotCompute: 8602 case scAddRecExpr: 8603 return nullptr; 8604 case scConstant: 8605 return cast<SCEVConstant>(V)->getValue(); 8606 case scUnknown: 8607 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8608 case scSignExtend: { 8609 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8610 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8611 return ConstantExpr::getSExt(CastOp, SS->getType()); 8612 return nullptr; 8613 } 8614 case scZeroExtend: { 8615 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8616 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8617 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8618 return nullptr; 8619 } 8620 case scPtrToInt: { 8621 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 8622 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 8623 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 8624 8625 return nullptr; 8626 } 8627 case scTruncate: { 8628 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8629 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8630 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8631 return nullptr; 8632 } 8633 case scAddExpr: { 8634 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8635 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8636 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8637 unsigned AS = PTy->getAddressSpace(); 8638 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8639 C = ConstantExpr::getBitCast(C, DestPtrTy); 8640 } 8641 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8642 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8643 if (!C2) 8644 return nullptr; 8645 8646 // First pointer! 8647 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8648 unsigned AS = C2->getType()->getPointerAddressSpace(); 8649 std::swap(C, C2); 8650 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8651 // The offsets have been converted to bytes. We can add bytes to an 8652 // i8* by GEP with the byte count in the first index. 8653 C = ConstantExpr::getBitCast(C, DestPtrTy); 8654 } 8655 8656 // Don't bother trying to sum two pointers. We probably can't 8657 // statically compute a load that results from it anyway. 8658 if (C2->getType()->isPointerTy()) 8659 return nullptr; 8660 8661 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8662 if (PTy->getElementType()->isStructTy()) 8663 C2 = ConstantExpr::getIntegerCast( 8664 C2, Type::getInt32Ty(C->getContext()), true); 8665 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8666 } else 8667 C = ConstantExpr::getAdd(C, C2); 8668 } 8669 return C; 8670 } 8671 return nullptr; 8672 } 8673 case scMulExpr: { 8674 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8675 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8676 // Don't bother with pointers at all. 8677 if (C->getType()->isPointerTy()) 8678 return nullptr; 8679 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8680 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8681 if (!C2 || C2->getType()->isPointerTy()) 8682 return nullptr; 8683 C = ConstantExpr::getMul(C, C2); 8684 } 8685 return C; 8686 } 8687 return nullptr; 8688 } 8689 case scUDivExpr: { 8690 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8691 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8692 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8693 if (LHS->getType() == RHS->getType()) 8694 return ConstantExpr::getUDiv(LHS, RHS); 8695 return nullptr; 8696 } 8697 case scSMaxExpr: 8698 case scUMaxExpr: 8699 case scSMinExpr: 8700 case scUMinExpr: 8701 return nullptr; // TODO: smax, umax, smin, umax. 8702 } 8703 llvm_unreachable("Unknown SCEV kind!"); 8704 } 8705 8706 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8707 if (isa<SCEVConstant>(V)) return V; 8708 8709 // If this instruction is evolved from a constant-evolving PHI, compute the 8710 // exit value from the loop without using SCEVs. 8711 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8712 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8713 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8714 const Loop *CurrLoop = this->LI[I->getParent()]; 8715 // Looking for loop exit value. 8716 if (CurrLoop && CurrLoop->getParentLoop() == L && 8717 PN->getParent() == CurrLoop->getHeader()) { 8718 // Okay, there is no closed form solution for the PHI node. Check 8719 // to see if the loop that contains it has a known backedge-taken 8720 // count. If so, we may be able to force computation of the exit 8721 // value. 8722 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8723 // This trivial case can show up in some degenerate cases where 8724 // the incoming IR has not yet been fully simplified. 8725 if (BackedgeTakenCount->isZero()) { 8726 Value *InitValue = nullptr; 8727 bool MultipleInitValues = false; 8728 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8729 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8730 if (!InitValue) 8731 InitValue = PN->getIncomingValue(i); 8732 else if (InitValue != PN->getIncomingValue(i)) { 8733 MultipleInitValues = true; 8734 break; 8735 } 8736 } 8737 } 8738 if (!MultipleInitValues && InitValue) 8739 return getSCEV(InitValue); 8740 } 8741 // Do we have a loop invariant value flowing around the backedge 8742 // for a loop which must execute the backedge? 8743 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8744 isKnownPositive(BackedgeTakenCount) && 8745 PN->getNumIncomingValues() == 2) { 8746 8747 unsigned InLoopPred = 8748 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8749 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8750 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8751 return getSCEV(BackedgeVal); 8752 } 8753 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8754 // Okay, we know how many times the containing loop executes. If 8755 // this is a constant evolving PHI node, get the final value at 8756 // the specified iteration number. 8757 Constant *RV = getConstantEvolutionLoopExitValue( 8758 PN, BTCC->getAPInt(), CurrLoop); 8759 if (RV) return getSCEV(RV); 8760 } 8761 } 8762 8763 // If there is a single-input Phi, evaluate it at our scope. If we can 8764 // prove that this replacement does not break LCSSA form, use new value. 8765 if (PN->getNumOperands() == 1) { 8766 const SCEV *Input = getSCEV(PN->getOperand(0)); 8767 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8768 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8769 // for the simplest case just support constants. 8770 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8771 } 8772 } 8773 8774 // Okay, this is an expression that we cannot symbolically evaluate 8775 // into a SCEV. Check to see if it's possible to symbolically evaluate 8776 // the arguments into constants, and if so, try to constant propagate the 8777 // result. This is particularly useful for computing loop exit values. 8778 if (CanConstantFold(I)) { 8779 SmallVector<Constant *, 4> Operands; 8780 bool MadeImprovement = false; 8781 for (Value *Op : I->operands()) { 8782 if (Constant *C = dyn_cast<Constant>(Op)) { 8783 Operands.push_back(C); 8784 continue; 8785 } 8786 8787 // If any of the operands is non-constant and if they are 8788 // non-integer and non-pointer, don't even try to analyze them 8789 // with scev techniques. 8790 if (!isSCEVable(Op->getType())) 8791 return V; 8792 8793 const SCEV *OrigV = getSCEV(Op); 8794 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8795 MadeImprovement |= OrigV != OpV; 8796 8797 Constant *C = BuildConstantFromSCEV(OpV); 8798 if (!C) return V; 8799 if (C->getType() != Op->getType()) 8800 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8801 Op->getType(), 8802 false), 8803 C, Op->getType()); 8804 Operands.push_back(C); 8805 } 8806 8807 // Check to see if getSCEVAtScope actually made an improvement. 8808 if (MadeImprovement) { 8809 Constant *C = nullptr; 8810 const DataLayout &DL = getDataLayout(); 8811 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8812 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8813 Operands[1], DL, &TLI); 8814 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8815 if (!Load->isVolatile()) 8816 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8817 DL); 8818 } else 8819 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8820 if (!C) return V; 8821 return getSCEV(C); 8822 } 8823 } 8824 } 8825 8826 // This is some other type of SCEVUnknown, just return it. 8827 return V; 8828 } 8829 8830 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8831 // Avoid performing the look-up in the common case where the specified 8832 // expression has no loop-variant portions. 8833 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8834 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8835 if (OpAtScope != Comm->getOperand(i)) { 8836 // Okay, at least one of these operands is loop variant but might be 8837 // foldable. Build a new instance of the folded commutative expression. 8838 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8839 Comm->op_begin()+i); 8840 NewOps.push_back(OpAtScope); 8841 8842 for (++i; i != e; ++i) { 8843 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8844 NewOps.push_back(OpAtScope); 8845 } 8846 if (isa<SCEVAddExpr>(Comm)) 8847 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8848 if (isa<SCEVMulExpr>(Comm)) 8849 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8850 if (isa<SCEVMinMaxExpr>(Comm)) 8851 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8852 llvm_unreachable("Unknown commutative SCEV type!"); 8853 } 8854 } 8855 // If we got here, all operands are loop invariant. 8856 return Comm; 8857 } 8858 8859 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8860 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8861 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8862 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8863 return Div; // must be loop invariant 8864 return getUDivExpr(LHS, RHS); 8865 } 8866 8867 // If this is a loop recurrence for a loop that does not contain L, then we 8868 // are dealing with the final value computed by the loop. 8869 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8870 // First, attempt to evaluate each operand. 8871 // Avoid performing the look-up in the common case where the specified 8872 // expression has no loop-variant portions. 8873 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8874 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8875 if (OpAtScope == AddRec->getOperand(i)) 8876 continue; 8877 8878 // Okay, at least one of these operands is loop variant but might be 8879 // foldable. Build a new instance of the folded commutative expression. 8880 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8881 AddRec->op_begin()+i); 8882 NewOps.push_back(OpAtScope); 8883 for (++i; i != e; ++i) 8884 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8885 8886 const SCEV *FoldedRec = 8887 getAddRecExpr(NewOps, AddRec->getLoop(), 8888 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8889 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8890 // The addrec may be folded to a nonrecurrence, for example, if the 8891 // induction variable is multiplied by zero after constant folding. Go 8892 // ahead and return the folded value. 8893 if (!AddRec) 8894 return FoldedRec; 8895 break; 8896 } 8897 8898 // If the scope is outside the addrec's loop, evaluate it by using the 8899 // loop exit value of the addrec. 8900 if (!AddRec->getLoop()->contains(L)) { 8901 // To evaluate this recurrence, we need to know how many times the AddRec 8902 // loop iterates. Compute this now. 8903 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8904 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8905 8906 // Then, evaluate the AddRec. 8907 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8908 } 8909 8910 return AddRec; 8911 } 8912 8913 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8914 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8915 if (Op == Cast->getOperand()) 8916 return Cast; // must be loop invariant 8917 return getZeroExtendExpr(Op, Cast->getType()); 8918 } 8919 8920 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8921 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8922 if (Op == Cast->getOperand()) 8923 return Cast; // must be loop invariant 8924 return getSignExtendExpr(Op, Cast->getType()); 8925 } 8926 8927 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8928 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8929 if (Op == Cast->getOperand()) 8930 return Cast; // must be loop invariant 8931 return getTruncateExpr(Op, Cast->getType()); 8932 } 8933 8934 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 8935 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8936 if (Op == Cast->getOperand()) 8937 return Cast; // must be loop invariant 8938 return getPtrToIntExpr(Op, Cast->getType()); 8939 } 8940 8941 llvm_unreachable("Unknown SCEV type!"); 8942 } 8943 8944 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8945 return getSCEVAtScope(getSCEV(V), L); 8946 } 8947 8948 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8949 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8950 return stripInjectiveFunctions(ZExt->getOperand()); 8951 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8952 return stripInjectiveFunctions(SExt->getOperand()); 8953 return S; 8954 } 8955 8956 /// Finds the minimum unsigned root of the following equation: 8957 /// 8958 /// A * X = B (mod N) 8959 /// 8960 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8961 /// A and B isn't important. 8962 /// 8963 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8964 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8965 ScalarEvolution &SE) { 8966 uint32_t BW = A.getBitWidth(); 8967 assert(BW == SE.getTypeSizeInBits(B->getType())); 8968 assert(A != 0 && "A must be non-zero."); 8969 8970 // 1. D = gcd(A, N) 8971 // 8972 // The gcd of A and N may have only one prime factor: 2. The number of 8973 // trailing zeros in A is its multiplicity 8974 uint32_t Mult2 = A.countTrailingZeros(); 8975 // D = 2^Mult2 8976 8977 // 2. Check if B is divisible by D. 8978 // 8979 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8980 // is not less than multiplicity of this prime factor for D. 8981 if (SE.GetMinTrailingZeros(B) < Mult2) 8982 return SE.getCouldNotCompute(); 8983 8984 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8985 // modulo (N / D). 8986 // 8987 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8988 // (N / D) in general. The inverse itself always fits into BW bits, though, 8989 // so we immediately truncate it. 8990 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8991 APInt Mod(BW + 1, 0); 8992 Mod.setBit(BW - Mult2); // Mod = N / D 8993 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8994 8995 // 4. Compute the minimum unsigned root of the equation: 8996 // I * (B / D) mod (N / D) 8997 // To simplify the computation, we factor out the divide by D: 8998 // (I * B mod N) / D 8999 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 9000 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 9001 } 9002 9003 /// For a given quadratic addrec, generate coefficients of the corresponding 9004 /// quadratic equation, multiplied by a common value to ensure that they are 9005 /// integers. 9006 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 9007 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 9008 /// were multiplied by, and BitWidth is the bit width of the original addrec 9009 /// coefficients. 9010 /// This function returns None if the addrec coefficients are not compile- 9011 /// time constants. 9012 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 9013 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 9014 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 9015 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 9016 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 9017 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 9018 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 9019 << *AddRec << '\n'); 9020 9021 // We currently can only solve this if the coefficients are constants. 9022 if (!LC || !MC || !NC) { 9023 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 9024 return None; 9025 } 9026 9027 APInt L = LC->getAPInt(); 9028 APInt M = MC->getAPInt(); 9029 APInt N = NC->getAPInt(); 9030 assert(!N.isNullValue() && "This is not a quadratic addrec"); 9031 9032 unsigned BitWidth = LC->getAPInt().getBitWidth(); 9033 unsigned NewWidth = BitWidth + 1; 9034 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 9035 << BitWidth << '\n'); 9036 // The sign-extension (as opposed to a zero-extension) here matches the 9037 // extension used in SolveQuadraticEquationWrap (with the same motivation). 9038 N = N.sext(NewWidth); 9039 M = M.sext(NewWidth); 9040 L = L.sext(NewWidth); 9041 9042 // The increments are M, M+N, M+2N, ..., so the accumulated values are 9043 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 9044 // L+M, L+2M+N, L+3M+3N, ... 9045 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 9046 // 9047 // The equation Acc = 0 is then 9048 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 9049 // In a quadratic form it becomes: 9050 // N n^2 + (2M-N) n + 2L = 0. 9051 9052 APInt A = N; 9053 APInt B = 2 * M - A; 9054 APInt C = 2 * L; 9055 APInt T = APInt(NewWidth, 2); 9056 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 9057 << "x + " << C << ", coeff bw: " << NewWidth 9058 << ", multiplied by " << T << '\n'); 9059 return std::make_tuple(A, B, C, T, BitWidth); 9060 } 9061 9062 /// Helper function to compare optional APInts: 9063 /// (a) if X and Y both exist, return min(X, Y), 9064 /// (b) if neither X nor Y exist, return None, 9065 /// (c) if exactly one of X and Y exists, return that value. 9066 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 9067 if (X.hasValue() && Y.hasValue()) { 9068 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 9069 APInt XW = X->sextOrSelf(W); 9070 APInt YW = Y->sextOrSelf(W); 9071 return XW.slt(YW) ? *X : *Y; 9072 } 9073 if (!X.hasValue() && !Y.hasValue()) 9074 return None; 9075 return X.hasValue() ? *X : *Y; 9076 } 9077 9078 /// Helper function to truncate an optional APInt to a given BitWidth. 9079 /// When solving addrec-related equations, it is preferable to return a value 9080 /// that has the same bit width as the original addrec's coefficients. If the 9081 /// solution fits in the original bit width, truncate it (except for i1). 9082 /// Returning a value of a different bit width may inhibit some optimizations. 9083 /// 9084 /// In general, a solution to a quadratic equation generated from an addrec 9085 /// may require BW+1 bits, where BW is the bit width of the addrec's 9086 /// coefficients. The reason is that the coefficients of the quadratic 9087 /// equation are BW+1 bits wide (to avoid truncation when converting from 9088 /// the addrec to the equation). 9089 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 9090 if (!X.hasValue()) 9091 return None; 9092 unsigned W = X->getBitWidth(); 9093 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9094 return X->trunc(BitWidth); 9095 return X; 9096 } 9097 9098 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9099 /// iterations. The values L, M, N are assumed to be signed, and they 9100 /// should all have the same bit widths. 9101 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9102 /// where BW is the bit width of the addrec's coefficients. 9103 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9104 /// returned as such, otherwise the bit width of the returned value may 9105 /// be greater than BW. 9106 /// 9107 /// This function returns None if 9108 /// (a) the addrec coefficients are not constant, or 9109 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9110 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9111 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9112 static Optional<APInt> 9113 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9114 APInt A, B, C, M; 9115 unsigned BitWidth; 9116 auto T = GetQuadraticEquation(AddRec); 9117 if (!T.hasValue()) 9118 return None; 9119 9120 std::tie(A, B, C, M, BitWidth) = *T; 9121 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9122 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9123 if (!X.hasValue()) 9124 return None; 9125 9126 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9127 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9128 if (!V->isZero()) 9129 return None; 9130 9131 return TruncIfPossible(X, BitWidth); 9132 } 9133 9134 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9135 /// iterations. The values M, N are assumed to be signed, and they 9136 /// should all have the same bit widths. 9137 /// Find the least n such that c(n) does not belong to the given range, 9138 /// while c(n-1) does. 9139 /// 9140 /// This function returns None if 9141 /// (a) the addrec coefficients are not constant, or 9142 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9143 /// bounds of the range. 9144 static Optional<APInt> 9145 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9146 const ConstantRange &Range, ScalarEvolution &SE) { 9147 assert(AddRec->getOperand(0)->isZero() && 9148 "Starting value of addrec should be 0"); 9149 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9150 << Range << ", addrec " << *AddRec << '\n'); 9151 // This case is handled in getNumIterationsInRange. Here we can assume that 9152 // we start in the range. 9153 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9154 "Addrec's initial value should be in range"); 9155 9156 APInt A, B, C, M; 9157 unsigned BitWidth; 9158 auto T = GetQuadraticEquation(AddRec); 9159 if (!T.hasValue()) 9160 return None; 9161 9162 // Be careful about the return value: there can be two reasons for not 9163 // returning an actual number. First, if no solutions to the equations 9164 // were found, and second, if the solutions don't leave the given range. 9165 // The first case means that the actual solution is "unknown", the second 9166 // means that it's known, but not valid. If the solution is unknown, we 9167 // cannot make any conclusions. 9168 // Return a pair: the optional solution and a flag indicating if the 9169 // solution was found. 9170 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9171 // Solve for signed overflow and unsigned overflow, pick the lower 9172 // solution. 9173 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9174 << Bound << " (before multiplying by " << M << ")\n"); 9175 Bound *= M; // The quadratic equation multiplier. 9176 9177 Optional<APInt> SO = None; 9178 if (BitWidth > 1) { 9179 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9180 "signed overflow\n"); 9181 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9182 } 9183 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9184 "unsigned overflow\n"); 9185 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9186 BitWidth+1); 9187 9188 auto LeavesRange = [&] (const APInt &X) { 9189 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9190 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9191 if (Range.contains(V0->getValue())) 9192 return false; 9193 // X should be at least 1, so X-1 is non-negative. 9194 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9195 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9196 if (Range.contains(V1->getValue())) 9197 return true; 9198 return false; 9199 }; 9200 9201 // If SolveQuadraticEquationWrap returns None, it means that there can 9202 // be a solution, but the function failed to find it. We cannot treat it 9203 // as "no solution". 9204 if (!SO.hasValue() || !UO.hasValue()) 9205 return { None, false }; 9206 9207 // Check the smaller value first to see if it leaves the range. 9208 // At this point, both SO and UO must have values. 9209 Optional<APInt> Min = MinOptional(SO, UO); 9210 if (LeavesRange(*Min)) 9211 return { Min, true }; 9212 Optional<APInt> Max = Min == SO ? UO : SO; 9213 if (LeavesRange(*Max)) 9214 return { Max, true }; 9215 9216 // Solutions were found, but were eliminated, hence the "true". 9217 return { None, true }; 9218 }; 9219 9220 std::tie(A, B, C, M, BitWidth) = *T; 9221 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9222 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9223 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9224 auto SL = SolveForBoundary(Lower); 9225 auto SU = SolveForBoundary(Upper); 9226 // If any of the solutions was unknown, no meaninigful conclusions can 9227 // be made. 9228 if (!SL.second || !SU.second) 9229 return None; 9230 9231 // Claim: The correct solution is not some value between Min and Max. 9232 // 9233 // Justification: Assuming that Min and Max are different values, one of 9234 // them is when the first signed overflow happens, the other is when the 9235 // first unsigned overflow happens. Crossing the range boundary is only 9236 // possible via an overflow (treating 0 as a special case of it, modeling 9237 // an overflow as crossing k*2^W for some k). 9238 // 9239 // The interesting case here is when Min was eliminated as an invalid 9240 // solution, but Max was not. The argument is that if there was another 9241 // overflow between Min and Max, it would also have been eliminated if 9242 // it was considered. 9243 // 9244 // For a given boundary, it is possible to have two overflows of the same 9245 // type (signed/unsigned) without having the other type in between: this 9246 // can happen when the vertex of the parabola is between the iterations 9247 // corresponding to the overflows. This is only possible when the two 9248 // overflows cross k*2^W for the same k. In such case, if the second one 9249 // left the range (and was the first one to do so), the first overflow 9250 // would have to enter the range, which would mean that either we had left 9251 // the range before or that we started outside of it. Both of these cases 9252 // are contradictions. 9253 // 9254 // Claim: In the case where SolveForBoundary returns None, the correct 9255 // solution is not some value between the Max for this boundary and the 9256 // Min of the other boundary. 9257 // 9258 // Justification: Assume that we had such Max_A and Min_B corresponding 9259 // to range boundaries A and B and such that Max_A < Min_B. If there was 9260 // a solution between Max_A and Min_B, it would have to be caused by an 9261 // overflow corresponding to either A or B. It cannot correspond to B, 9262 // since Min_B is the first occurrence of such an overflow. If it 9263 // corresponded to A, it would have to be either a signed or an unsigned 9264 // overflow that is larger than both eliminated overflows for A. But 9265 // between the eliminated overflows and this overflow, the values would 9266 // cover the entire value space, thus crossing the other boundary, which 9267 // is a contradiction. 9268 9269 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9270 } 9271 9272 ScalarEvolution::ExitLimit 9273 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9274 bool AllowPredicates) { 9275 9276 // This is only used for loops with a "x != y" exit test. The exit condition 9277 // is now expressed as a single expression, V = x-y. So the exit test is 9278 // effectively V != 0. We know and take advantage of the fact that this 9279 // expression only being used in a comparison by zero context. 9280 9281 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9282 // If the value is a constant 9283 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9284 // If the value is already zero, the branch will execute zero times. 9285 if (C->getValue()->isZero()) return C; 9286 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9287 } 9288 9289 const SCEVAddRecExpr *AddRec = 9290 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9291 9292 if (!AddRec && AllowPredicates) 9293 // Try to make this an AddRec using runtime tests, in the first X 9294 // iterations of this loop, where X is the SCEV expression found by the 9295 // algorithm below. 9296 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9297 9298 if (!AddRec || AddRec->getLoop() != L) 9299 return getCouldNotCompute(); 9300 9301 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9302 // the quadratic equation to solve it. 9303 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9304 // We can only use this value if the chrec ends up with an exact zero 9305 // value at this index. When solving for "X*X != 5", for example, we 9306 // should not accept a root of 2. 9307 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9308 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9309 return ExitLimit(R, R, false, Predicates); 9310 } 9311 return getCouldNotCompute(); 9312 } 9313 9314 // Otherwise we can only handle this if it is affine. 9315 if (!AddRec->isAffine()) 9316 return getCouldNotCompute(); 9317 9318 // If this is an affine expression, the execution count of this branch is 9319 // the minimum unsigned root of the following equation: 9320 // 9321 // Start + Step*N = 0 (mod 2^BW) 9322 // 9323 // equivalent to: 9324 // 9325 // Step*N = -Start (mod 2^BW) 9326 // 9327 // where BW is the common bit width of Start and Step. 9328 9329 // Get the initial value for the loop. 9330 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9331 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9332 9333 // For now we handle only constant steps. 9334 // 9335 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9336 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9337 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9338 // We have not yet seen any such cases. 9339 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9340 if (!StepC || StepC->getValue()->isZero()) 9341 return getCouldNotCompute(); 9342 9343 // For positive steps (counting up until unsigned overflow): 9344 // N = -Start/Step (as unsigned) 9345 // For negative steps (counting down to zero): 9346 // N = Start/-Step 9347 // First compute the unsigned distance from zero in the direction of Step. 9348 bool CountDown = StepC->getAPInt().isNegative(); 9349 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9350 9351 // Handle unitary steps, which cannot wraparound. 9352 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9353 // N = Distance (as unsigned) 9354 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9355 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9356 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 9357 if (MaxBECountBase.ult(MaxBECount)) 9358 MaxBECount = MaxBECountBase; 9359 9360 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9361 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9362 // case, and see if we can improve the bound. 9363 // 9364 // Explicitly handling this here is necessary because getUnsignedRange 9365 // isn't context-sensitive; it doesn't know that we only care about the 9366 // range inside the loop. 9367 const SCEV *Zero = getZero(Distance->getType()); 9368 const SCEV *One = getOne(Distance->getType()); 9369 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9370 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9371 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9372 // as "unsigned_max(Distance + 1) - 1". 9373 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9374 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9375 } 9376 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9377 } 9378 9379 // If the condition controls loop exit (the loop exits only if the expression 9380 // is true) and the addition is no-wrap we can use unsigned divide to 9381 // compute the backedge count. In this case, the step may not divide the 9382 // distance, but we don't care because if the condition is "missed" the loop 9383 // will have undefined behavior due to wrapping. 9384 if (ControlsExit && AddRec->hasNoSelfWrap() && 9385 loopHasNoAbnormalExits(AddRec->getLoop())) { 9386 const SCEV *Exact = 9387 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9388 const SCEV *Max = getCouldNotCompute(); 9389 if (Exact != getCouldNotCompute()) { 9390 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 9391 APInt BaseMaxInt = getUnsignedRangeMax(Exact); 9392 if (BaseMaxInt.ult(MaxInt)) 9393 Max = getConstant(BaseMaxInt); 9394 else 9395 Max = getConstant(MaxInt); 9396 } 9397 return ExitLimit(Exact, Max, false, Predicates); 9398 } 9399 9400 // Solve the general equation. 9401 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9402 getNegativeSCEV(Start), *this); 9403 const SCEV *M = E == getCouldNotCompute() 9404 ? E 9405 : getConstant(getUnsignedRangeMax(E)); 9406 return ExitLimit(E, M, false, Predicates); 9407 } 9408 9409 ScalarEvolution::ExitLimit 9410 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9411 // Loops that look like: while (X == 0) are very strange indeed. We don't 9412 // handle them yet except for the trivial case. This could be expanded in the 9413 // future as needed. 9414 9415 // If the value is a constant, check to see if it is known to be non-zero 9416 // already. If so, the backedge will execute zero times. 9417 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9418 if (!C->getValue()->isZero()) 9419 return getZero(C->getType()); 9420 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9421 } 9422 9423 // We could implement others, but I really doubt anyone writes loops like 9424 // this, and if they did, they would already be constant folded. 9425 return getCouldNotCompute(); 9426 } 9427 9428 std::pair<const BasicBlock *, const BasicBlock *> 9429 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9430 const { 9431 // If the block has a unique predecessor, then there is no path from the 9432 // predecessor to the block that does not go through the direct edge 9433 // from the predecessor to the block. 9434 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9435 return {Pred, BB}; 9436 9437 // A loop's header is defined to be a block that dominates the loop. 9438 // If the header has a unique predecessor outside the loop, it must be 9439 // a block that has exactly one successor that can reach the loop. 9440 if (const Loop *L = LI.getLoopFor(BB)) 9441 return {L->getLoopPredecessor(), L->getHeader()}; 9442 9443 return {nullptr, nullptr}; 9444 } 9445 9446 /// SCEV structural equivalence is usually sufficient for testing whether two 9447 /// expressions are equal, however for the purposes of looking for a condition 9448 /// guarding a loop, it can be useful to be a little more general, since a 9449 /// front-end may have replicated the controlling expression. 9450 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9451 // Quick check to see if they are the same SCEV. 9452 if (A == B) return true; 9453 9454 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9455 // Not all instructions that are "identical" compute the same value. For 9456 // instance, two distinct alloca instructions allocating the same type are 9457 // identical and do not read memory; but compute distinct values. 9458 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9459 }; 9460 9461 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9462 // two different instructions with the same value. Check for this case. 9463 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9464 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9465 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9466 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9467 if (ComputesEqualValues(AI, BI)) 9468 return true; 9469 9470 // Otherwise assume they may have a different value. 9471 return false; 9472 } 9473 9474 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9475 const SCEV *&LHS, const SCEV *&RHS, 9476 unsigned Depth) { 9477 bool Changed = false; 9478 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9479 // '0 != 0'. 9480 auto TrivialCase = [&](bool TriviallyTrue) { 9481 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9482 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9483 return true; 9484 }; 9485 // If we hit the max recursion limit bail out. 9486 if (Depth >= 3) 9487 return false; 9488 9489 // Canonicalize a constant to the right side. 9490 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9491 // Check for both operands constant. 9492 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9493 if (ConstantExpr::getICmp(Pred, 9494 LHSC->getValue(), 9495 RHSC->getValue())->isNullValue()) 9496 return TrivialCase(false); 9497 else 9498 return TrivialCase(true); 9499 } 9500 // Otherwise swap the operands to put the constant on the right. 9501 std::swap(LHS, RHS); 9502 Pred = ICmpInst::getSwappedPredicate(Pred); 9503 Changed = true; 9504 } 9505 9506 // If we're comparing an addrec with a value which is loop-invariant in the 9507 // addrec's loop, put the addrec on the left. Also make a dominance check, 9508 // as both operands could be addrecs loop-invariant in each other's loop. 9509 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9510 const Loop *L = AR->getLoop(); 9511 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9512 std::swap(LHS, RHS); 9513 Pred = ICmpInst::getSwappedPredicate(Pred); 9514 Changed = true; 9515 } 9516 } 9517 9518 // If there's a constant operand, canonicalize comparisons with boundary 9519 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9520 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9521 const APInt &RA = RC->getAPInt(); 9522 9523 bool SimplifiedByConstantRange = false; 9524 9525 if (!ICmpInst::isEquality(Pred)) { 9526 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9527 if (ExactCR.isFullSet()) 9528 return TrivialCase(true); 9529 else if (ExactCR.isEmptySet()) 9530 return TrivialCase(false); 9531 9532 APInt NewRHS; 9533 CmpInst::Predicate NewPred; 9534 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9535 ICmpInst::isEquality(NewPred)) { 9536 // We were able to convert an inequality to an equality. 9537 Pred = NewPred; 9538 RHS = getConstant(NewRHS); 9539 Changed = SimplifiedByConstantRange = true; 9540 } 9541 } 9542 9543 if (!SimplifiedByConstantRange) { 9544 switch (Pred) { 9545 default: 9546 break; 9547 case ICmpInst::ICMP_EQ: 9548 case ICmpInst::ICMP_NE: 9549 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9550 if (!RA) 9551 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9552 if (const SCEVMulExpr *ME = 9553 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9554 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9555 ME->getOperand(0)->isAllOnesValue()) { 9556 RHS = AE->getOperand(1); 9557 LHS = ME->getOperand(1); 9558 Changed = true; 9559 } 9560 break; 9561 9562 9563 // The "Should have been caught earlier!" messages refer to the fact 9564 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9565 // should have fired on the corresponding cases, and canonicalized the 9566 // check to trivial case. 9567 9568 case ICmpInst::ICMP_UGE: 9569 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9570 Pred = ICmpInst::ICMP_UGT; 9571 RHS = getConstant(RA - 1); 9572 Changed = true; 9573 break; 9574 case ICmpInst::ICMP_ULE: 9575 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9576 Pred = ICmpInst::ICMP_ULT; 9577 RHS = getConstant(RA + 1); 9578 Changed = true; 9579 break; 9580 case ICmpInst::ICMP_SGE: 9581 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9582 Pred = ICmpInst::ICMP_SGT; 9583 RHS = getConstant(RA - 1); 9584 Changed = true; 9585 break; 9586 case ICmpInst::ICMP_SLE: 9587 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9588 Pred = ICmpInst::ICMP_SLT; 9589 RHS = getConstant(RA + 1); 9590 Changed = true; 9591 break; 9592 } 9593 } 9594 } 9595 9596 // Check for obvious equality. 9597 if (HasSameValue(LHS, RHS)) { 9598 if (ICmpInst::isTrueWhenEqual(Pred)) 9599 return TrivialCase(true); 9600 if (ICmpInst::isFalseWhenEqual(Pred)) 9601 return TrivialCase(false); 9602 } 9603 9604 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9605 // adding or subtracting 1 from one of the operands. 9606 switch (Pred) { 9607 case ICmpInst::ICMP_SLE: 9608 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9609 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9610 SCEV::FlagNSW); 9611 Pred = ICmpInst::ICMP_SLT; 9612 Changed = true; 9613 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9614 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9615 SCEV::FlagNSW); 9616 Pred = ICmpInst::ICMP_SLT; 9617 Changed = true; 9618 } 9619 break; 9620 case ICmpInst::ICMP_SGE: 9621 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9622 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9623 SCEV::FlagNSW); 9624 Pred = ICmpInst::ICMP_SGT; 9625 Changed = true; 9626 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9627 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9628 SCEV::FlagNSW); 9629 Pred = ICmpInst::ICMP_SGT; 9630 Changed = true; 9631 } 9632 break; 9633 case ICmpInst::ICMP_ULE: 9634 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9635 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9636 SCEV::FlagNUW); 9637 Pred = ICmpInst::ICMP_ULT; 9638 Changed = true; 9639 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9640 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9641 Pred = ICmpInst::ICMP_ULT; 9642 Changed = true; 9643 } 9644 break; 9645 case ICmpInst::ICMP_UGE: 9646 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9647 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9648 Pred = ICmpInst::ICMP_UGT; 9649 Changed = true; 9650 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9651 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9652 SCEV::FlagNUW); 9653 Pred = ICmpInst::ICMP_UGT; 9654 Changed = true; 9655 } 9656 break; 9657 default: 9658 break; 9659 } 9660 9661 // TODO: More simplifications are possible here. 9662 9663 // Recursively simplify until we either hit a recursion limit or nothing 9664 // changes. 9665 if (Changed) 9666 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9667 9668 return Changed; 9669 } 9670 9671 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9672 return getSignedRangeMax(S).isNegative(); 9673 } 9674 9675 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9676 return getSignedRangeMin(S).isStrictlyPositive(); 9677 } 9678 9679 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9680 return !getSignedRangeMin(S).isNegative(); 9681 } 9682 9683 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9684 return !getSignedRangeMax(S).isStrictlyPositive(); 9685 } 9686 9687 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9688 return isKnownNegative(S) || isKnownPositive(S); 9689 } 9690 9691 std::pair<const SCEV *, const SCEV *> 9692 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9693 // Compute SCEV on entry of loop L. 9694 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9695 if (Start == getCouldNotCompute()) 9696 return { Start, Start }; 9697 // Compute post increment SCEV for loop L. 9698 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9699 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9700 return { Start, PostInc }; 9701 } 9702 9703 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9704 const SCEV *LHS, const SCEV *RHS) { 9705 // First collect all loops. 9706 SmallPtrSet<const Loop *, 8> LoopsUsed; 9707 getUsedLoops(LHS, LoopsUsed); 9708 getUsedLoops(RHS, LoopsUsed); 9709 9710 if (LoopsUsed.empty()) 9711 return false; 9712 9713 // Domination relationship must be a linear order on collected loops. 9714 #ifndef NDEBUG 9715 for (auto *L1 : LoopsUsed) 9716 for (auto *L2 : LoopsUsed) 9717 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9718 DT.dominates(L2->getHeader(), L1->getHeader())) && 9719 "Domination relationship is not a linear order"); 9720 #endif 9721 9722 const Loop *MDL = 9723 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9724 [&](const Loop *L1, const Loop *L2) { 9725 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9726 }); 9727 9728 // Get init and post increment value for LHS. 9729 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9730 // if LHS contains unknown non-invariant SCEV then bail out. 9731 if (SplitLHS.first == getCouldNotCompute()) 9732 return false; 9733 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9734 // Get init and post increment value for RHS. 9735 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9736 // if RHS contains unknown non-invariant SCEV then bail out. 9737 if (SplitRHS.first == getCouldNotCompute()) 9738 return false; 9739 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9740 // It is possible that init SCEV contains an invariant load but it does 9741 // not dominate MDL and is not available at MDL loop entry, so we should 9742 // check it here. 9743 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9744 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9745 return false; 9746 9747 // It seems backedge guard check is faster than entry one so in some cases 9748 // it can speed up whole estimation by short circuit 9749 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9750 SplitRHS.second) && 9751 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9752 } 9753 9754 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9755 const SCEV *LHS, const SCEV *RHS) { 9756 // Canonicalize the inputs first. 9757 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9758 9759 if (isKnownViaInduction(Pred, LHS, RHS)) 9760 return true; 9761 9762 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9763 return true; 9764 9765 // Otherwise see what can be done with some simple reasoning. 9766 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9767 } 9768 9769 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 9770 const SCEV *LHS, 9771 const SCEV *RHS) { 9772 if (isKnownPredicate(Pred, LHS, RHS)) 9773 return true; 9774 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 9775 return false; 9776 return None; 9777 } 9778 9779 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9780 const SCEV *LHS, const SCEV *RHS, 9781 const Instruction *Context) { 9782 // TODO: Analyze guards and assumes from Context's block. 9783 return isKnownPredicate(Pred, LHS, RHS) || 9784 isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS); 9785 } 9786 9787 Optional<bool> 9788 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS, 9789 const SCEV *RHS, 9790 const Instruction *Context) { 9791 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 9792 if (KnownWithoutContext) 9793 return KnownWithoutContext; 9794 9795 if (isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS)) 9796 return true; 9797 else if (isBasicBlockEntryGuardedByCond(Context->getParent(), 9798 ICmpInst::getInversePredicate(Pred), 9799 LHS, RHS)) 9800 return false; 9801 return None; 9802 } 9803 9804 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9805 const SCEVAddRecExpr *LHS, 9806 const SCEV *RHS) { 9807 const Loop *L = LHS->getLoop(); 9808 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9809 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9810 } 9811 9812 Optional<ScalarEvolution::MonotonicPredicateType> 9813 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 9814 ICmpInst::Predicate Pred) { 9815 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 9816 9817 #ifndef NDEBUG 9818 // Verify an invariant: inverting the predicate should turn a monotonically 9819 // increasing change to a monotonically decreasing one, and vice versa. 9820 if (Result) { 9821 auto ResultSwapped = 9822 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 9823 9824 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 9825 assert(ResultSwapped.getValue() != Result.getValue() && 9826 "monotonicity should flip as we flip the predicate"); 9827 } 9828 #endif 9829 9830 return Result; 9831 } 9832 9833 Optional<ScalarEvolution::MonotonicPredicateType> 9834 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 9835 ICmpInst::Predicate Pred) { 9836 // A zero step value for LHS means the induction variable is essentially a 9837 // loop invariant value. We don't really depend on the predicate actually 9838 // flipping from false to true (for increasing predicates, and the other way 9839 // around for decreasing predicates), all we care about is that *if* the 9840 // predicate changes then it only changes from false to true. 9841 // 9842 // A zero step value in itself is not very useful, but there may be places 9843 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9844 // as general as possible. 9845 9846 // Only handle LE/LT/GE/GT predicates. 9847 if (!ICmpInst::isRelational(Pred)) 9848 return None; 9849 9850 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 9851 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 9852 "Should be greater or less!"); 9853 9854 // Check that AR does not wrap. 9855 if (ICmpInst::isUnsigned(Pred)) { 9856 if (!LHS->hasNoUnsignedWrap()) 9857 return None; 9858 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9859 } else { 9860 assert(ICmpInst::isSigned(Pred) && 9861 "Relational predicate is either signed or unsigned!"); 9862 if (!LHS->hasNoSignedWrap()) 9863 return None; 9864 9865 const SCEV *Step = LHS->getStepRecurrence(*this); 9866 9867 if (isKnownNonNegative(Step)) 9868 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9869 9870 if (isKnownNonPositive(Step)) 9871 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9872 9873 return None; 9874 } 9875 } 9876 9877 Optional<ScalarEvolution::LoopInvariantPredicate> 9878 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 9879 const SCEV *LHS, const SCEV *RHS, 9880 const Loop *L) { 9881 9882 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9883 if (!isLoopInvariant(RHS, L)) { 9884 if (!isLoopInvariant(LHS, L)) 9885 return None; 9886 9887 std::swap(LHS, RHS); 9888 Pred = ICmpInst::getSwappedPredicate(Pred); 9889 } 9890 9891 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9892 if (!ArLHS || ArLHS->getLoop() != L) 9893 return None; 9894 9895 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 9896 if (!MonotonicType) 9897 return None; 9898 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9899 // true as the loop iterates, and the backedge is control dependent on 9900 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9901 // 9902 // * if the predicate was false in the first iteration then the predicate 9903 // is never evaluated again, since the loop exits without taking the 9904 // backedge. 9905 // * if the predicate was true in the first iteration then it will 9906 // continue to be true for all future iterations since it is 9907 // monotonically increasing. 9908 // 9909 // For both the above possibilities, we can replace the loop varying 9910 // predicate with its value on the first iteration of the loop (which is 9911 // loop invariant). 9912 // 9913 // A similar reasoning applies for a monotonically decreasing predicate, by 9914 // replacing true with false and false with true in the above two bullets. 9915 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 9916 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9917 9918 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9919 return None; 9920 9921 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 9922 } 9923 9924 Optional<ScalarEvolution::LoopInvariantPredicate> 9925 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 9926 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9927 const Instruction *Context, const SCEV *MaxIter) { 9928 // Try to prove the following set of facts: 9929 // - The predicate is monotonic in the iteration space. 9930 // - If the check does not fail on the 1st iteration: 9931 // - No overflow will happen during first MaxIter iterations; 9932 // - It will not fail on the MaxIter'th iteration. 9933 // If the check does fail on the 1st iteration, we leave the loop and no 9934 // other checks matter. 9935 9936 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9937 if (!isLoopInvariant(RHS, L)) { 9938 if (!isLoopInvariant(LHS, L)) 9939 return None; 9940 9941 std::swap(LHS, RHS); 9942 Pred = ICmpInst::getSwappedPredicate(Pred); 9943 } 9944 9945 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 9946 if (!AR || AR->getLoop() != L) 9947 return None; 9948 9949 // The predicate must be relational (i.e. <, <=, >=, >). 9950 if (!ICmpInst::isRelational(Pred)) 9951 return None; 9952 9953 // TODO: Support steps other than +/- 1. 9954 const SCEV *Step = AR->getStepRecurrence(*this); 9955 auto *One = getOne(Step->getType()); 9956 auto *MinusOne = getNegativeSCEV(One); 9957 if (Step != One && Step != MinusOne) 9958 return None; 9959 9960 // Type mismatch here means that MaxIter is potentially larger than max 9961 // unsigned value in start type, which mean we cannot prove no wrap for the 9962 // indvar. 9963 if (AR->getType() != MaxIter->getType()) 9964 return None; 9965 9966 // Value of IV on suggested last iteration. 9967 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 9968 // Does it still meet the requirement? 9969 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 9970 return None; 9971 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 9972 // not exceed max unsigned value of this type), this effectively proves 9973 // that there is no wrap during the iteration. To prove that there is no 9974 // signed/unsigned wrap, we need to check that 9975 // Start <= Last for step = 1 or Start >= Last for step = -1. 9976 ICmpInst::Predicate NoOverflowPred = 9977 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 9978 if (Step == MinusOne) 9979 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 9980 const SCEV *Start = AR->getStart(); 9981 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context)) 9982 return None; 9983 9984 // Everything is fine. 9985 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 9986 } 9987 9988 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9989 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9990 if (HasSameValue(LHS, RHS)) 9991 return ICmpInst::isTrueWhenEqual(Pred); 9992 9993 // This code is split out from isKnownPredicate because it is called from 9994 // within isLoopEntryGuardedByCond. 9995 9996 auto CheckRanges = [&](const ConstantRange &RangeLHS, 9997 const ConstantRange &RangeRHS) { 9998 return RangeLHS.icmp(Pred, RangeRHS); 9999 }; 10000 10001 // The check at the top of the function catches the case where the values are 10002 // known to be equal. 10003 if (Pred == CmpInst::ICMP_EQ) 10004 return false; 10005 10006 if (Pred == CmpInst::ICMP_NE) 10007 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 10008 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 10009 isKnownNonZero(getMinusSCEV(LHS, RHS)); 10010 10011 if (CmpInst::isSigned(Pred)) 10012 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 10013 10014 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 10015 } 10016 10017 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 10018 const SCEV *LHS, 10019 const SCEV *RHS) { 10020 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 10021 // Return Y via OutY. 10022 auto MatchBinaryAddToConst = 10023 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 10024 SCEV::NoWrapFlags ExpectedFlags) { 10025 const SCEV *NonConstOp, *ConstOp; 10026 SCEV::NoWrapFlags FlagsPresent; 10027 10028 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 10029 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 10030 return false; 10031 10032 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 10033 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 10034 }; 10035 10036 APInt C; 10037 10038 switch (Pred) { 10039 default: 10040 break; 10041 10042 case ICmpInst::ICMP_SGE: 10043 std::swap(LHS, RHS); 10044 LLVM_FALLTHROUGH; 10045 case ICmpInst::ICMP_SLE: 10046 // X s<= (X + C)<nsw> if C >= 0 10047 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 10048 return true; 10049 10050 // (X + C)<nsw> s<= X if C <= 0 10051 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 10052 !C.isStrictlyPositive()) 10053 return true; 10054 break; 10055 10056 case ICmpInst::ICMP_SGT: 10057 std::swap(LHS, RHS); 10058 LLVM_FALLTHROUGH; 10059 case ICmpInst::ICMP_SLT: 10060 // X s< (X + C)<nsw> if C > 0 10061 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 10062 C.isStrictlyPositive()) 10063 return true; 10064 10065 // (X + C)<nsw> s< X if C < 0 10066 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 10067 return true; 10068 break; 10069 10070 case ICmpInst::ICMP_UGE: 10071 std::swap(LHS, RHS); 10072 LLVM_FALLTHROUGH; 10073 case ICmpInst::ICMP_ULE: 10074 // X u<= (X + C)<nuw> for any C 10075 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW)) 10076 return true; 10077 break; 10078 10079 case ICmpInst::ICMP_UGT: 10080 std::swap(LHS, RHS); 10081 LLVM_FALLTHROUGH; 10082 case ICmpInst::ICMP_ULT: 10083 // X u< (X + C)<nuw> if C != 0 10084 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue()) 10085 return true; 10086 break; 10087 } 10088 10089 return false; 10090 } 10091 10092 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10093 const SCEV *LHS, 10094 const SCEV *RHS) { 10095 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10096 return false; 10097 10098 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10099 // the stack can result in exponential time complexity. 10100 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10101 10102 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10103 // 10104 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10105 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10106 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10107 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10108 // use isKnownPredicate later if needed. 10109 return isKnownNonNegative(RHS) && 10110 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10111 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10112 } 10113 10114 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10115 ICmpInst::Predicate Pred, 10116 const SCEV *LHS, const SCEV *RHS) { 10117 // No need to even try if we know the module has no guards. 10118 if (!HasGuards) 10119 return false; 10120 10121 return any_of(*BB, [&](const Instruction &I) { 10122 using namespace llvm::PatternMatch; 10123 10124 Value *Condition; 10125 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10126 m_Value(Condition))) && 10127 isImpliedCond(Pred, LHS, RHS, Condition, false); 10128 }); 10129 } 10130 10131 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10132 /// protected by a conditional between LHS and RHS. This is used to 10133 /// to eliminate casts. 10134 bool 10135 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10136 ICmpInst::Predicate Pred, 10137 const SCEV *LHS, const SCEV *RHS) { 10138 // Interpret a null as meaning no loop, where there is obviously no guard 10139 // (interprocedural conditions notwithstanding). 10140 if (!L) return true; 10141 10142 if (VerifyIR) 10143 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10144 "This cannot be done on broken IR!"); 10145 10146 10147 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10148 return true; 10149 10150 BasicBlock *Latch = L->getLoopLatch(); 10151 if (!Latch) 10152 return false; 10153 10154 BranchInst *LoopContinuePredicate = 10155 dyn_cast<BranchInst>(Latch->getTerminator()); 10156 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10157 isImpliedCond(Pred, LHS, RHS, 10158 LoopContinuePredicate->getCondition(), 10159 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10160 return true; 10161 10162 // We don't want more than one activation of the following loops on the stack 10163 // -- that can lead to O(n!) time complexity. 10164 if (WalkingBEDominatingConds) 10165 return false; 10166 10167 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10168 10169 // See if we can exploit a trip count to prove the predicate. 10170 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10171 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10172 if (LatchBECount != getCouldNotCompute()) { 10173 // We know that Latch branches back to the loop header exactly 10174 // LatchBECount times. This means the backdege condition at Latch is 10175 // equivalent to "{0,+,1} u< LatchBECount". 10176 Type *Ty = LatchBECount->getType(); 10177 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10178 const SCEV *LoopCounter = 10179 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10180 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10181 LatchBECount)) 10182 return true; 10183 } 10184 10185 // Check conditions due to any @llvm.assume intrinsics. 10186 for (auto &AssumeVH : AC.assumptions()) { 10187 if (!AssumeVH) 10188 continue; 10189 auto *CI = cast<CallInst>(AssumeVH); 10190 if (!DT.dominates(CI, Latch->getTerminator())) 10191 continue; 10192 10193 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10194 return true; 10195 } 10196 10197 // If the loop is not reachable from the entry block, we risk running into an 10198 // infinite loop as we walk up into the dom tree. These loops do not matter 10199 // anyway, so we just return a conservative answer when we see them. 10200 if (!DT.isReachableFromEntry(L->getHeader())) 10201 return false; 10202 10203 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10204 return true; 10205 10206 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10207 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10208 assert(DTN && "should reach the loop header before reaching the root!"); 10209 10210 BasicBlock *BB = DTN->getBlock(); 10211 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10212 return true; 10213 10214 BasicBlock *PBB = BB->getSinglePredecessor(); 10215 if (!PBB) 10216 continue; 10217 10218 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10219 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10220 continue; 10221 10222 Value *Condition = ContinuePredicate->getCondition(); 10223 10224 // If we have an edge `E` within the loop body that dominates the only 10225 // latch, the condition guarding `E` also guards the backedge. This 10226 // reasoning works only for loops with a single latch. 10227 10228 BasicBlockEdge DominatingEdge(PBB, BB); 10229 if (DominatingEdge.isSingleEdge()) { 10230 // We're constructively (and conservatively) enumerating edges within the 10231 // loop body that dominate the latch. The dominator tree better agree 10232 // with us on this: 10233 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10234 10235 if (isImpliedCond(Pred, LHS, RHS, Condition, 10236 BB != ContinuePredicate->getSuccessor(0))) 10237 return true; 10238 } 10239 } 10240 10241 return false; 10242 } 10243 10244 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10245 ICmpInst::Predicate Pred, 10246 const SCEV *LHS, 10247 const SCEV *RHS) { 10248 if (VerifyIR) 10249 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10250 "This cannot be done on broken IR!"); 10251 10252 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10253 // the facts (a >= b && a != b) separately. A typical situation is when the 10254 // non-strict comparison is known from ranges and non-equality is known from 10255 // dominating predicates. If we are proving strict comparison, we always try 10256 // to prove non-equality and non-strict comparison separately. 10257 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10258 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10259 bool ProvedNonStrictComparison = false; 10260 bool ProvedNonEquality = false; 10261 10262 auto SplitAndProve = 10263 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10264 if (!ProvedNonStrictComparison) 10265 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10266 if (!ProvedNonEquality) 10267 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10268 if (ProvedNonStrictComparison && ProvedNonEquality) 10269 return true; 10270 return false; 10271 }; 10272 10273 if (ProvingStrictComparison) { 10274 auto ProofFn = [&](ICmpInst::Predicate P) { 10275 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10276 }; 10277 if (SplitAndProve(ProofFn)) 10278 return true; 10279 } 10280 10281 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10282 auto ProveViaGuard = [&](const BasicBlock *Block) { 10283 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10284 return true; 10285 if (ProvingStrictComparison) { 10286 auto ProofFn = [&](ICmpInst::Predicate P) { 10287 return isImpliedViaGuard(Block, P, LHS, RHS); 10288 }; 10289 if (SplitAndProve(ProofFn)) 10290 return true; 10291 } 10292 return false; 10293 }; 10294 10295 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10296 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10297 const Instruction *Context = &BB->front(); 10298 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context)) 10299 return true; 10300 if (ProvingStrictComparison) { 10301 auto ProofFn = [&](ICmpInst::Predicate P) { 10302 return isImpliedCond(P, LHS, RHS, Condition, Inverse, Context); 10303 }; 10304 if (SplitAndProve(ProofFn)) 10305 return true; 10306 } 10307 return false; 10308 }; 10309 10310 // Starting at the block's predecessor, climb up the predecessor chain, as long 10311 // as there are predecessors that can be found that have unique successors 10312 // leading to the original block. 10313 const Loop *ContainingLoop = LI.getLoopFor(BB); 10314 const BasicBlock *PredBB; 10315 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10316 PredBB = ContainingLoop->getLoopPredecessor(); 10317 else 10318 PredBB = BB->getSinglePredecessor(); 10319 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10320 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10321 if (ProveViaGuard(Pair.first)) 10322 return true; 10323 10324 const BranchInst *LoopEntryPredicate = 10325 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10326 if (!LoopEntryPredicate || 10327 LoopEntryPredicate->isUnconditional()) 10328 continue; 10329 10330 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10331 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10332 return true; 10333 } 10334 10335 // Check conditions due to any @llvm.assume intrinsics. 10336 for (auto &AssumeVH : AC.assumptions()) { 10337 if (!AssumeVH) 10338 continue; 10339 auto *CI = cast<CallInst>(AssumeVH); 10340 if (!DT.dominates(CI, BB)) 10341 continue; 10342 10343 if (ProveViaCond(CI->getArgOperand(0), false)) 10344 return true; 10345 } 10346 10347 return false; 10348 } 10349 10350 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10351 ICmpInst::Predicate Pred, 10352 const SCEV *LHS, 10353 const SCEV *RHS) { 10354 // Interpret a null as meaning no loop, where there is obviously no guard 10355 // (interprocedural conditions notwithstanding). 10356 if (!L) 10357 return false; 10358 10359 // Both LHS and RHS must be available at loop entry. 10360 assert(isAvailableAtLoopEntry(LHS, L) && 10361 "LHS is not available at Loop Entry"); 10362 assert(isAvailableAtLoopEntry(RHS, L) && 10363 "RHS is not available at Loop Entry"); 10364 10365 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10366 return true; 10367 10368 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10369 } 10370 10371 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10372 const SCEV *RHS, 10373 const Value *FoundCondValue, bool Inverse, 10374 const Instruction *Context) { 10375 // False conditions implies anything. Do not bother analyzing it further. 10376 if (FoundCondValue == 10377 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 10378 return true; 10379 10380 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10381 return false; 10382 10383 auto ClearOnExit = 10384 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10385 10386 // Recursively handle And and Or conditions. 10387 const Value *Op0, *Op1; 10388 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 10389 if (!Inverse) 10390 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) || 10391 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context); 10392 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 10393 if (Inverse) 10394 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) || 10395 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context); 10396 } 10397 10398 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10399 if (!ICI) return false; 10400 10401 // Now that we found a conditional branch that dominates the loop or controls 10402 // the loop latch. Check to see if it is the comparison we are looking for. 10403 ICmpInst::Predicate FoundPred; 10404 if (Inverse) 10405 FoundPred = ICI->getInversePredicate(); 10406 else 10407 FoundPred = ICI->getPredicate(); 10408 10409 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10410 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10411 10412 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context); 10413 } 10414 10415 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10416 const SCEV *RHS, 10417 ICmpInst::Predicate FoundPred, 10418 const SCEV *FoundLHS, const SCEV *FoundRHS, 10419 const Instruction *Context) { 10420 // Balance the types. 10421 if (getTypeSizeInBits(LHS->getType()) < 10422 getTypeSizeInBits(FoundLHS->getType())) { 10423 // For unsigned and equality predicates, try to prove that both found 10424 // operands fit into narrow unsigned range. If so, try to prove facts in 10425 // narrow types. 10426 if (!CmpInst::isSigned(FoundPred)) { 10427 auto *NarrowType = LHS->getType(); 10428 auto *WideType = FoundLHS->getType(); 10429 auto BitWidth = getTypeSizeInBits(NarrowType); 10430 const SCEV *MaxValue = getZeroExtendExpr( 10431 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10432 if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) && 10433 isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) { 10434 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10435 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10436 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10437 TruncFoundRHS, Context)) 10438 return true; 10439 } 10440 } 10441 10442 if (CmpInst::isSigned(Pred)) { 10443 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10444 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10445 } else { 10446 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10447 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10448 } 10449 } else if (getTypeSizeInBits(LHS->getType()) > 10450 getTypeSizeInBits(FoundLHS->getType())) { 10451 if (CmpInst::isSigned(FoundPred)) { 10452 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10453 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10454 } else { 10455 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10456 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10457 } 10458 } 10459 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10460 FoundRHS, Context); 10461 } 10462 10463 bool ScalarEvolution::isImpliedCondBalancedTypes( 10464 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10465 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10466 const Instruction *Context) { 10467 assert(getTypeSizeInBits(LHS->getType()) == 10468 getTypeSizeInBits(FoundLHS->getType()) && 10469 "Types should be balanced!"); 10470 // Canonicalize the query to match the way instcombine will have 10471 // canonicalized the comparison. 10472 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10473 if (LHS == RHS) 10474 return CmpInst::isTrueWhenEqual(Pred); 10475 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10476 if (FoundLHS == FoundRHS) 10477 return CmpInst::isFalseWhenEqual(FoundPred); 10478 10479 // Check to see if we can make the LHS or RHS match. 10480 if (LHS == FoundRHS || RHS == FoundLHS) { 10481 if (isa<SCEVConstant>(RHS)) { 10482 std::swap(FoundLHS, FoundRHS); 10483 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10484 } else { 10485 std::swap(LHS, RHS); 10486 Pred = ICmpInst::getSwappedPredicate(Pred); 10487 } 10488 } 10489 10490 // Check whether the found predicate is the same as the desired predicate. 10491 if (FoundPred == Pred) 10492 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10493 10494 // Check whether swapping the found predicate makes it the same as the 10495 // desired predicate. 10496 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 10497 // We can write the implication 10498 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 10499 // using one of the following ways: 10500 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 10501 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 10502 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 10503 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 10504 // Forms 1. and 2. require swapping the operands of one condition. Don't 10505 // do this if it would break canonical constant/addrec ordering. 10506 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 10507 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 10508 Context); 10509 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 10510 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context); 10511 10512 // There's no clear preference between forms 3. and 4., try both. 10513 return isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 10514 FoundLHS, FoundRHS, Context) || 10515 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 10516 getNotSCEV(FoundRHS), Context); 10517 } 10518 10519 // Unsigned comparison is the same as signed comparison when both the operands 10520 // are non-negative. 10521 if (CmpInst::isUnsigned(FoundPred) && 10522 CmpInst::getSignedPredicate(FoundPred) == Pred && 10523 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 10524 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10525 10526 // Check if we can make progress by sharpening ranges. 10527 if (FoundPred == ICmpInst::ICMP_NE && 10528 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 10529 10530 const SCEVConstant *C = nullptr; 10531 const SCEV *V = nullptr; 10532 10533 if (isa<SCEVConstant>(FoundLHS)) { 10534 C = cast<SCEVConstant>(FoundLHS); 10535 V = FoundRHS; 10536 } else { 10537 C = cast<SCEVConstant>(FoundRHS); 10538 V = FoundLHS; 10539 } 10540 10541 // The guarding predicate tells us that C != V. If the known range 10542 // of V is [C, t), we can sharpen the range to [C + 1, t). The 10543 // range we consider has to correspond to same signedness as the 10544 // predicate we're interested in folding. 10545 10546 APInt Min = ICmpInst::isSigned(Pred) ? 10547 getSignedRangeMin(V) : getUnsignedRangeMin(V); 10548 10549 if (Min == C->getAPInt()) { 10550 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 10551 // This is true even if (Min + 1) wraps around -- in case of 10552 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 10553 10554 APInt SharperMin = Min + 1; 10555 10556 switch (Pred) { 10557 case ICmpInst::ICMP_SGE: 10558 case ICmpInst::ICMP_UGE: 10559 // We know V `Pred` SharperMin. If this implies LHS `Pred` 10560 // RHS, we're done. 10561 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 10562 Context)) 10563 return true; 10564 LLVM_FALLTHROUGH; 10565 10566 case ICmpInst::ICMP_SGT: 10567 case ICmpInst::ICMP_UGT: 10568 // We know from the range information that (V `Pred` Min || 10569 // V == Min). We know from the guarding condition that !(V 10570 // == Min). This gives us 10571 // 10572 // V `Pred` Min || V == Min && !(V == Min) 10573 // => V `Pred` Min 10574 // 10575 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 10576 10577 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), 10578 Context)) 10579 return true; 10580 break; 10581 10582 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 10583 case ICmpInst::ICMP_SLE: 10584 case ICmpInst::ICMP_ULE: 10585 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10586 LHS, V, getConstant(SharperMin), Context)) 10587 return true; 10588 LLVM_FALLTHROUGH; 10589 10590 case ICmpInst::ICMP_SLT: 10591 case ICmpInst::ICMP_ULT: 10592 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10593 LHS, V, getConstant(Min), Context)) 10594 return true; 10595 break; 10596 10597 default: 10598 // No change 10599 break; 10600 } 10601 } 10602 } 10603 10604 // Check whether the actual condition is beyond sufficient. 10605 if (FoundPred == ICmpInst::ICMP_EQ) 10606 if (ICmpInst::isTrueWhenEqual(Pred)) 10607 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context)) 10608 return true; 10609 if (Pred == ICmpInst::ICMP_NE) 10610 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 10611 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, 10612 Context)) 10613 return true; 10614 10615 // Otherwise assume the worst. 10616 return false; 10617 } 10618 10619 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 10620 const SCEV *&L, const SCEV *&R, 10621 SCEV::NoWrapFlags &Flags) { 10622 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 10623 if (!AE || AE->getNumOperands() != 2) 10624 return false; 10625 10626 L = AE->getOperand(0); 10627 R = AE->getOperand(1); 10628 Flags = AE->getNoWrapFlags(); 10629 return true; 10630 } 10631 10632 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 10633 const SCEV *Less) { 10634 // We avoid subtracting expressions here because this function is usually 10635 // fairly deep in the call stack (i.e. is called many times). 10636 10637 // X - X = 0. 10638 if (More == Less) 10639 return APInt(getTypeSizeInBits(More->getType()), 0); 10640 10641 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 10642 const auto *LAR = cast<SCEVAddRecExpr>(Less); 10643 const auto *MAR = cast<SCEVAddRecExpr>(More); 10644 10645 if (LAR->getLoop() != MAR->getLoop()) 10646 return None; 10647 10648 // We look at affine expressions only; not for correctness but to keep 10649 // getStepRecurrence cheap. 10650 if (!LAR->isAffine() || !MAR->isAffine()) 10651 return None; 10652 10653 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 10654 return None; 10655 10656 Less = LAR->getStart(); 10657 More = MAR->getStart(); 10658 10659 // fall through 10660 } 10661 10662 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10663 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10664 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10665 return M - L; 10666 } 10667 10668 SCEV::NoWrapFlags Flags; 10669 const SCEV *LLess = nullptr, *RLess = nullptr; 10670 const SCEV *LMore = nullptr, *RMore = nullptr; 10671 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10672 // Compare (X + C1) vs X. 10673 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10674 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10675 if (RLess == More) 10676 return -(C1->getAPInt()); 10677 10678 // Compare X vs (X + C2). 10679 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10680 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10681 if (RMore == Less) 10682 return C2->getAPInt(); 10683 10684 // Compare (X + C1) vs (X + C2). 10685 if (C1 && C2 && RLess == RMore) 10686 return C2->getAPInt() - C1->getAPInt(); 10687 10688 return None; 10689 } 10690 10691 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10692 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10693 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) { 10694 // Try to recognize the following pattern: 10695 // 10696 // FoundRHS = ... 10697 // ... 10698 // loop: 10699 // FoundLHS = {Start,+,W} 10700 // context_bb: // Basic block from the same loop 10701 // known(Pred, FoundLHS, FoundRHS) 10702 // 10703 // If some predicate is known in the context of a loop, it is also known on 10704 // each iteration of this loop, including the first iteration. Therefore, in 10705 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10706 // prove the original pred using this fact. 10707 if (!Context) 10708 return false; 10709 const BasicBlock *ContextBB = Context->getParent(); 10710 // Make sure AR varies in the context block. 10711 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10712 const Loop *L = AR->getLoop(); 10713 // Make sure that context belongs to the loop and executes on 1st iteration 10714 // (if it ever executes at all). 10715 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10716 return false; 10717 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10718 return false; 10719 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10720 } 10721 10722 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10723 const Loop *L = AR->getLoop(); 10724 // Make sure that context belongs to the loop and executes on 1st iteration 10725 // (if it ever executes at all). 10726 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10727 return false; 10728 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10729 return false; 10730 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10731 } 10732 10733 return false; 10734 } 10735 10736 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10737 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10738 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10739 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10740 return false; 10741 10742 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10743 if (!AddRecLHS) 10744 return false; 10745 10746 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10747 if (!AddRecFoundLHS) 10748 return false; 10749 10750 // We'd like to let SCEV reason about control dependencies, so we constrain 10751 // both the inequalities to be about add recurrences on the same loop. This 10752 // way we can use isLoopEntryGuardedByCond later. 10753 10754 const Loop *L = AddRecFoundLHS->getLoop(); 10755 if (L != AddRecLHS->getLoop()) 10756 return false; 10757 10758 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10759 // 10760 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10761 // ... (2) 10762 // 10763 // Informal proof for (2), assuming (1) [*]: 10764 // 10765 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10766 // 10767 // Then 10768 // 10769 // FoundLHS s< FoundRHS s< INT_MIN - C 10770 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10771 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10772 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10773 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10774 // <=> FoundLHS + C s< FoundRHS + C 10775 // 10776 // [*]: (1) can be proved by ruling out overflow. 10777 // 10778 // [**]: This can be proved by analyzing all the four possibilities: 10779 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10780 // (A s>= 0, B s>= 0). 10781 // 10782 // Note: 10783 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10784 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10785 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10786 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10787 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10788 // C)". 10789 10790 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10791 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10792 if (!LDiff || !RDiff || *LDiff != *RDiff) 10793 return false; 10794 10795 if (LDiff->isMinValue()) 10796 return true; 10797 10798 APInt FoundRHSLimit; 10799 10800 if (Pred == CmpInst::ICMP_ULT) { 10801 FoundRHSLimit = -(*RDiff); 10802 } else { 10803 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10804 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10805 } 10806 10807 // Try to prove (1) or (2), as needed. 10808 return isAvailableAtLoopEntry(FoundRHS, L) && 10809 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10810 getConstant(FoundRHSLimit)); 10811 } 10812 10813 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10814 const SCEV *LHS, const SCEV *RHS, 10815 const SCEV *FoundLHS, 10816 const SCEV *FoundRHS, unsigned Depth) { 10817 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10818 10819 auto ClearOnExit = make_scope_exit([&]() { 10820 if (LPhi) { 10821 bool Erased = PendingMerges.erase(LPhi); 10822 assert(Erased && "Failed to erase LPhi!"); 10823 (void)Erased; 10824 } 10825 if (RPhi) { 10826 bool Erased = PendingMerges.erase(RPhi); 10827 assert(Erased && "Failed to erase RPhi!"); 10828 (void)Erased; 10829 } 10830 }); 10831 10832 // Find respective Phis and check that they are not being pending. 10833 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10834 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10835 if (!PendingMerges.insert(Phi).second) 10836 return false; 10837 LPhi = Phi; 10838 } 10839 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10840 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10841 // If we detect a loop of Phi nodes being processed by this method, for 10842 // example: 10843 // 10844 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10845 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10846 // 10847 // we don't want to deal with a case that complex, so return conservative 10848 // answer false. 10849 if (!PendingMerges.insert(Phi).second) 10850 return false; 10851 RPhi = Phi; 10852 } 10853 10854 // If none of LHS, RHS is a Phi, nothing to do here. 10855 if (!LPhi && !RPhi) 10856 return false; 10857 10858 // If there is a SCEVUnknown Phi we are interested in, make it left. 10859 if (!LPhi) { 10860 std::swap(LHS, RHS); 10861 std::swap(FoundLHS, FoundRHS); 10862 std::swap(LPhi, RPhi); 10863 Pred = ICmpInst::getSwappedPredicate(Pred); 10864 } 10865 10866 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10867 const BasicBlock *LBB = LPhi->getParent(); 10868 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10869 10870 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10871 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10872 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10873 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10874 }; 10875 10876 if (RPhi && RPhi->getParent() == LBB) { 10877 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10878 // If we compare two Phis from the same block, and for each entry block 10879 // the predicate is true for incoming values from this block, then the 10880 // predicate is also true for the Phis. 10881 for (const BasicBlock *IncBB : predecessors(LBB)) { 10882 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10883 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10884 if (!ProvedEasily(L, R)) 10885 return false; 10886 } 10887 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10888 // Case two: RHS is also a Phi from the same basic block, and it is an 10889 // AddRec. It means that there is a loop which has both AddRec and Unknown 10890 // PHIs, for it we can compare incoming values of AddRec from above the loop 10891 // and latch with their respective incoming values of LPhi. 10892 // TODO: Generalize to handle loops with many inputs in a header. 10893 if (LPhi->getNumIncomingValues() != 2) return false; 10894 10895 auto *RLoop = RAR->getLoop(); 10896 auto *Predecessor = RLoop->getLoopPredecessor(); 10897 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10898 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10899 if (!ProvedEasily(L1, RAR->getStart())) 10900 return false; 10901 auto *Latch = RLoop->getLoopLatch(); 10902 assert(Latch && "Loop with AddRec with no latch?"); 10903 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10904 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10905 return false; 10906 } else { 10907 // In all other cases go over inputs of LHS and compare each of them to RHS, 10908 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10909 // At this point RHS is either a non-Phi, or it is a Phi from some block 10910 // different from LBB. 10911 for (const BasicBlock *IncBB : predecessors(LBB)) { 10912 // Check that RHS is available in this block. 10913 if (!dominates(RHS, IncBB)) 10914 return false; 10915 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10916 // Make sure L does not refer to a value from a potentially previous 10917 // iteration of a loop. 10918 if (!properlyDominates(L, IncBB)) 10919 return false; 10920 if (!ProvedEasily(L, RHS)) 10921 return false; 10922 } 10923 } 10924 return true; 10925 } 10926 10927 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10928 const SCEV *LHS, const SCEV *RHS, 10929 const SCEV *FoundLHS, 10930 const SCEV *FoundRHS, 10931 const Instruction *Context) { 10932 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10933 return true; 10934 10935 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10936 return true; 10937 10938 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 10939 Context)) 10940 return true; 10941 10942 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10943 FoundLHS, FoundRHS); 10944 } 10945 10946 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10947 template <typename MinMaxExprType> 10948 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10949 const SCEV *Candidate) { 10950 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10951 if (!MinMaxExpr) 10952 return false; 10953 10954 return is_contained(MinMaxExpr->operands(), Candidate); 10955 } 10956 10957 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10958 ICmpInst::Predicate Pred, 10959 const SCEV *LHS, const SCEV *RHS) { 10960 // If both sides are affine addrecs for the same loop, with equal 10961 // steps, and we know the recurrences don't wrap, then we only 10962 // need to check the predicate on the starting values. 10963 10964 if (!ICmpInst::isRelational(Pred)) 10965 return false; 10966 10967 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10968 if (!LAR) 10969 return false; 10970 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10971 if (!RAR) 10972 return false; 10973 if (LAR->getLoop() != RAR->getLoop()) 10974 return false; 10975 if (!LAR->isAffine() || !RAR->isAffine()) 10976 return false; 10977 10978 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10979 return false; 10980 10981 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10982 SCEV::FlagNSW : SCEV::FlagNUW; 10983 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10984 return false; 10985 10986 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10987 } 10988 10989 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10990 /// expression? 10991 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10992 ICmpInst::Predicate Pred, 10993 const SCEV *LHS, const SCEV *RHS) { 10994 switch (Pred) { 10995 default: 10996 return false; 10997 10998 case ICmpInst::ICMP_SGE: 10999 std::swap(LHS, RHS); 11000 LLVM_FALLTHROUGH; 11001 case ICmpInst::ICMP_SLE: 11002 return 11003 // min(A, ...) <= A 11004 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 11005 // A <= max(A, ...) 11006 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 11007 11008 case ICmpInst::ICMP_UGE: 11009 std::swap(LHS, RHS); 11010 LLVM_FALLTHROUGH; 11011 case ICmpInst::ICMP_ULE: 11012 return 11013 // min(A, ...) <= A 11014 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 11015 // A <= max(A, ...) 11016 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 11017 } 11018 11019 llvm_unreachable("covered switch fell through?!"); 11020 } 11021 11022 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 11023 const SCEV *LHS, const SCEV *RHS, 11024 const SCEV *FoundLHS, 11025 const SCEV *FoundRHS, 11026 unsigned Depth) { 11027 assert(getTypeSizeInBits(LHS->getType()) == 11028 getTypeSizeInBits(RHS->getType()) && 11029 "LHS and RHS have different sizes?"); 11030 assert(getTypeSizeInBits(FoundLHS->getType()) == 11031 getTypeSizeInBits(FoundRHS->getType()) && 11032 "FoundLHS and FoundRHS have different sizes?"); 11033 // We want to avoid hurting the compile time with analysis of too big trees. 11034 if (Depth > MaxSCEVOperationsImplicationDepth) 11035 return false; 11036 11037 // We only want to work with GT comparison so far. 11038 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 11039 Pred = CmpInst::getSwappedPredicate(Pred); 11040 std::swap(LHS, RHS); 11041 std::swap(FoundLHS, FoundRHS); 11042 } 11043 11044 // For unsigned, try to reduce it to corresponding signed comparison. 11045 if (Pred == ICmpInst::ICMP_UGT) 11046 // We can replace unsigned predicate with its signed counterpart if all 11047 // involved values are non-negative. 11048 // TODO: We could have better support for unsigned. 11049 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 11050 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 11051 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 11052 // use this fact to prove that LHS and RHS are non-negative. 11053 const SCEV *MinusOne = getMinusOne(LHS->getType()); 11054 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 11055 FoundRHS) && 11056 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 11057 FoundRHS)) 11058 Pred = ICmpInst::ICMP_SGT; 11059 } 11060 11061 if (Pred != ICmpInst::ICMP_SGT) 11062 return false; 11063 11064 auto GetOpFromSExt = [&](const SCEV *S) { 11065 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 11066 return Ext->getOperand(); 11067 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 11068 // the constant in some cases. 11069 return S; 11070 }; 11071 11072 // Acquire values from extensions. 11073 auto *OrigLHS = LHS; 11074 auto *OrigFoundLHS = FoundLHS; 11075 LHS = GetOpFromSExt(LHS); 11076 FoundLHS = GetOpFromSExt(FoundLHS); 11077 11078 // Is the SGT predicate can be proved trivially or using the found context. 11079 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 11080 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 11081 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 11082 FoundRHS, Depth + 1); 11083 }; 11084 11085 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 11086 // We want to avoid creation of any new non-constant SCEV. Since we are 11087 // going to compare the operands to RHS, we should be certain that we don't 11088 // need any size extensions for this. So let's decline all cases when the 11089 // sizes of types of LHS and RHS do not match. 11090 // TODO: Maybe try to get RHS from sext to catch more cases? 11091 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11092 return false; 11093 11094 // Should not overflow. 11095 if (!LHSAddExpr->hasNoSignedWrap()) 11096 return false; 11097 11098 auto *LL = LHSAddExpr->getOperand(0); 11099 auto *LR = LHSAddExpr->getOperand(1); 11100 auto *MinusOne = getMinusOne(RHS->getType()); 11101 11102 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11103 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11104 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11105 }; 11106 // Try to prove the following rule: 11107 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11108 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11109 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11110 return true; 11111 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11112 Value *LL, *LR; 11113 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11114 11115 using namespace llvm::PatternMatch; 11116 11117 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11118 // Rules for division. 11119 // We are going to perform some comparisons with Denominator and its 11120 // derivative expressions. In general case, creating a SCEV for it may 11121 // lead to a complex analysis of the entire graph, and in particular it 11122 // can request trip count recalculation for the same loop. This would 11123 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11124 // this, we only want to create SCEVs that are constants in this section. 11125 // So we bail if Denominator is not a constant. 11126 if (!isa<ConstantInt>(LR)) 11127 return false; 11128 11129 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11130 11131 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11132 // then a SCEV for the numerator already exists and matches with FoundLHS. 11133 auto *Numerator = getExistingSCEV(LL); 11134 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11135 return false; 11136 11137 // Make sure that the numerator matches with FoundLHS and the denominator 11138 // is positive. 11139 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11140 return false; 11141 11142 auto *DTy = Denominator->getType(); 11143 auto *FRHSTy = FoundRHS->getType(); 11144 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11145 // One of types is a pointer and another one is not. We cannot extend 11146 // them properly to a wider type, so let us just reject this case. 11147 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11148 // to avoid this check. 11149 return false; 11150 11151 // Given that: 11152 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11153 auto *WTy = getWiderType(DTy, FRHSTy); 11154 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11155 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11156 11157 // Try to prove the following rule: 11158 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11159 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11160 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11161 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11162 if (isKnownNonPositive(RHS) && 11163 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11164 return true; 11165 11166 // Try to prove the following rule: 11167 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11168 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11169 // If we divide it by Denominator > 2, then: 11170 // 1. If FoundLHS is negative, then the result is 0. 11171 // 2. If FoundLHS is non-negative, then the result is non-negative. 11172 // Anyways, the result is non-negative. 11173 auto *MinusOne = getMinusOne(WTy); 11174 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11175 if (isKnownNegative(RHS) && 11176 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11177 return true; 11178 } 11179 } 11180 11181 // If our expression contained SCEVUnknown Phis, and we split it down and now 11182 // need to prove something for them, try to prove the predicate for every 11183 // possible incoming values of those Phis. 11184 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11185 return true; 11186 11187 return false; 11188 } 11189 11190 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11191 const SCEV *LHS, const SCEV *RHS) { 11192 // zext x u<= sext x, sext x s<= zext x 11193 switch (Pred) { 11194 case ICmpInst::ICMP_SGE: 11195 std::swap(LHS, RHS); 11196 LLVM_FALLTHROUGH; 11197 case ICmpInst::ICMP_SLE: { 11198 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11199 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11200 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11201 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11202 return true; 11203 break; 11204 } 11205 case ICmpInst::ICMP_UGE: 11206 std::swap(LHS, RHS); 11207 LLVM_FALLTHROUGH; 11208 case ICmpInst::ICMP_ULE: { 11209 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11210 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11211 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11212 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11213 return true; 11214 break; 11215 } 11216 default: 11217 break; 11218 }; 11219 return false; 11220 } 11221 11222 bool 11223 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 11224 const SCEV *LHS, const SCEV *RHS) { 11225 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 11226 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 11227 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 11228 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 11229 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 11230 } 11231 11232 bool 11233 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 11234 const SCEV *LHS, const SCEV *RHS, 11235 const SCEV *FoundLHS, 11236 const SCEV *FoundRHS) { 11237 switch (Pred) { 11238 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 11239 case ICmpInst::ICMP_EQ: 11240 case ICmpInst::ICMP_NE: 11241 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 11242 return true; 11243 break; 11244 case ICmpInst::ICMP_SLT: 11245 case ICmpInst::ICMP_SLE: 11246 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 11247 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 11248 return true; 11249 break; 11250 case ICmpInst::ICMP_SGT: 11251 case ICmpInst::ICMP_SGE: 11252 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 11253 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 11254 return true; 11255 break; 11256 case ICmpInst::ICMP_ULT: 11257 case ICmpInst::ICMP_ULE: 11258 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 11259 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 11260 return true; 11261 break; 11262 case ICmpInst::ICMP_UGT: 11263 case ICmpInst::ICMP_UGE: 11264 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 11265 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 11266 return true; 11267 break; 11268 } 11269 11270 // Maybe it can be proved via operations? 11271 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11272 return true; 11273 11274 return false; 11275 } 11276 11277 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 11278 const SCEV *LHS, 11279 const SCEV *RHS, 11280 const SCEV *FoundLHS, 11281 const SCEV *FoundRHS) { 11282 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 11283 // The restriction on `FoundRHS` be lifted easily -- it exists only to 11284 // reduce the compile time impact of this optimization. 11285 return false; 11286 11287 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 11288 if (!Addend) 11289 return false; 11290 11291 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 11292 11293 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 11294 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 11295 ConstantRange FoundLHSRange = 11296 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 11297 11298 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 11299 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 11300 11301 // We can also compute the range of values for `LHS` that satisfy the 11302 // consequent, "`LHS` `Pred` `RHS`": 11303 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 11304 // The antecedent implies the consequent if every value of `LHS` that 11305 // satisfies the antecedent also satisfies the consequent. 11306 return LHSRange.icmp(Pred, ConstRHS); 11307 } 11308 11309 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 11310 bool IsSigned) { 11311 assert(isKnownPositive(Stride) && "Positive stride expected!"); 11312 11313 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11314 const SCEV *One = getOne(Stride->getType()); 11315 11316 if (IsSigned) { 11317 APInt MaxRHS = getSignedRangeMax(RHS); 11318 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11319 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11320 11321 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11322 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11323 } 11324 11325 APInt MaxRHS = getUnsignedRangeMax(RHS); 11326 APInt MaxValue = APInt::getMaxValue(BitWidth); 11327 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11328 11329 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11330 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11331 } 11332 11333 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11334 bool IsSigned) { 11335 11336 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11337 const SCEV *One = getOne(Stride->getType()); 11338 11339 if (IsSigned) { 11340 APInt MinRHS = getSignedRangeMin(RHS); 11341 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11342 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11343 11344 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11345 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11346 } 11347 11348 APInt MinRHS = getUnsignedRangeMin(RHS); 11349 APInt MinValue = APInt::getMinValue(BitWidth); 11350 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11351 11352 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11353 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11354 } 11355 11356 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, 11357 const SCEV *Step) { 11358 const SCEV *One = getOne(Step->getType()); 11359 Delta = getAddExpr(Delta, getMinusSCEV(Step, One)); 11360 return getUDivExpr(Delta, Step); 11361 } 11362 11363 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11364 const SCEV *Stride, 11365 const SCEV *End, 11366 unsigned BitWidth, 11367 bool IsSigned) { 11368 11369 assert(!isKnownNonPositive(Stride) && 11370 "Stride is expected strictly positive!"); 11371 // Calculate the maximum backedge count based on the range of values 11372 // permitted by Start, End, and Stride. 11373 const SCEV *MaxBECount; 11374 APInt MinStart = 11375 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11376 11377 APInt StrideForMaxBECount = 11378 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11379 11380 // We already know that the stride is positive, so we paper over conservatism 11381 // in our range computation by forcing StrideForMaxBECount to be at least one. 11382 // In theory this is unnecessary, but we expect MaxBECount to be a 11383 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 11384 // is nothing to constant fold it to). 11385 APInt One(BitWidth, 1, IsSigned); 11386 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 11387 11388 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11389 : APInt::getMaxValue(BitWidth); 11390 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11391 11392 // Although End can be a MAX expression we estimate MaxEnd considering only 11393 // the case End = RHS of the loop termination condition. This is safe because 11394 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11395 // taken count. 11396 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11397 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11398 11399 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 11400 getConstant(StrideForMaxBECount) /* Step */); 11401 11402 return MaxBECount; 11403 } 11404 11405 ScalarEvolution::ExitLimit 11406 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11407 const Loop *L, bool IsSigned, 11408 bool ControlsExit, bool AllowPredicates) { 11409 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11410 11411 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11412 bool PredicatedIV = false; 11413 11414 if (!IV && AllowPredicates) { 11415 // Try to make this an AddRec using runtime tests, in the first X 11416 // iterations of this loop, where X is the SCEV expression found by the 11417 // algorithm below. 11418 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11419 PredicatedIV = true; 11420 } 11421 11422 // Avoid weird loops 11423 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11424 return getCouldNotCompute(); 11425 11426 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 11427 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 11428 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 11429 11430 const SCEV *Stride = IV->getStepRecurrence(*this); 11431 11432 bool PositiveStride = isKnownPositive(Stride); 11433 11434 // Avoid negative or zero stride values. 11435 if (!PositiveStride) { 11436 // We can compute the correct backedge taken count for loops with unknown 11437 // strides if we can prove that the loop is not an infinite loop with side 11438 // effects. Here's the loop structure we are trying to handle - 11439 // 11440 // i = start 11441 // do { 11442 // A[i] = i; 11443 // i += s; 11444 // } while (i < end); 11445 // 11446 // The backedge taken count for such loops is evaluated as - 11447 // (max(end, start + stride) - start - 1) /u stride 11448 // 11449 // The additional preconditions that we need to check to prove correctness 11450 // of the above formula is as follows - 11451 // 11452 // a) IV is either nuw or nsw depending upon signedness (indicated by the 11453 // NoWrap flag). 11454 // b) loop is single exit with no side effects. 11455 // 11456 // 11457 // Precondition a) implies that if the stride is negative, this is a single 11458 // trip loop. The backedge taken count formula reduces to zero in this case. 11459 // 11460 // Precondition b) implies that the unknown stride cannot be zero otherwise 11461 // we have UB. 11462 // 11463 // The positive stride case is the same as isKnownPositive(Stride) returning 11464 // true (original behavior of the function). 11465 // 11466 // We want to make sure that the stride is truly unknown as there are edge 11467 // cases where ScalarEvolution propagates no wrap flags to the 11468 // post-increment/decrement IV even though the increment/decrement operation 11469 // itself is wrapping. The computed backedge taken count may be wrong in 11470 // such cases. This is prevented by checking that the stride is not known to 11471 // be either positive or non-positive. For example, no wrap flags are 11472 // propagated to the post-increment IV of this loop with a trip count of 2 - 11473 // 11474 // unsigned char i; 11475 // for(i=127; i<128; i+=129) 11476 // A[i] = i; 11477 // 11478 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 11479 !loopIsFiniteByAssumption(L)) 11480 return getCouldNotCompute(); 11481 } else if (!Stride->isOne() && !NoWrap) { 11482 auto isUBOnWrap = [&]() { 11483 // Can we prove this loop *must* be UB if overflow of IV occurs? 11484 // Reasoning goes as follows: 11485 // * Suppose the IV did self wrap. 11486 // * If Stride evenly divides the iteration space, then once wrap 11487 // occurs, the loop must revisit the same values. 11488 // * We know that RHS is invariant, and that none of those values 11489 // caused this exit to be taken previously. Thus, this exit is 11490 // dynamically dead. 11491 // * If this is the sole exit, then a dead exit implies the loop 11492 // must be infinite if there are no abnormal exits. 11493 // * If the loop were infinite, then it must either not be mustprogress 11494 // or have side effects. Otherwise, it must be UB. 11495 // * It can't (by assumption), be UB so we have contradicted our 11496 // premise and can conclude the IV did not in fact self-wrap. 11497 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This 11498 // follows trivially from the fact that every (un)signed-wrapped, but 11499 // not self-wrapped value must be LT than the last value before 11500 // (un)signed wrap. Since we know that last value didn't exit, nor 11501 // will any smaller one. 11502 11503 if (!isLoopInvariant(RHS, L)) 11504 return false; 11505 11506 auto *StrideC = dyn_cast<SCEVConstant>(Stride); 11507 if (!StrideC || !StrideC->getAPInt().isPowerOf2()) 11508 return false; 11509 11510 if (!ControlsExit || !loopHasNoAbnormalExits(L)) 11511 return false; 11512 11513 return loopIsFiniteByAssumption(L); 11514 }; 11515 11516 // Avoid proven overflow cases: this will ensure that the backedge taken 11517 // count will not generate any unsigned overflow. Relaxed no-overflow 11518 // conditions exploit NoWrapFlags, allowing to optimize in presence of 11519 // undefined behaviors like the case of C language. 11520 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap()) 11521 return getCouldNotCompute(); 11522 } 11523 11524 const SCEV *Start = IV->getStart(); 11525 const SCEV *End = RHS; 11526 // When the RHS is not invariant, we do not know the end bound of the loop and 11527 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 11528 // calculate the MaxBECount, given the start, stride and max value for the end 11529 // bound of the loop (RHS), and the fact that IV does not overflow (which is 11530 // checked above). 11531 if (!isLoopInvariant(RHS, L)) { 11532 const SCEV *MaxBECount = computeMaxBECountForLT( 11533 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11534 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 11535 false /*MaxOrZero*/, Predicates); 11536 } 11537 // If the backedge is taken at least once, then it will be taken 11538 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 11539 // is the LHS value of the less-than comparison the first time it is evaluated 11540 // and End is the RHS. 11541 const SCEV *BECountIfBackedgeTaken = 11542 computeBECount(getMinusSCEV(End, Start), Stride); 11543 // If the loop entry is guarded by the result of the backedge test of the 11544 // first loop iteration, then we know the backedge will be taken at least 11545 // once and so the backedge taken count is as above. If not then we use the 11546 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 11547 // as if the backedge is taken at least once max(End,Start) is End and so the 11548 // result is as above, and if not max(End,Start) is Start so we get a backedge 11549 // count of zero. 11550 const SCEV *BECount; 11551 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 11552 BECount = BECountIfBackedgeTaken; 11553 else { 11554 // If we know that RHS >= Start in the context of loop, then we know that 11555 // max(RHS, Start) = RHS at this point. 11556 if (isLoopEntryGuardedByCond( 11557 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start)) 11558 End = RHS; 11559 else 11560 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 11561 BECount = computeBECount(getMinusSCEV(End, Start), Stride); 11562 } 11563 11564 const SCEV *MaxBECount; 11565 bool MaxOrZero = false; 11566 if (isa<SCEVConstant>(BECount)) 11567 MaxBECount = BECount; 11568 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 11569 // If we know exactly how many times the backedge will be taken if it's 11570 // taken at least once, then the backedge count will either be that or 11571 // zero. 11572 MaxBECount = BECountIfBackedgeTaken; 11573 MaxOrZero = true; 11574 } else { 11575 MaxBECount = computeMaxBECountForLT( 11576 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11577 } 11578 11579 if (isa<SCEVCouldNotCompute>(MaxBECount) && 11580 !isa<SCEVCouldNotCompute>(BECount)) 11581 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 11582 11583 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 11584 } 11585 11586 ScalarEvolution::ExitLimit 11587 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 11588 const Loop *L, bool IsSigned, 11589 bool ControlsExit, bool AllowPredicates) { 11590 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11591 // We handle only IV > Invariant 11592 if (!isLoopInvariant(RHS, L)) 11593 return getCouldNotCompute(); 11594 11595 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11596 if (!IV && AllowPredicates) 11597 // Try to make this an AddRec using runtime tests, in the first X 11598 // iterations of this loop, where X is the SCEV expression found by the 11599 // algorithm below. 11600 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11601 11602 // Avoid weird loops 11603 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11604 return getCouldNotCompute(); 11605 11606 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 11607 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 11608 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 11609 11610 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 11611 11612 // Avoid negative or zero stride values 11613 if (!isKnownPositive(Stride)) 11614 return getCouldNotCompute(); 11615 11616 // Avoid proven overflow cases: this will ensure that the backedge taken count 11617 // will not generate any unsigned overflow. Relaxed no-overflow conditions 11618 // exploit NoWrapFlags, allowing to optimize in presence of undefined 11619 // behaviors like the case of C language. 11620 if (!Stride->isOne() && !NoWrap) 11621 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 11622 return getCouldNotCompute(); 11623 11624 const SCEV *Start = IV->getStart(); 11625 const SCEV *End = RHS; 11626 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 11627 // If we know that Start >= RHS in the context of loop, then we know that 11628 // min(RHS, Start) = RHS at this point. 11629 if (isLoopEntryGuardedByCond( 11630 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 11631 End = RHS; 11632 else 11633 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 11634 } 11635 11636 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride); 11637 11638 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 11639 : getUnsignedRangeMax(Start); 11640 11641 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 11642 : getUnsignedRangeMin(Stride); 11643 11644 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 11645 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 11646 : APInt::getMinValue(BitWidth) + (MinStride - 1); 11647 11648 // Although End can be a MIN expression we estimate MinEnd considering only 11649 // the case End = RHS. This is safe because in the other case (Start - End) 11650 // is zero, leading to a zero maximum backedge taken count. 11651 APInt MinEnd = 11652 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 11653 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 11654 11655 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 11656 ? BECount 11657 : computeBECount(getConstant(MaxStart - MinEnd), 11658 getConstant(MinStride)); 11659 11660 if (isa<SCEVCouldNotCompute>(MaxBECount)) 11661 MaxBECount = BECount; 11662 11663 return ExitLimit(BECount, MaxBECount, false, Predicates); 11664 } 11665 11666 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 11667 ScalarEvolution &SE) const { 11668 if (Range.isFullSet()) // Infinite loop. 11669 return SE.getCouldNotCompute(); 11670 11671 // If the start is a non-zero constant, shift the range to simplify things. 11672 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 11673 if (!SC->getValue()->isZero()) { 11674 SmallVector<const SCEV *, 4> Operands(operands()); 11675 Operands[0] = SE.getZero(SC->getType()); 11676 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 11677 getNoWrapFlags(FlagNW)); 11678 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 11679 return ShiftedAddRec->getNumIterationsInRange( 11680 Range.subtract(SC->getAPInt()), SE); 11681 // This is strange and shouldn't happen. 11682 return SE.getCouldNotCompute(); 11683 } 11684 11685 // The only time we can solve this is when we have all constant indices. 11686 // Otherwise, we cannot determine the overflow conditions. 11687 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 11688 return SE.getCouldNotCompute(); 11689 11690 // Okay at this point we know that all elements of the chrec are constants and 11691 // that the start element is zero. 11692 11693 // First check to see if the range contains zero. If not, the first 11694 // iteration exits. 11695 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 11696 if (!Range.contains(APInt(BitWidth, 0))) 11697 return SE.getZero(getType()); 11698 11699 if (isAffine()) { 11700 // If this is an affine expression then we have this situation: 11701 // Solve {0,+,A} in Range === Ax in Range 11702 11703 // We know that zero is in the range. If A is positive then we know that 11704 // the upper value of the range must be the first possible exit value. 11705 // If A is negative then the lower of the range is the last possible loop 11706 // value. Also note that we already checked for a full range. 11707 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 11708 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 11709 11710 // The exit value should be (End+A)/A. 11711 APInt ExitVal = (End + A).udiv(A); 11712 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 11713 11714 // Evaluate at the exit value. If we really did fall out of the valid 11715 // range, then we computed our trip count, otherwise wrap around or other 11716 // things must have happened. 11717 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 11718 if (Range.contains(Val->getValue())) 11719 return SE.getCouldNotCompute(); // Something strange happened 11720 11721 // Ensure that the previous value is in the range. This is a sanity check. 11722 assert(Range.contains( 11723 EvaluateConstantChrecAtConstant(this, 11724 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 11725 "Linear scev computation is off in a bad way!"); 11726 return SE.getConstant(ExitValue); 11727 } 11728 11729 if (isQuadratic()) { 11730 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 11731 return SE.getConstant(S.getValue()); 11732 } 11733 11734 return SE.getCouldNotCompute(); 11735 } 11736 11737 const SCEVAddRecExpr * 11738 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 11739 assert(getNumOperands() > 1 && "AddRec with zero step?"); 11740 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 11741 // but in this case we cannot guarantee that the value returned will be an 11742 // AddRec because SCEV does not have a fixed point where it stops 11743 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 11744 // may happen if we reach arithmetic depth limit while simplifying. So we 11745 // construct the returned value explicitly. 11746 SmallVector<const SCEV *, 3> Ops; 11747 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 11748 // (this + Step) is {A+B,+,B+C,+...,+,N}. 11749 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 11750 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 11751 // We know that the last operand is not a constant zero (otherwise it would 11752 // have been popped out earlier). This guarantees us that if the result has 11753 // the same last operand, then it will also not be popped out, meaning that 11754 // the returned value will be an AddRec. 11755 const SCEV *Last = getOperand(getNumOperands() - 1); 11756 assert(!Last->isZero() && "Recurrency with zero step?"); 11757 Ops.push_back(Last); 11758 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 11759 SCEV::FlagAnyWrap)); 11760 } 11761 11762 // Return true when S contains at least an undef value. 11763 static inline bool containsUndefs(const SCEV *S) { 11764 return SCEVExprContains(S, [](const SCEV *S) { 11765 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 11766 return isa<UndefValue>(SU->getValue()); 11767 return false; 11768 }); 11769 } 11770 11771 namespace { 11772 11773 // Collect all steps of SCEV expressions. 11774 struct SCEVCollectStrides { 11775 ScalarEvolution &SE; 11776 SmallVectorImpl<const SCEV *> &Strides; 11777 11778 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 11779 : SE(SE), Strides(S) {} 11780 11781 bool follow(const SCEV *S) { 11782 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 11783 Strides.push_back(AR->getStepRecurrence(SE)); 11784 return true; 11785 } 11786 11787 bool isDone() const { return false; } 11788 }; 11789 11790 // Collect all SCEVUnknown and SCEVMulExpr expressions. 11791 struct SCEVCollectTerms { 11792 SmallVectorImpl<const SCEV *> &Terms; 11793 11794 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 11795 11796 bool follow(const SCEV *S) { 11797 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 11798 isa<SCEVSignExtendExpr>(S)) { 11799 if (!containsUndefs(S)) 11800 Terms.push_back(S); 11801 11802 // Stop recursion: once we collected a term, do not walk its operands. 11803 return false; 11804 } 11805 11806 // Keep looking. 11807 return true; 11808 } 11809 11810 bool isDone() const { return false; } 11811 }; 11812 11813 // Check if a SCEV contains an AddRecExpr. 11814 struct SCEVHasAddRec { 11815 bool &ContainsAddRec; 11816 11817 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 11818 ContainsAddRec = false; 11819 } 11820 11821 bool follow(const SCEV *S) { 11822 if (isa<SCEVAddRecExpr>(S)) { 11823 ContainsAddRec = true; 11824 11825 // Stop recursion: once we collected a term, do not walk its operands. 11826 return false; 11827 } 11828 11829 // Keep looking. 11830 return true; 11831 } 11832 11833 bool isDone() const { return false; } 11834 }; 11835 11836 // Find factors that are multiplied with an expression that (possibly as a 11837 // subexpression) contains an AddRecExpr. In the expression: 11838 // 11839 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11840 // 11841 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11842 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11843 // parameters as they form a product with an induction variable. 11844 // 11845 // This collector expects all array size parameters to be in the same MulExpr. 11846 // It might be necessary to later add support for collecting parameters that are 11847 // spread over different nested MulExpr. 11848 struct SCEVCollectAddRecMultiplies { 11849 SmallVectorImpl<const SCEV *> &Terms; 11850 ScalarEvolution &SE; 11851 11852 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11853 : Terms(T), SE(SE) {} 11854 11855 bool follow(const SCEV *S) { 11856 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11857 bool HasAddRec = false; 11858 SmallVector<const SCEV *, 0> Operands; 11859 for (auto Op : Mul->operands()) { 11860 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11861 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11862 Operands.push_back(Op); 11863 } else if (Unknown) { 11864 HasAddRec = true; 11865 } else { 11866 bool ContainsAddRec = false; 11867 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11868 visitAll(Op, ContiansAddRec); 11869 HasAddRec |= ContainsAddRec; 11870 } 11871 } 11872 if (Operands.size() == 0) 11873 return true; 11874 11875 if (!HasAddRec) 11876 return false; 11877 11878 Terms.push_back(SE.getMulExpr(Operands)); 11879 // Stop recursion: once we collected a term, do not walk its operands. 11880 return false; 11881 } 11882 11883 // Keep looking. 11884 return true; 11885 } 11886 11887 bool isDone() const { return false; } 11888 }; 11889 11890 } // end anonymous namespace 11891 11892 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11893 /// two places: 11894 /// 1) The strides of AddRec expressions. 11895 /// 2) Unknowns that are multiplied with AddRec expressions. 11896 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11897 SmallVectorImpl<const SCEV *> &Terms) { 11898 SmallVector<const SCEV *, 4> Strides; 11899 SCEVCollectStrides StrideCollector(*this, Strides); 11900 visitAll(Expr, StrideCollector); 11901 11902 LLVM_DEBUG({ 11903 dbgs() << "Strides:\n"; 11904 for (const SCEV *S : Strides) 11905 dbgs() << *S << "\n"; 11906 }); 11907 11908 for (const SCEV *S : Strides) { 11909 SCEVCollectTerms TermCollector(Terms); 11910 visitAll(S, TermCollector); 11911 } 11912 11913 LLVM_DEBUG({ 11914 dbgs() << "Terms:\n"; 11915 for (const SCEV *T : Terms) 11916 dbgs() << *T << "\n"; 11917 }); 11918 11919 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11920 visitAll(Expr, MulCollector); 11921 } 11922 11923 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11924 SmallVectorImpl<const SCEV *> &Terms, 11925 SmallVectorImpl<const SCEV *> &Sizes) { 11926 int Last = Terms.size() - 1; 11927 const SCEV *Step = Terms[Last]; 11928 11929 // End of recursion. 11930 if (Last == 0) { 11931 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11932 SmallVector<const SCEV *, 2> Qs; 11933 for (const SCEV *Op : M->operands()) 11934 if (!isa<SCEVConstant>(Op)) 11935 Qs.push_back(Op); 11936 11937 Step = SE.getMulExpr(Qs); 11938 } 11939 11940 Sizes.push_back(Step); 11941 return true; 11942 } 11943 11944 for (const SCEV *&Term : Terms) { 11945 // Normalize the terms before the next call to findArrayDimensionsRec. 11946 const SCEV *Q, *R; 11947 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11948 11949 // Bail out when GCD does not evenly divide one of the terms. 11950 if (!R->isZero()) 11951 return false; 11952 11953 Term = Q; 11954 } 11955 11956 // Remove all SCEVConstants. 11957 erase_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }); 11958 11959 if (Terms.size() > 0) 11960 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11961 return false; 11962 11963 Sizes.push_back(Step); 11964 return true; 11965 } 11966 11967 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11968 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11969 for (const SCEV *T : Terms) 11970 if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); })) 11971 return true; 11972 11973 return false; 11974 } 11975 11976 // Return the number of product terms in S. 11977 static inline int numberOfTerms(const SCEV *S) { 11978 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11979 return Expr->getNumOperands(); 11980 return 1; 11981 } 11982 11983 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11984 if (isa<SCEVConstant>(T)) 11985 return nullptr; 11986 11987 if (isa<SCEVUnknown>(T)) 11988 return T; 11989 11990 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11991 SmallVector<const SCEV *, 2> Factors; 11992 for (const SCEV *Op : M->operands()) 11993 if (!isa<SCEVConstant>(Op)) 11994 Factors.push_back(Op); 11995 11996 return SE.getMulExpr(Factors); 11997 } 11998 11999 return T; 12000 } 12001 12002 /// Return the size of an element read or written by Inst. 12003 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 12004 Type *Ty; 12005 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 12006 Ty = Store->getValueOperand()->getType(); 12007 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 12008 Ty = Load->getType(); 12009 else 12010 return nullptr; 12011 12012 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 12013 return getSizeOfExpr(ETy, Ty); 12014 } 12015 12016 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 12017 SmallVectorImpl<const SCEV *> &Sizes, 12018 const SCEV *ElementSize) { 12019 if (Terms.size() < 1 || !ElementSize) 12020 return; 12021 12022 // Early return when Terms do not contain parameters: we do not delinearize 12023 // non parametric SCEVs. 12024 if (!containsParameters(Terms)) 12025 return; 12026 12027 LLVM_DEBUG({ 12028 dbgs() << "Terms:\n"; 12029 for (const SCEV *T : Terms) 12030 dbgs() << *T << "\n"; 12031 }); 12032 12033 // Remove duplicates. 12034 array_pod_sort(Terms.begin(), Terms.end()); 12035 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 12036 12037 // Put larger terms first. 12038 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 12039 return numberOfTerms(LHS) > numberOfTerms(RHS); 12040 }); 12041 12042 // Try to divide all terms by the element size. If term is not divisible by 12043 // element size, proceed with the original term. 12044 for (const SCEV *&Term : Terms) { 12045 const SCEV *Q, *R; 12046 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 12047 if (!Q->isZero()) 12048 Term = Q; 12049 } 12050 12051 SmallVector<const SCEV *, 4> NewTerms; 12052 12053 // Remove constant factors. 12054 for (const SCEV *T : Terms) 12055 if (const SCEV *NewT = removeConstantFactors(*this, T)) 12056 NewTerms.push_back(NewT); 12057 12058 LLVM_DEBUG({ 12059 dbgs() << "Terms after sorting:\n"; 12060 for (const SCEV *T : NewTerms) 12061 dbgs() << *T << "\n"; 12062 }); 12063 12064 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 12065 Sizes.clear(); 12066 return; 12067 } 12068 12069 // The last element to be pushed into Sizes is the size of an element. 12070 Sizes.push_back(ElementSize); 12071 12072 LLVM_DEBUG({ 12073 dbgs() << "Sizes:\n"; 12074 for (const SCEV *S : Sizes) 12075 dbgs() << *S << "\n"; 12076 }); 12077 } 12078 12079 void ScalarEvolution::computeAccessFunctions( 12080 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 12081 SmallVectorImpl<const SCEV *> &Sizes) { 12082 // Early exit in case this SCEV is not an affine multivariate function. 12083 if (Sizes.empty()) 12084 return; 12085 12086 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 12087 if (!AR->isAffine()) 12088 return; 12089 12090 const SCEV *Res = Expr; 12091 int Last = Sizes.size() - 1; 12092 for (int i = Last; i >= 0; i--) { 12093 const SCEV *Q, *R; 12094 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 12095 12096 LLVM_DEBUG({ 12097 dbgs() << "Res: " << *Res << "\n"; 12098 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 12099 dbgs() << "Res divided by Sizes[i]:\n"; 12100 dbgs() << "Quotient: " << *Q << "\n"; 12101 dbgs() << "Remainder: " << *R << "\n"; 12102 }); 12103 12104 Res = Q; 12105 12106 // Do not record the last subscript corresponding to the size of elements in 12107 // the array. 12108 if (i == Last) { 12109 12110 // Bail out if the remainder is too complex. 12111 if (isa<SCEVAddRecExpr>(R)) { 12112 Subscripts.clear(); 12113 Sizes.clear(); 12114 return; 12115 } 12116 12117 continue; 12118 } 12119 12120 // Record the access function for the current subscript. 12121 Subscripts.push_back(R); 12122 } 12123 12124 // Also push in last position the remainder of the last division: it will be 12125 // the access function of the innermost dimension. 12126 Subscripts.push_back(Res); 12127 12128 std::reverse(Subscripts.begin(), Subscripts.end()); 12129 12130 LLVM_DEBUG({ 12131 dbgs() << "Subscripts:\n"; 12132 for (const SCEV *S : Subscripts) 12133 dbgs() << *S << "\n"; 12134 }); 12135 } 12136 12137 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 12138 /// sizes of an array access. Returns the remainder of the delinearization that 12139 /// is the offset start of the array. The SCEV->delinearize algorithm computes 12140 /// the multiples of SCEV coefficients: that is a pattern matching of sub 12141 /// expressions in the stride and base of a SCEV corresponding to the 12142 /// computation of a GCD (greatest common divisor) of base and stride. When 12143 /// SCEV->delinearize fails, it returns the SCEV unchanged. 12144 /// 12145 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 12146 /// 12147 /// void foo(long n, long m, long o, double A[n][m][o]) { 12148 /// 12149 /// for (long i = 0; i < n; i++) 12150 /// for (long j = 0; j < m; j++) 12151 /// for (long k = 0; k < o; k++) 12152 /// A[i][j][k] = 1.0; 12153 /// } 12154 /// 12155 /// the delinearization input is the following AddRec SCEV: 12156 /// 12157 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 12158 /// 12159 /// From this SCEV, we are able to say that the base offset of the access is %A 12160 /// because it appears as an offset that does not divide any of the strides in 12161 /// the loops: 12162 /// 12163 /// CHECK: Base offset: %A 12164 /// 12165 /// and then SCEV->delinearize determines the size of some of the dimensions of 12166 /// the array as these are the multiples by which the strides are happening: 12167 /// 12168 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 12169 /// 12170 /// Note that the outermost dimension remains of UnknownSize because there are 12171 /// no strides that would help identifying the size of the last dimension: when 12172 /// the array has been statically allocated, one could compute the size of that 12173 /// dimension by dividing the overall size of the array by the size of the known 12174 /// dimensions: %m * %o * 8. 12175 /// 12176 /// Finally delinearize provides the access functions for the array reference 12177 /// that does correspond to A[i][j][k] of the above C testcase: 12178 /// 12179 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 12180 /// 12181 /// The testcases are checking the output of a function pass: 12182 /// DelinearizationPass that walks through all loads and stores of a function 12183 /// asking for the SCEV of the memory access with respect to all enclosing 12184 /// loops, calling SCEV->delinearize on that and printing the results. 12185 void ScalarEvolution::delinearize(const SCEV *Expr, 12186 SmallVectorImpl<const SCEV *> &Subscripts, 12187 SmallVectorImpl<const SCEV *> &Sizes, 12188 const SCEV *ElementSize) { 12189 // First step: collect parametric terms. 12190 SmallVector<const SCEV *, 4> Terms; 12191 collectParametricTerms(Expr, Terms); 12192 12193 if (Terms.empty()) 12194 return; 12195 12196 // Second step: find subscript sizes. 12197 findArrayDimensions(Terms, Sizes, ElementSize); 12198 12199 if (Sizes.empty()) 12200 return; 12201 12202 // Third step: compute the access functions for each subscript. 12203 computeAccessFunctions(Expr, Subscripts, Sizes); 12204 12205 if (Subscripts.empty()) 12206 return; 12207 12208 LLVM_DEBUG({ 12209 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 12210 dbgs() << "ArrayDecl[UnknownSize]"; 12211 for (const SCEV *S : Sizes) 12212 dbgs() << "[" << *S << "]"; 12213 12214 dbgs() << "\nArrayRef"; 12215 for (const SCEV *S : Subscripts) 12216 dbgs() << "[" << *S << "]"; 12217 dbgs() << "\n"; 12218 }); 12219 } 12220 12221 bool ScalarEvolution::getIndexExpressionsFromGEP( 12222 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 12223 SmallVectorImpl<int> &Sizes) { 12224 assert(Subscripts.empty() && Sizes.empty() && 12225 "Expected output lists to be empty on entry to this function."); 12226 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 12227 Type *Ty = GEP->getPointerOperandType(); 12228 bool DroppedFirstDim = false; 12229 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 12230 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 12231 if (i == 1) { 12232 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 12233 Ty = PtrTy->getElementType(); 12234 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 12235 Ty = ArrayTy->getElementType(); 12236 } else { 12237 Subscripts.clear(); 12238 Sizes.clear(); 12239 return false; 12240 } 12241 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 12242 if (Const->getValue()->isZero()) { 12243 DroppedFirstDim = true; 12244 continue; 12245 } 12246 Subscripts.push_back(Expr); 12247 continue; 12248 } 12249 12250 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 12251 if (!ArrayTy) { 12252 Subscripts.clear(); 12253 Sizes.clear(); 12254 return false; 12255 } 12256 12257 Subscripts.push_back(Expr); 12258 if (!(DroppedFirstDim && i == 2)) 12259 Sizes.push_back(ArrayTy->getNumElements()); 12260 12261 Ty = ArrayTy->getElementType(); 12262 } 12263 return !Subscripts.empty(); 12264 } 12265 12266 //===----------------------------------------------------------------------===// 12267 // SCEVCallbackVH Class Implementation 12268 //===----------------------------------------------------------------------===// 12269 12270 void ScalarEvolution::SCEVCallbackVH::deleted() { 12271 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12272 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12273 SE->ConstantEvolutionLoopExitValue.erase(PN); 12274 SE->eraseValueFromMap(getValPtr()); 12275 // this now dangles! 12276 } 12277 12278 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12279 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12280 12281 // Forget all the expressions associated with users of the old value, 12282 // so that future queries will recompute the expressions using the new 12283 // value. 12284 Value *Old = getValPtr(); 12285 SmallVector<User *, 16> Worklist(Old->users()); 12286 SmallPtrSet<User *, 8> Visited; 12287 while (!Worklist.empty()) { 12288 User *U = Worklist.pop_back_val(); 12289 // Deleting the Old value will cause this to dangle. Postpone 12290 // that until everything else is done. 12291 if (U == Old) 12292 continue; 12293 if (!Visited.insert(U).second) 12294 continue; 12295 if (PHINode *PN = dyn_cast<PHINode>(U)) 12296 SE->ConstantEvolutionLoopExitValue.erase(PN); 12297 SE->eraseValueFromMap(U); 12298 llvm::append_range(Worklist, U->users()); 12299 } 12300 // Delete the Old value. 12301 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12302 SE->ConstantEvolutionLoopExitValue.erase(PN); 12303 SE->eraseValueFromMap(Old); 12304 // this now dangles! 12305 } 12306 12307 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12308 : CallbackVH(V), SE(se) {} 12309 12310 //===----------------------------------------------------------------------===// 12311 // ScalarEvolution Class Implementation 12312 //===----------------------------------------------------------------------===// 12313 12314 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12315 AssumptionCache &AC, DominatorTree &DT, 12316 LoopInfo &LI) 12317 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12318 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12319 LoopDispositions(64), BlockDispositions(64) { 12320 // To use guards for proving predicates, we need to scan every instruction in 12321 // relevant basic blocks, and not just terminators. Doing this is a waste of 12322 // time if the IR does not actually contain any calls to 12323 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12324 // 12325 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12326 // to _add_ guards to the module when there weren't any before, and wants 12327 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12328 // efficient in lieu of being smart in that rather obscure case. 12329 12330 auto *GuardDecl = F.getParent()->getFunction( 12331 Intrinsic::getName(Intrinsic::experimental_guard)); 12332 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12333 } 12334 12335 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12336 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12337 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12338 ValueExprMap(std::move(Arg.ValueExprMap)), 12339 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12340 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12341 PendingMerges(std::move(Arg.PendingMerges)), 12342 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12343 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12344 PredicatedBackedgeTakenCounts( 12345 std::move(Arg.PredicatedBackedgeTakenCounts)), 12346 ConstantEvolutionLoopExitValue( 12347 std::move(Arg.ConstantEvolutionLoopExitValue)), 12348 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12349 LoopDispositions(std::move(Arg.LoopDispositions)), 12350 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12351 BlockDispositions(std::move(Arg.BlockDispositions)), 12352 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12353 SignedRanges(std::move(Arg.SignedRanges)), 12354 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12355 UniquePreds(std::move(Arg.UniquePreds)), 12356 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12357 LoopUsers(std::move(Arg.LoopUsers)), 12358 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12359 FirstUnknown(Arg.FirstUnknown) { 12360 Arg.FirstUnknown = nullptr; 12361 } 12362 12363 ScalarEvolution::~ScalarEvolution() { 12364 // Iterate through all the SCEVUnknown instances and call their 12365 // destructors, so that they release their references to their values. 12366 for (SCEVUnknown *U = FirstUnknown; U;) { 12367 SCEVUnknown *Tmp = U; 12368 U = U->Next; 12369 Tmp->~SCEVUnknown(); 12370 } 12371 FirstUnknown = nullptr; 12372 12373 ExprValueMap.clear(); 12374 ValueExprMap.clear(); 12375 HasRecMap.clear(); 12376 BackedgeTakenCounts.clear(); 12377 PredicatedBackedgeTakenCounts.clear(); 12378 12379 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12380 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12381 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12382 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12383 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12384 } 12385 12386 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12387 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12388 } 12389 12390 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12391 const Loop *L) { 12392 // Print all inner loops first 12393 for (Loop *I : *L) 12394 PrintLoopInfo(OS, SE, I); 12395 12396 OS << "Loop "; 12397 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12398 OS << ": "; 12399 12400 SmallVector<BasicBlock *, 8> ExitingBlocks; 12401 L->getExitingBlocks(ExitingBlocks); 12402 if (ExitingBlocks.size() != 1) 12403 OS << "<multiple exits> "; 12404 12405 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12406 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12407 else 12408 OS << "Unpredictable backedge-taken count.\n"; 12409 12410 if (ExitingBlocks.size() > 1) 12411 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12412 OS << " exit count for " << ExitingBlock->getName() << ": " 12413 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12414 } 12415 12416 OS << "Loop "; 12417 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12418 OS << ": "; 12419 12420 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12421 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12422 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12423 OS << ", actual taken count either this or zero."; 12424 } else { 12425 OS << "Unpredictable max backedge-taken count. "; 12426 } 12427 12428 OS << "\n" 12429 "Loop "; 12430 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12431 OS << ": "; 12432 12433 SCEVUnionPredicate Pred; 12434 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12435 if (!isa<SCEVCouldNotCompute>(PBT)) { 12436 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12437 OS << " Predicates:\n"; 12438 Pred.print(OS, 4); 12439 } else { 12440 OS << "Unpredictable predicated backedge-taken count. "; 12441 } 12442 OS << "\n"; 12443 12444 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12445 OS << "Loop "; 12446 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12447 OS << ": "; 12448 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12449 } 12450 } 12451 12452 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12453 switch (LD) { 12454 case ScalarEvolution::LoopVariant: 12455 return "Variant"; 12456 case ScalarEvolution::LoopInvariant: 12457 return "Invariant"; 12458 case ScalarEvolution::LoopComputable: 12459 return "Computable"; 12460 } 12461 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12462 } 12463 12464 void ScalarEvolution::print(raw_ostream &OS) const { 12465 // ScalarEvolution's implementation of the print method is to print 12466 // out SCEV values of all instructions that are interesting. Doing 12467 // this potentially causes it to create new SCEV objects though, 12468 // which technically conflicts with the const qualifier. This isn't 12469 // observable from outside the class though, so casting away the 12470 // const isn't dangerous. 12471 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12472 12473 if (ClassifyExpressions) { 12474 OS << "Classifying expressions for: "; 12475 F.printAsOperand(OS, /*PrintType=*/false); 12476 OS << "\n"; 12477 for (Instruction &I : instructions(F)) 12478 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12479 OS << I << '\n'; 12480 OS << " --> "; 12481 const SCEV *SV = SE.getSCEV(&I); 12482 SV->print(OS); 12483 if (!isa<SCEVCouldNotCompute>(SV)) { 12484 OS << " U: "; 12485 SE.getUnsignedRange(SV).print(OS); 12486 OS << " S: "; 12487 SE.getSignedRange(SV).print(OS); 12488 } 12489 12490 const Loop *L = LI.getLoopFor(I.getParent()); 12491 12492 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12493 if (AtUse != SV) { 12494 OS << " --> "; 12495 AtUse->print(OS); 12496 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12497 OS << " U: "; 12498 SE.getUnsignedRange(AtUse).print(OS); 12499 OS << " S: "; 12500 SE.getSignedRange(AtUse).print(OS); 12501 } 12502 } 12503 12504 if (L) { 12505 OS << "\t\t" "Exits: "; 12506 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12507 if (!SE.isLoopInvariant(ExitValue, L)) { 12508 OS << "<<Unknown>>"; 12509 } else { 12510 OS << *ExitValue; 12511 } 12512 12513 bool First = true; 12514 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12515 if (First) { 12516 OS << "\t\t" "LoopDispositions: { "; 12517 First = false; 12518 } else { 12519 OS << ", "; 12520 } 12521 12522 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12523 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12524 } 12525 12526 for (auto *InnerL : depth_first(L)) { 12527 if (InnerL == L) 12528 continue; 12529 if (First) { 12530 OS << "\t\t" "LoopDispositions: { "; 12531 First = false; 12532 } else { 12533 OS << ", "; 12534 } 12535 12536 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12537 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12538 } 12539 12540 OS << " }"; 12541 } 12542 12543 OS << "\n"; 12544 } 12545 } 12546 12547 OS << "Determining loop execution counts for: "; 12548 F.printAsOperand(OS, /*PrintType=*/false); 12549 OS << "\n"; 12550 for (Loop *I : LI) 12551 PrintLoopInfo(OS, &SE, I); 12552 } 12553 12554 ScalarEvolution::LoopDisposition 12555 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12556 auto &Values = LoopDispositions[S]; 12557 for (auto &V : Values) { 12558 if (V.getPointer() == L) 12559 return V.getInt(); 12560 } 12561 Values.emplace_back(L, LoopVariant); 12562 LoopDisposition D = computeLoopDisposition(S, L); 12563 auto &Values2 = LoopDispositions[S]; 12564 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12565 if (V.getPointer() == L) { 12566 V.setInt(D); 12567 break; 12568 } 12569 } 12570 return D; 12571 } 12572 12573 ScalarEvolution::LoopDisposition 12574 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12575 switch (S->getSCEVType()) { 12576 case scConstant: 12577 return LoopInvariant; 12578 case scPtrToInt: 12579 case scTruncate: 12580 case scZeroExtend: 12581 case scSignExtend: 12582 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12583 case scAddRecExpr: { 12584 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12585 12586 // If L is the addrec's loop, it's computable. 12587 if (AR->getLoop() == L) 12588 return LoopComputable; 12589 12590 // Add recurrences are never invariant in the function-body (null loop). 12591 if (!L) 12592 return LoopVariant; 12593 12594 // Everything that is not defined at loop entry is variant. 12595 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12596 return LoopVariant; 12597 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12598 " dominate the contained loop's header?"); 12599 12600 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12601 if (AR->getLoop()->contains(L)) 12602 return LoopInvariant; 12603 12604 // This recurrence is variant w.r.t. L if any of its operands 12605 // are variant. 12606 for (auto *Op : AR->operands()) 12607 if (!isLoopInvariant(Op, L)) 12608 return LoopVariant; 12609 12610 // Otherwise it's loop-invariant. 12611 return LoopInvariant; 12612 } 12613 case scAddExpr: 12614 case scMulExpr: 12615 case scUMaxExpr: 12616 case scSMaxExpr: 12617 case scUMinExpr: 12618 case scSMinExpr: { 12619 bool HasVarying = false; 12620 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12621 LoopDisposition D = getLoopDisposition(Op, L); 12622 if (D == LoopVariant) 12623 return LoopVariant; 12624 if (D == LoopComputable) 12625 HasVarying = true; 12626 } 12627 return HasVarying ? LoopComputable : LoopInvariant; 12628 } 12629 case scUDivExpr: { 12630 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12631 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12632 if (LD == LoopVariant) 12633 return LoopVariant; 12634 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12635 if (RD == LoopVariant) 12636 return LoopVariant; 12637 return (LD == LoopInvariant && RD == LoopInvariant) ? 12638 LoopInvariant : LoopComputable; 12639 } 12640 case scUnknown: 12641 // All non-instruction values are loop invariant. All instructions are loop 12642 // invariant if they are not contained in the specified loop. 12643 // Instructions are never considered invariant in the function body 12644 // (null loop) because they are defined within the "loop". 12645 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12646 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12647 return LoopInvariant; 12648 case scCouldNotCompute: 12649 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12650 } 12651 llvm_unreachable("Unknown SCEV kind!"); 12652 } 12653 12654 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 12655 return getLoopDisposition(S, L) == LoopInvariant; 12656 } 12657 12658 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 12659 return getLoopDisposition(S, L) == LoopComputable; 12660 } 12661 12662 ScalarEvolution::BlockDisposition 12663 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12664 auto &Values = BlockDispositions[S]; 12665 for (auto &V : Values) { 12666 if (V.getPointer() == BB) 12667 return V.getInt(); 12668 } 12669 Values.emplace_back(BB, DoesNotDominateBlock); 12670 BlockDisposition D = computeBlockDisposition(S, BB); 12671 auto &Values2 = BlockDispositions[S]; 12672 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12673 if (V.getPointer() == BB) { 12674 V.setInt(D); 12675 break; 12676 } 12677 } 12678 return D; 12679 } 12680 12681 ScalarEvolution::BlockDisposition 12682 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12683 switch (S->getSCEVType()) { 12684 case scConstant: 12685 return ProperlyDominatesBlock; 12686 case scPtrToInt: 12687 case scTruncate: 12688 case scZeroExtend: 12689 case scSignExtend: 12690 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 12691 case scAddRecExpr: { 12692 // This uses a "dominates" query instead of "properly dominates" query 12693 // to test for proper dominance too, because the instruction which 12694 // produces the addrec's value is a PHI, and a PHI effectively properly 12695 // dominates its entire containing block. 12696 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12697 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 12698 return DoesNotDominateBlock; 12699 12700 // Fall through into SCEVNAryExpr handling. 12701 LLVM_FALLTHROUGH; 12702 } 12703 case scAddExpr: 12704 case scMulExpr: 12705 case scUMaxExpr: 12706 case scSMaxExpr: 12707 case scUMinExpr: 12708 case scSMinExpr: { 12709 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12710 bool Proper = true; 12711 for (const SCEV *NAryOp : NAry->operands()) { 12712 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12713 if (D == DoesNotDominateBlock) 12714 return DoesNotDominateBlock; 12715 if (D == DominatesBlock) 12716 Proper = false; 12717 } 12718 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12719 } 12720 case scUDivExpr: { 12721 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12722 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12723 BlockDisposition LD = getBlockDisposition(LHS, BB); 12724 if (LD == DoesNotDominateBlock) 12725 return DoesNotDominateBlock; 12726 BlockDisposition RD = getBlockDisposition(RHS, BB); 12727 if (RD == DoesNotDominateBlock) 12728 return DoesNotDominateBlock; 12729 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12730 ProperlyDominatesBlock : DominatesBlock; 12731 } 12732 case scUnknown: 12733 if (Instruction *I = 12734 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12735 if (I->getParent() == BB) 12736 return DominatesBlock; 12737 if (DT.properlyDominates(I->getParent(), BB)) 12738 return ProperlyDominatesBlock; 12739 return DoesNotDominateBlock; 12740 } 12741 return ProperlyDominatesBlock; 12742 case scCouldNotCompute: 12743 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12744 } 12745 llvm_unreachable("Unknown SCEV kind!"); 12746 } 12747 12748 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12749 return getBlockDisposition(S, BB) >= DominatesBlock; 12750 } 12751 12752 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12753 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12754 } 12755 12756 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12757 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12758 } 12759 12760 void 12761 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12762 ValuesAtScopes.erase(S); 12763 LoopDispositions.erase(S); 12764 BlockDispositions.erase(S); 12765 UnsignedRanges.erase(S); 12766 SignedRanges.erase(S); 12767 ExprValueMap.erase(S); 12768 HasRecMap.erase(S); 12769 MinTrailingZerosCache.erase(S); 12770 12771 for (auto I = PredicatedSCEVRewrites.begin(); 12772 I != PredicatedSCEVRewrites.end();) { 12773 std::pair<const SCEV *, const Loop *> Entry = I->first; 12774 if (Entry.first == S) 12775 PredicatedSCEVRewrites.erase(I++); 12776 else 12777 ++I; 12778 } 12779 12780 auto RemoveSCEVFromBackedgeMap = 12781 [S](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12782 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12783 BackedgeTakenInfo &BEInfo = I->second; 12784 if (BEInfo.hasOperand(S)) 12785 Map.erase(I++); 12786 else 12787 ++I; 12788 } 12789 }; 12790 12791 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12792 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12793 } 12794 12795 void 12796 ScalarEvolution::getUsedLoops(const SCEV *S, 12797 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12798 struct FindUsedLoops { 12799 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12800 : LoopsUsed(LoopsUsed) {} 12801 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12802 bool follow(const SCEV *S) { 12803 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12804 LoopsUsed.insert(AR->getLoop()); 12805 return true; 12806 } 12807 12808 bool isDone() const { return false; } 12809 }; 12810 12811 FindUsedLoops F(LoopsUsed); 12812 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12813 } 12814 12815 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12816 SmallPtrSet<const Loop *, 8> LoopsUsed; 12817 getUsedLoops(S, LoopsUsed); 12818 for (auto *L : LoopsUsed) 12819 LoopUsers[L].push_back(S); 12820 } 12821 12822 void ScalarEvolution::verify() const { 12823 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12824 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12825 12826 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12827 12828 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12829 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12830 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12831 12832 const SCEV *visitConstant(const SCEVConstant *Constant) { 12833 return SE.getConstant(Constant->getAPInt()); 12834 } 12835 12836 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12837 return SE.getUnknown(Expr->getValue()); 12838 } 12839 12840 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12841 return SE.getCouldNotCompute(); 12842 } 12843 }; 12844 12845 SCEVMapper SCM(SE2); 12846 12847 while (!LoopStack.empty()) { 12848 auto *L = LoopStack.pop_back_val(); 12849 llvm::append_range(LoopStack, *L); 12850 12851 auto *CurBECount = SCM.visit( 12852 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12853 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12854 12855 if (CurBECount == SE2.getCouldNotCompute() || 12856 NewBECount == SE2.getCouldNotCompute()) { 12857 // NB! This situation is legal, but is very suspicious -- whatever pass 12858 // change the loop to make a trip count go from could not compute to 12859 // computable or vice-versa *should have* invalidated SCEV. However, we 12860 // choose not to assert here (for now) since we don't want false 12861 // positives. 12862 continue; 12863 } 12864 12865 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12866 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12867 // not propagate undef aggressively). This means we can (and do) fail 12868 // verification in cases where a transform makes the trip count of a loop 12869 // go from "undef" to "undef+1" (say). The transform is fine, since in 12870 // both cases the loop iterates "undef" times, but SCEV thinks we 12871 // increased the trip count of the loop by 1 incorrectly. 12872 continue; 12873 } 12874 12875 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12876 SE.getTypeSizeInBits(NewBECount->getType())) 12877 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12878 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12879 SE.getTypeSizeInBits(NewBECount->getType())) 12880 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12881 12882 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12883 12884 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12885 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12886 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12887 dbgs() << "Old: " << *CurBECount << "\n"; 12888 dbgs() << "New: " << *NewBECount << "\n"; 12889 dbgs() << "Delta: " << *Delta << "\n"; 12890 std::abort(); 12891 } 12892 } 12893 12894 // Collect all valid loops currently in LoopInfo. 12895 SmallPtrSet<Loop *, 32> ValidLoops; 12896 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12897 while (!Worklist.empty()) { 12898 Loop *L = Worklist.pop_back_val(); 12899 if (ValidLoops.contains(L)) 12900 continue; 12901 ValidLoops.insert(L); 12902 Worklist.append(L->begin(), L->end()); 12903 } 12904 // Check for SCEV expressions referencing invalid/deleted loops. 12905 for (auto &KV : ValueExprMap) { 12906 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12907 if (!AR) 12908 continue; 12909 assert(ValidLoops.contains(AR->getLoop()) && 12910 "AddRec references invalid loop"); 12911 } 12912 } 12913 12914 bool ScalarEvolution::invalidate( 12915 Function &F, const PreservedAnalyses &PA, 12916 FunctionAnalysisManager::Invalidator &Inv) { 12917 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12918 // of its dependencies is invalidated. 12919 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12920 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12921 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12922 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12923 Inv.invalidate<LoopAnalysis>(F, PA); 12924 } 12925 12926 AnalysisKey ScalarEvolutionAnalysis::Key; 12927 12928 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12929 FunctionAnalysisManager &AM) { 12930 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12931 AM.getResult<AssumptionAnalysis>(F), 12932 AM.getResult<DominatorTreeAnalysis>(F), 12933 AM.getResult<LoopAnalysis>(F)); 12934 } 12935 12936 PreservedAnalyses 12937 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12938 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12939 return PreservedAnalyses::all(); 12940 } 12941 12942 PreservedAnalyses 12943 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12944 // For compatibility with opt's -analyze feature under legacy pass manager 12945 // which was not ported to NPM. This keeps tests using 12946 // update_analyze_test_checks.py working. 12947 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12948 << F.getName() << "':\n"; 12949 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12950 return PreservedAnalyses::all(); 12951 } 12952 12953 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12954 "Scalar Evolution Analysis", false, true) 12955 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12956 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12957 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12958 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12959 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12960 "Scalar Evolution Analysis", false, true) 12961 12962 char ScalarEvolutionWrapperPass::ID = 0; 12963 12964 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12965 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12966 } 12967 12968 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12969 SE.reset(new ScalarEvolution( 12970 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12971 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12972 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12973 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12974 return false; 12975 } 12976 12977 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12978 12979 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12980 SE->print(OS); 12981 } 12982 12983 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12984 if (!VerifySCEV) 12985 return; 12986 12987 SE->verify(); 12988 } 12989 12990 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12991 AU.setPreservesAll(); 12992 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12993 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12994 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12995 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12996 } 12997 12998 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12999 const SCEV *RHS) { 13000 FoldingSetNodeID ID; 13001 assert(LHS->getType() == RHS->getType() && 13002 "Type mismatch between LHS and RHS"); 13003 // Unique this node based on the arguments 13004 ID.AddInteger(SCEVPredicate::P_Equal); 13005 ID.AddPointer(LHS); 13006 ID.AddPointer(RHS); 13007 void *IP = nullptr; 13008 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13009 return S; 13010 SCEVEqualPredicate *Eq = new (SCEVAllocator) 13011 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 13012 UniquePreds.InsertNode(Eq, IP); 13013 return Eq; 13014 } 13015 13016 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 13017 const SCEVAddRecExpr *AR, 13018 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13019 FoldingSetNodeID ID; 13020 // Unique this node based on the arguments 13021 ID.AddInteger(SCEVPredicate::P_Wrap); 13022 ID.AddPointer(AR); 13023 ID.AddInteger(AddedFlags); 13024 void *IP = nullptr; 13025 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13026 return S; 13027 auto *OF = new (SCEVAllocator) 13028 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 13029 UniquePreds.InsertNode(OF, IP); 13030 return OF; 13031 } 13032 13033 namespace { 13034 13035 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 13036 public: 13037 13038 /// Rewrites \p S in the context of a loop L and the SCEV predication 13039 /// infrastructure. 13040 /// 13041 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 13042 /// equivalences present in \p Pred. 13043 /// 13044 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 13045 /// \p NewPreds such that the result will be an AddRecExpr. 13046 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 13047 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13048 SCEVUnionPredicate *Pred) { 13049 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 13050 return Rewriter.visit(S); 13051 } 13052 13053 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13054 if (Pred) { 13055 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 13056 for (auto *Pred : ExprPreds) 13057 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 13058 if (IPred->getLHS() == Expr) 13059 return IPred->getRHS(); 13060 } 13061 return convertToAddRecWithPreds(Expr); 13062 } 13063 13064 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 13065 const SCEV *Operand = visit(Expr->getOperand()); 13066 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13067 if (AR && AR->getLoop() == L && AR->isAffine()) { 13068 // This couldn't be folded because the operand didn't have the nuw 13069 // flag. Add the nusw flag as an assumption that we could make. 13070 const SCEV *Step = AR->getStepRecurrence(SE); 13071 Type *Ty = Expr->getType(); 13072 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 13073 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 13074 SE.getSignExtendExpr(Step, Ty), L, 13075 AR->getNoWrapFlags()); 13076 } 13077 return SE.getZeroExtendExpr(Operand, Expr->getType()); 13078 } 13079 13080 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 13081 const SCEV *Operand = visit(Expr->getOperand()); 13082 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13083 if (AR && AR->getLoop() == L && AR->isAffine()) { 13084 // This couldn't be folded because the operand didn't have the nsw 13085 // flag. Add the nssw flag as an assumption that we could make. 13086 const SCEV *Step = AR->getStepRecurrence(SE); 13087 Type *Ty = Expr->getType(); 13088 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 13089 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 13090 SE.getSignExtendExpr(Step, Ty), L, 13091 AR->getNoWrapFlags()); 13092 } 13093 return SE.getSignExtendExpr(Operand, Expr->getType()); 13094 } 13095 13096 private: 13097 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 13098 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13099 SCEVUnionPredicate *Pred) 13100 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 13101 13102 bool addOverflowAssumption(const SCEVPredicate *P) { 13103 if (!NewPreds) { 13104 // Check if we've already made this assumption. 13105 return Pred && Pred->implies(P); 13106 } 13107 NewPreds->insert(P); 13108 return true; 13109 } 13110 13111 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 13112 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13113 auto *A = SE.getWrapPredicate(AR, AddedFlags); 13114 return addOverflowAssumption(A); 13115 } 13116 13117 // If \p Expr represents a PHINode, we try to see if it can be represented 13118 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 13119 // to add this predicate as a runtime overflow check, we return the AddRec. 13120 // If \p Expr does not meet these conditions (is not a PHI node, or we 13121 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13122 // return \p Expr. 13123 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13124 if (!isa<PHINode>(Expr->getValue())) 13125 return Expr; 13126 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13127 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13128 if (!PredicatedRewrite) 13129 return Expr; 13130 for (auto *P : PredicatedRewrite->second){ 13131 // Wrap predicates from outer loops are not supported. 13132 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13133 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 13134 if (L != AR->getLoop()) 13135 return Expr; 13136 } 13137 if (!addOverflowAssumption(P)) 13138 return Expr; 13139 } 13140 return PredicatedRewrite->first; 13141 } 13142 13143 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13144 SCEVUnionPredicate *Pred; 13145 const Loop *L; 13146 }; 13147 13148 } // end anonymous namespace 13149 13150 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13151 SCEVUnionPredicate &Preds) { 13152 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13153 } 13154 13155 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13156 const SCEV *S, const Loop *L, 13157 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13158 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13159 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13160 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13161 13162 if (!AddRec) 13163 return nullptr; 13164 13165 // Since the transformation was successful, we can now transfer the SCEV 13166 // predicates. 13167 for (auto *P : TransformPreds) 13168 Preds.insert(P); 13169 13170 return AddRec; 13171 } 13172 13173 /// SCEV predicates 13174 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13175 SCEVPredicateKind Kind) 13176 : FastID(ID), Kind(Kind) {} 13177 13178 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 13179 const SCEV *LHS, const SCEV *RHS) 13180 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 13181 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13182 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13183 } 13184 13185 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 13186 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 13187 13188 if (!Op) 13189 return false; 13190 13191 return Op->LHS == LHS && Op->RHS == RHS; 13192 } 13193 13194 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 13195 13196 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 13197 13198 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 13199 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13200 } 13201 13202 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13203 const SCEVAddRecExpr *AR, 13204 IncrementWrapFlags Flags) 13205 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13206 13207 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 13208 13209 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 13210 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 13211 13212 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 13213 } 13214 13215 bool SCEVWrapPredicate::isAlwaysTrue() const { 13216 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 13217 IncrementWrapFlags IFlags = Flags; 13218 13219 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 13220 IFlags = clearFlags(IFlags, IncrementNSSW); 13221 13222 return IFlags == IncrementAnyWrap; 13223 } 13224 13225 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 13226 OS.indent(Depth) << *getExpr() << " Added Flags: "; 13227 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 13228 OS << "<nusw>"; 13229 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 13230 OS << "<nssw>"; 13231 OS << "\n"; 13232 } 13233 13234 SCEVWrapPredicate::IncrementWrapFlags 13235 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 13236 ScalarEvolution &SE) { 13237 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 13238 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 13239 13240 // We can safely transfer the NSW flag as NSSW. 13241 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 13242 ImpliedFlags = IncrementNSSW; 13243 13244 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 13245 // If the increment is positive, the SCEV NUW flag will also imply the 13246 // WrapPredicate NUSW flag. 13247 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 13248 if (Step->getValue()->getValue().isNonNegative()) 13249 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 13250 } 13251 13252 return ImpliedFlags; 13253 } 13254 13255 /// Union predicates don't get cached so create a dummy set ID for it. 13256 SCEVUnionPredicate::SCEVUnionPredicate() 13257 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 13258 13259 bool SCEVUnionPredicate::isAlwaysTrue() const { 13260 return all_of(Preds, 13261 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 13262 } 13263 13264 ArrayRef<const SCEVPredicate *> 13265 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 13266 auto I = SCEVToPreds.find(Expr); 13267 if (I == SCEVToPreds.end()) 13268 return ArrayRef<const SCEVPredicate *>(); 13269 return I->second; 13270 } 13271 13272 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 13273 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 13274 return all_of(Set->Preds, 13275 [this](const SCEVPredicate *I) { return this->implies(I); }); 13276 13277 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 13278 if (ScevPredsIt == SCEVToPreds.end()) 13279 return false; 13280 auto &SCEVPreds = ScevPredsIt->second; 13281 13282 return any_of(SCEVPreds, 13283 [N](const SCEVPredicate *I) { return I->implies(N); }); 13284 } 13285 13286 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 13287 13288 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 13289 for (auto Pred : Preds) 13290 Pred->print(OS, Depth); 13291 } 13292 13293 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 13294 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 13295 for (auto Pred : Set->Preds) 13296 add(Pred); 13297 return; 13298 } 13299 13300 if (implies(N)) 13301 return; 13302 13303 const SCEV *Key = N->getExpr(); 13304 assert(Key && "Only SCEVUnionPredicate doesn't have an " 13305 " associated expression!"); 13306 13307 SCEVToPreds[Key].push_back(N); 13308 Preds.push_back(N); 13309 } 13310 13311 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 13312 Loop &L) 13313 : SE(SE), L(L) {} 13314 13315 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 13316 const SCEV *Expr = SE.getSCEV(V); 13317 RewriteEntry &Entry = RewriteMap[Expr]; 13318 13319 // If we already have an entry and the version matches, return it. 13320 if (Entry.second && Generation == Entry.first) 13321 return Entry.second; 13322 13323 // We found an entry but it's stale. Rewrite the stale entry 13324 // according to the current predicate. 13325 if (Entry.second) 13326 Expr = Entry.second; 13327 13328 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 13329 Entry = {Generation, NewSCEV}; 13330 13331 return NewSCEV; 13332 } 13333 13334 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13335 if (!BackedgeCount) { 13336 SCEVUnionPredicate BackedgePred; 13337 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 13338 addPredicate(BackedgePred); 13339 } 13340 return BackedgeCount; 13341 } 13342 13343 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13344 if (Preds.implies(&Pred)) 13345 return; 13346 Preds.add(&Pred); 13347 updateGeneration(); 13348 } 13349 13350 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 13351 return Preds; 13352 } 13353 13354 void PredicatedScalarEvolution::updateGeneration() { 13355 // If the generation number wrapped recompute everything. 13356 if (++Generation == 0) { 13357 for (auto &II : RewriteMap) { 13358 const SCEV *Rewritten = II.second.second; 13359 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 13360 } 13361 } 13362 } 13363 13364 void PredicatedScalarEvolution::setNoOverflow( 13365 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13366 const SCEV *Expr = getSCEV(V); 13367 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13368 13369 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13370 13371 // Clear the statically implied flags. 13372 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13373 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13374 13375 auto II = FlagsMap.insert({V, Flags}); 13376 if (!II.second) 13377 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13378 } 13379 13380 bool PredicatedScalarEvolution::hasNoOverflow( 13381 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13382 const SCEV *Expr = getSCEV(V); 13383 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13384 13385 Flags = SCEVWrapPredicate::clearFlags( 13386 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13387 13388 auto II = FlagsMap.find(V); 13389 13390 if (II != FlagsMap.end()) 13391 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13392 13393 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13394 } 13395 13396 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13397 const SCEV *Expr = this->getSCEV(V); 13398 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13399 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13400 13401 if (!New) 13402 return nullptr; 13403 13404 for (auto *P : NewPreds) 13405 Preds.add(P); 13406 13407 updateGeneration(); 13408 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13409 return New; 13410 } 13411 13412 PredicatedScalarEvolution::PredicatedScalarEvolution( 13413 const PredicatedScalarEvolution &Init) 13414 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13415 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13416 for (auto I : Init.FlagsMap) 13417 FlagsMap.insert(I); 13418 } 13419 13420 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13421 // For each block. 13422 for (auto *BB : L.getBlocks()) 13423 for (auto &I : *BB) { 13424 if (!SE.isSCEVable(I.getType())) 13425 continue; 13426 13427 auto *Expr = SE.getSCEV(&I); 13428 auto II = RewriteMap.find(Expr); 13429 13430 if (II == RewriteMap.end()) 13431 continue; 13432 13433 // Don't print things that are not interesting. 13434 if (II->second.second == Expr) 13435 continue; 13436 13437 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13438 OS.indent(Depth + 2) << *Expr << "\n"; 13439 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13440 } 13441 } 13442 13443 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13444 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13445 // for URem with constant power-of-2 second operands. 13446 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13447 // 4, A / B becomes X / 8). 13448 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13449 const SCEV *&RHS) { 13450 // Try to match 'zext (trunc A to iB) to iY', which is used 13451 // for URem with constant power-of-2 second operands. Make sure the size of 13452 // the operand A matches the size of the whole expressions. 13453 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13454 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13455 LHS = Trunc->getOperand(); 13456 // Bail out if the type of the LHS is larger than the type of the 13457 // expression for now. 13458 if (getTypeSizeInBits(LHS->getType()) > 13459 getTypeSizeInBits(Expr->getType())) 13460 return false; 13461 if (LHS->getType() != Expr->getType()) 13462 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13463 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13464 << getTypeSizeInBits(Trunc->getType())); 13465 return true; 13466 } 13467 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13468 if (Add == nullptr || Add->getNumOperands() != 2) 13469 return false; 13470 13471 const SCEV *A = Add->getOperand(1); 13472 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13473 13474 if (Mul == nullptr) 13475 return false; 13476 13477 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13478 // (SomeExpr + (-(SomeExpr / B) * B)). 13479 if (Expr == getURemExpr(A, B)) { 13480 LHS = A; 13481 RHS = B; 13482 return true; 13483 } 13484 return false; 13485 }; 13486 13487 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13488 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13489 return MatchURemWithDivisor(Mul->getOperand(1)) || 13490 MatchURemWithDivisor(Mul->getOperand(2)); 13491 13492 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13493 if (Mul->getNumOperands() == 2) 13494 return MatchURemWithDivisor(Mul->getOperand(1)) || 13495 MatchURemWithDivisor(Mul->getOperand(0)) || 13496 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 13497 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 13498 return false; 13499 } 13500 13501 const SCEV * 13502 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 13503 SmallVector<BasicBlock*, 16> ExitingBlocks; 13504 L->getExitingBlocks(ExitingBlocks); 13505 13506 // Form an expression for the maximum exit count possible for this loop. We 13507 // merge the max and exact information to approximate a version of 13508 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 13509 SmallVector<const SCEV*, 4> ExitCounts; 13510 for (BasicBlock *ExitingBB : ExitingBlocks) { 13511 const SCEV *ExitCount = getExitCount(L, ExitingBB); 13512 if (isa<SCEVCouldNotCompute>(ExitCount)) 13513 ExitCount = getExitCount(L, ExitingBB, 13514 ScalarEvolution::ConstantMaximum); 13515 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 13516 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 13517 "We should only have known counts for exiting blocks that " 13518 "dominate latch!"); 13519 ExitCounts.push_back(ExitCount); 13520 } 13521 } 13522 if (ExitCounts.empty()) 13523 return getCouldNotCompute(); 13524 return getUMinFromMismatchedTypes(ExitCounts); 13525 } 13526 13527 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 13528 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 13529 /// we cannot guarantee that the replacement is loop invariant in the loop of 13530 /// the AddRec. 13531 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 13532 ValueToSCEVMapTy ⤅ 13533 13534 public: 13535 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 13536 : SCEVRewriteVisitor(SE), Map(M) {} 13537 13538 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 13539 13540 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13541 auto I = Map.find(Expr->getValue()); 13542 if (I == Map.end()) 13543 return Expr; 13544 return I->second; 13545 } 13546 }; 13547 13548 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 13549 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 13550 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 13551 // If we have LHS == 0, check if LHS is computing a property of some unknown 13552 // SCEV %v which we can rewrite %v to express explicitly. 13553 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 13554 if (Predicate == CmpInst::ICMP_EQ && RHSC && 13555 RHSC->getValue()->isNullValue()) { 13556 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 13557 // explicitly express that. 13558 const SCEV *URemLHS = nullptr; 13559 const SCEV *URemRHS = nullptr; 13560 if (matchURem(LHS, URemLHS, URemRHS)) { 13561 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 13562 Value *V = LHSUnknown->getValue(); 13563 auto Multiple = 13564 getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS, 13565 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 13566 RewriteMap[V] = Multiple; 13567 return; 13568 } 13569 } 13570 } 13571 13572 if (!isa<SCEVUnknown>(LHS)) { 13573 std::swap(LHS, RHS); 13574 Predicate = CmpInst::getSwappedPredicate(Predicate); 13575 } 13576 13577 // For now, limit to conditions that provide information about unknown 13578 // expressions. 13579 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 13580 if (!LHSUnknown) 13581 return; 13582 13583 // Check whether LHS has already been rewritten. In that case we want to 13584 // chain further rewrites onto the already rewritten value. 13585 auto I = RewriteMap.find(LHSUnknown->getValue()); 13586 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 13587 13588 // TODO: use information from more predicates. 13589 switch (Predicate) { 13590 case CmpInst::ICMP_ULT: 13591 if (!containsAddRecurrence(RHS)) 13592 RewriteMap[LHSUnknown->getValue()] = getUMinExpr( 13593 RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13594 break; 13595 case CmpInst::ICMP_ULE: 13596 if (!containsAddRecurrence(RHS)) 13597 RewriteMap[LHSUnknown->getValue()] = getUMinExpr(RewrittenLHS, RHS); 13598 break; 13599 case CmpInst::ICMP_UGT: 13600 if (!containsAddRecurrence(RHS)) 13601 RewriteMap[LHSUnknown->getValue()] = 13602 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13603 break; 13604 case CmpInst::ICMP_UGE: 13605 if (!containsAddRecurrence(RHS)) 13606 RewriteMap[LHSUnknown->getValue()] = getUMaxExpr(RewrittenLHS, RHS); 13607 break; 13608 case CmpInst::ICMP_EQ: 13609 if (isa<SCEVConstant>(RHS)) 13610 RewriteMap[LHSUnknown->getValue()] = RHS; 13611 break; 13612 case CmpInst::ICMP_NE: 13613 if (isa<SCEVConstant>(RHS) && 13614 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 13615 RewriteMap[LHSUnknown->getValue()] = 13616 getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 13617 break; 13618 default: 13619 break; 13620 } 13621 }; 13622 // Starting at the loop predecessor, climb up the predecessor chain, as long 13623 // as there are predecessors that can be found that have unique successors 13624 // leading to the original header. 13625 // TODO: share this logic with isLoopEntryGuardedByCond. 13626 ValueToSCEVMapTy RewriteMap; 13627 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 13628 L->getLoopPredecessor(), L->getHeader()); 13629 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 13630 13631 const BranchInst *LoopEntryPredicate = 13632 dyn_cast<BranchInst>(Pair.first->getTerminator()); 13633 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 13634 continue; 13635 13636 bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second; 13637 SmallVector<Value *, 8> Worklist; 13638 SmallPtrSet<Value *, 8> Visited; 13639 Worklist.push_back(LoopEntryPredicate->getCondition()); 13640 while (!Worklist.empty()) { 13641 Value *Cond = Worklist.pop_back_val(); 13642 if (!Visited.insert(Cond).second) 13643 continue; 13644 13645 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 13646 auto Predicate = 13647 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 13648 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 13649 getSCEV(Cmp->getOperand(1)), RewriteMap); 13650 continue; 13651 } 13652 13653 Value *L, *R; 13654 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 13655 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 13656 Worklist.push_back(L); 13657 Worklist.push_back(R); 13658 } 13659 } 13660 } 13661 13662 // Also collect information from assumptions dominating the loop. 13663 for (auto &AssumeVH : AC.assumptions()) { 13664 if (!AssumeVH) 13665 continue; 13666 auto *AssumeI = cast<CallInst>(AssumeVH); 13667 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 13668 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 13669 continue; 13670 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 13671 getSCEV(Cmp->getOperand(1)), RewriteMap); 13672 } 13673 13674 if (RewriteMap.empty()) 13675 return Expr; 13676 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 13677 return Rewriter.visit(Expr); 13678 } 13679