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 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2248 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2249 // can't-overflow flags for the operation if possible. 2250 static SCEV::NoWrapFlags 2251 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2252 const ArrayRef<const SCEV *> Ops, 2253 SCEV::NoWrapFlags Flags) { 2254 using namespace std::placeholders; 2255 2256 using OBO = OverflowingBinaryOperator; 2257 2258 bool CanAnalyze = 2259 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2260 (void)CanAnalyze; 2261 assert(CanAnalyze && "don't call from other places!"); 2262 2263 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2264 SCEV::NoWrapFlags SignOrUnsignWrap = 2265 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2266 2267 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2268 auto IsKnownNonNegative = [&](const SCEV *S) { 2269 return SE->isKnownNonNegative(S); 2270 }; 2271 2272 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2273 Flags = 2274 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2275 2276 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2277 2278 if (SignOrUnsignWrap != SignOrUnsignMask && 2279 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2280 isa<SCEVConstant>(Ops[0])) { 2281 2282 auto Opcode = [&] { 2283 switch (Type) { 2284 case scAddExpr: 2285 return Instruction::Add; 2286 case scMulExpr: 2287 return Instruction::Mul; 2288 default: 2289 llvm_unreachable("Unexpected SCEV op."); 2290 } 2291 }(); 2292 2293 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2294 2295 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2296 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2297 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2298 Opcode, C, OBO::NoSignedWrap); 2299 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2300 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2301 } 2302 2303 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2304 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2305 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2306 Opcode, C, OBO::NoUnsignedWrap); 2307 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2308 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2309 } 2310 } 2311 2312 return Flags; 2313 } 2314 2315 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2316 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2317 } 2318 2319 /// Get a canonical add expression, or something simpler if possible. 2320 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2321 SCEV::NoWrapFlags OrigFlags, 2322 unsigned Depth) { 2323 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2324 "only nuw or nsw allowed"); 2325 assert(!Ops.empty() && "Cannot get empty add!"); 2326 if (Ops.size() == 1) return Ops[0]; 2327 #ifndef NDEBUG 2328 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2329 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2330 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2331 "SCEVAddExpr operand types don't match!"); 2332 #endif 2333 2334 // Sort by complexity, this groups all similar expression types together. 2335 GroupByComplexity(Ops, &LI, DT); 2336 2337 // If there are any constants, fold them together. 2338 unsigned Idx = 0; 2339 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2340 ++Idx; 2341 assert(Idx < Ops.size()); 2342 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2343 // We found two constants, fold them together! 2344 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2345 if (Ops.size() == 2) return Ops[0]; 2346 Ops.erase(Ops.begin()+1); // Erase the folded element 2347 LHSC = cast<SCEVConstant>(Ops[0]); 2348 } 2349 2350 // If we are left with a constant zero being added, strip it off. 2351 if (LHSC->getValue()->isZero()) { 2352 Ops.erase(Ops.begin()); 2353 --Idx; 2354 } 2355 2356 if (Ops.size() == 1) return Ops[0]; 2357 } 2358 2359 // Delay expensive flag strengthening until necessary. 2360 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2361 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2362 }; 2363 2364 // Limit recursion calls depth. 2365 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2366 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2367 2368 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) { 2369 // Don't strengthen flags if we have no new information. 2370 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2371 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2372 Add->setNoWrapFlags(ComputeFlags(Ops)); 2373 return S; 2374 } 2375 2376 // Okay, check to see if the same value occurs in the operand list more than 2377 // once. If so, merge them together into an multiply expression. Since we 2378 // sorted the list, these values are required to be adjacent. 2379 Type *Ty = Ops[0]->getType(); 2380 bool FoundMatch = false; 2381 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2382 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2383 // Scan ahead to count how many equal operands there are. 2384 unsigned Count = 2; 2385 while (i+Count != e && Ops[i+Count] == Ops[i]) 2386 ++Count; 2387 // Merge the values into a multiply. 2388 const SCEV *Scale = getConstant(Ty, Count); 2389 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2390 if (Ops.size() == Count) 2391 return Mul; 2392 Ops[i] = Mul; 2393 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2394 --i; e -= Count - 1; 2395 FoundMatch = true; 2396 } 2397 if (FoundMatch) 2398 return getAddExpr(Ops, OrigFlags, Depth + 1); 2399 2400 // Check for truncates. If all the operands are truncated from the same 2401 // type, see if factoring out the truncate would permit the result to be 2402 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2403 // if the contents of the resulting outer trunc fold to something simple. 2404 auto FindTruncSrcType = [&]() -> Type * { 2405 // We're ultimately looking to fold an addrec of truncs and muls of only 2406 // constants and truncs, so if we find any other types of SCEV 2407 // as operands of the addrec then we bail and return nullptr here. 2408 // Otherwise, we return the type of the operand of a trunc that we find. 2409 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2410 return T->getOperand()->getType(); 2411 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2412 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2413 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2414 return T->getOperand()->getType(); 2415 } 2416 return nullptr; 2417 }; 2418 if (auto *SrcType = FindTruncSrcType()) { 2419 SmallVector<const SCEV *, 8> LargeOps; 2420 bool Ok = true; 2421 // Check all the operands to see if they can be represented in the 2422 // source type of the truncate. 2423 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2424 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2425 if (T->getOperand()->getType() != SrcType) { 2426 Ok = false; 2427 break; 2428 } 2429 LargeOps.push_back(T->getOperand()); 2430 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2431 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2432 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2433 SmallVector<const SCEV *, 8> LargeMulOps; 2434 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2435 if (const SCEVTruncateExpr *T = 2436 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2437 if (T->getOperand()->getType() != SrcType) { 2438 Ok = false; 2439 break; 2440 } 2441 LargeMulOps.push_back(T->getOperand()); 2442 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2443 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2444 } else { 2445 Ok = false; 2446 break; 2447 } 2448 } 2449 if (Ok) 2450 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2451 } else { 2452 Ok = false; 2453 break; 2454 } 2455 } 2456 if (Ok) { 2457 // Evaluate the expression in the larger type. 2458 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2459 // If it folds to something simple, use it. Otherwise, don't. 2460 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2461 return getTruncateExpr(Fold, Ty); 2462 } 2463 } 2464 2465 // Skip past any other cast SCEVs. 2466 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2467 ++Idx; 2468 2469 // If there are add operands they would be next. 2470 if (Idx < Ops.size()) { 2471 bool DeletedAdd = false; 2472 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2473 if (Ops.size() > AddOpsInlineThreshold || 2474 Add->getNumOperands() > AddOpsInlineThreshold) 2475 break; 2476 // If we have an add, expand the add operands onto the end of the operands 2477 // list. 2478 Ops.erase(Ops.begin()+Idx); 2479 Ops.append(Add->op_begin(), Add->op_end()); 2480 DeletedAdd = true; 2481 } 2482 2483 // If we deleted at least one add, we added operands to the end of the list, 2484 // and they are not necessarily sorted. Recurse to resort and resimplify 2485 // any operands we just acquired. 2486 if (DeletedAdd) 2487 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2488 } 2489 2490 // Skip over the add expression until we get to a multiply. 2491 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2492 ++Idx; 2493 2494 // Check to see if there are any folding opportunities present with 2495 // operands multiplied by constant values. 2496 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2497 uint64_t BitWidth = getTypeSizeInBits(Ty); 2498 DenseMap<const SCEV *, APInt> M; 2499 SmallVector<const SCEV *, 8> NewOps; 2500 APInt AccumulatedConstant(BitWidth, 0); 2501 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2502 Ops.data(), Ops.size(), 2503 APInt(BitWidth, 1), *this)) { 2504 struct APIntCompare { 2505 bool operator()(const APInt &LHS, const APInt &RHS) const { 2506 return LHS.ult(RHS); 2507 } 2508 }; 2509 2510 // Some interesting folding opportunity is present, so its worthwhile to 2511 // re-generate the operands list. Group the operands by constant scale, 2512 // to avoid multiplying by the same constant scale multiple times. 2513 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2514 for (const SCEV *NewOp : NewOps) 2515 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2516 // Re-generate the operands list. 2517 Ops.clear(); 2518 if (AccumulatedConstant != 0) 2519 Ops.push_back(getConstant(AccumulatedConstant)); 2520 for (auto &MulOp : MulOpLists) 2521 if (MulOp.first != 0) 2522 Ops.push_back(getMulExpr( 2523 getConstant(MulOp.first), 2524 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2525 SCEV::FlagAnyWrap, Depth + 1)); 2526 if (Ops.empty()) 2527 return getZero(Ty); 2528 if (Ops.size() == 1) 2529 return Ops[0]; 2530 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2531 } 2532 } 2533 2534 // If we are adding something to a multiply expression, make sure the 2535 // something is not already an operand of the multiply. If so, merge it into 2536 // the multiply. 2537 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2538 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2539 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2540 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2541 if (isa<SCEVConstant>(MulOpSCEV)) 2542 continue; 2543 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2544 if (MulOpSCEV == Ops[AddOp]) { 2545 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2546 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2547 if (Mul->getNumOperands() != 2) { 2548 // If the multiply has more than two operands, we must get the 2549 // Y*Z term. 2550 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2551 Mul->op_begin()+MulOp); 2552 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2553 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2554 } 2555 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2556 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2557 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2558 SCEV::FlagAnyWrap, Depth + 1); 2559 if (Ops.size() == 2) return OuterMul; 2560 if (AddOp < Idx) { 2561 Ops.erase(Ops.begin()+AddOp); 2562 Ops.erase(Ops.begin()+Idx-1); 2563 } else { 2564 Ops.erase(Ops.begin()+Idx); 2565 Ops.erase(Ops.begin()+AddOp-1); 2566 } 2567 Ops.push_back(OuterMul); 2568 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2569 } 2570 2571 // Check this multiply against other multiplies being added together. 2572 for (unsigned OtherMulIdx = Idx+1; 2573 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2574 ++OtherMulIdx) { 2575 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2576 // If MulOp occurs in OtherMul, we can fold the two multiplies 2577 // together. 2578 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2579 OMulOp != e; ++OMulOp) 2580 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2581 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2582 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2583 if (Mul->getNumOperands() != 2) { 2584 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2585 Mul->op_begin()+MulOp); 2586 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2587 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2588 } 2589 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2590 if (OtherMul->getNumOperands() != 2) { 2591 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2592 OtherMul->op_begin()+OMulOp); 2593 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2594 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2595 } 2596 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2597 const SCEV *InnerMulSum = 2598 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2599 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2600 SCEV::FlagAnyWrap, Depth + 1); 2601 if (Ops.size() == 2) return OuterMul; 2602 Ops.erase(Ops.begin()+Idx); 2603 Ops.erase(Ops.begin()+OtherMulIdx-1); 2604 Ops.push_back(OuterMul); 2605 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2606 } 2607 } 2608 } 2609 } 2610 2611 // If there are any add recurrences in the operands list, see if any other 2612 // added values are loop invariant. If so, we can fold them into the 2613 // recurrence. 2614 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2615 ++Idx; 2616 2617 // Scan over all recurrences, trying to fold loop invariants into them. 2618 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2619 // Scan all of the other operands to this add and add them to the vector if 2620 // they are loop invariant w.r.t. the recurrence. 2621 SmallVector<const SCEV *, 8> LIOps; 2622 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2623 const Loop *AddRecLoop = AddRec->getLoop(); 2624 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2625 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2626 LIOps.push_back(Ops[i]); 2627 Ops.erase(Ops.begin()+i); 2628 --i; --e; 2629 } 2630 2631 // If we found some loop invariants, fold them into the recurrence. 2632 if (!LIOps.empty()) { 2633 // Compute nowrap flags for the addition of the loop-invariant ops and 2634 // the addrec. Temporarily push it as an operand for that purpose. 2635 LIOps.push_back(AddRec); 2636 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2637 LIOps.pop_back(); 2638 2639 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2640 LIOps.push_back(AddRec->getStart()); 2641 2642 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2643 // This follows from the fact that the no-wrap flags on the outer add 2644 // expression are applicable on the 0th iteration, when the add recurrence 2645 // will be equal to its start value. 2646 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2647 2648 // Build the new addrec. Propagate the NUW and NSW flags if both the 2649 // outer add and the inner addrec are guaranteed to have no overflow. 2650 // Always propagate NW. 2651 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2652 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2653 2654 // If all of the other operands were loop invariant, we are done. 2655 if (Ops.size() == 1) return NewRec; 2656 2657 // Otherwise, add the folded AddRec by the non-invariant parts. 2658 for (unsigned i = 0;; ++i) 2659 if (Ops[i] == AddRec) { 2660 Ops[i] = NewRec; 2661 break; 2662 } 2663 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2664 } 2665 2666 // Okay, if there weren't any loop invariants to be folded, check to see if 2667 // there are multiple AddRec's with the same loop induction variable being 2668 // added together. If so, we can fold them. 2669 for (unsigned OtherIdx = Idx+1; 2670 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2671 ++OtherIdx) { 2672 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2673 // so that the 1st found AddRecExpr is dominated by all others. 2674 assert(DT.dominates( 2675 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2676 AddRec->getLoop()->getHeader()) && 2677 "AddRecExprs are not sorted in reverse dominance order?"); 2678 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2679 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2680 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2681 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2682 ++OtherIdx) { 2683 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2684 if (OtherAddRec->getLoop() == AddRecLoop) { 2685 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2686 i != e; ++i) { 2687 if (i >= AddRecOps.size()) { 2688 AddRecOps.append(OtherAddRec->op_begin()+i, 2689 OtherAddRec->op_end()); 2690 break; 2691 } 2692 SmallVector<const SCEV *, 2> TwoOps = { 2693 AddRecOps[i], OtherAddRec->getOperand(i)}; 2694 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2695 } 2696 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2697 } 2698 } 2699 // Step size has changed, so we cannot guarantee no self-wraparound. 2700 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2701 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2702 } 2703 } 2704 2705 // Otherwise couldn't fold anything into this recurrence. Move onto the 2706 // next one. 2707 } 2708 2709 // Okay, it looks like we really DO need an add expr. Check to see if we 2710 // already have one, otherwise create a new one. 2711 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2712 } 2713 2714 const SCEV * 2715 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2716 SCEV::NoWrapFlags Flags) { 2717 FoldingSetNodeID ID; 2718 ID.AddInteger(scAddExpr); 2719 for (const SCEV *Op : Ops) 2720 ID.AddPointer(Op); 2721 void *IP = nullptr; 2722 SCEVAddExpr *S = 2723 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2724 if (!S) { 2725 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2726 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2727 S = new (SCEVAllocator) 2728 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2729 UniqueSCEVs.InsertNode(S, IP); 2730 addToLoopUseLists(S); 2731 } 2732 S->setNoWrapFlags(Flags); 2733 return S; 2734 } 2735 2736 const SCEV * 2737 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2738 const Loop *L, SCEV::NoWrapFlags Flags) { 2739 FoldingSetNodeID ID; 2740 ID.AddInteger(scAddRecExpr); 2741 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2742 ID.AddPointer(Ops[i]); 2743 ID.AddPointer(L); 2744 void *IP = nullptr; 2745 SCEVAddRecExpr *S = 2746 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2747 if (!S) { 2748 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2749 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2750 S = new (SCEVAllocator) 2751 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2752 UniqueSCEVs.InsertNode(S, IP); 2753 addToLoopUseLists(S); 2754 } 2755 setNoWrapFlags(S, Flags); 2756 return S; 2757 } 2758 2759 const SCEV * 2760 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2761 SCEV::NoWrapFlags Flags) { 2762 FoldingSetNodeID ID; 2763 ID.AddInteger(scMulExpr); 2764 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2765 ID.AddPointer(Ops[i]); 2766 void *IP = nullptr; 2767 SCEVMulExpr *S = 2768 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2769 if (!S) { 2770 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2771 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2772 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2773 O, Ops.size()); 2774 UniqueSCEVs.InsertNode(S, IP); 2775 addToLoopUseLists(S); 2776 } 2777 S->setNoWrapFlags(Flags); 2778 return S; 2779 } 2780 2781 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2782 uint64_t k = i*j; 2783 if (j > 1 && k / j != i) Overflow = true; 2784 return k; 2785 } 2786 2787 /// Compute the result of "n choose k", the binomial coefficient. If an 2788 /// intermediate computation overflows, Overflow will be set and the return will 2789 /// be garbage. Overflow is not cleared on absence of overflow. 2790 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2791 // We use the multiplicative formula: 2792 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2793 // At each iteration, we take the n-th term of the numeral and divide by the 2794 // (k-n)th term of the denominator. This division will always produce an 2795 // integral result, and helps reduce the chance of overflow in the 2796 // intermediate computations. However, we can still overflow even when the 2797 // final result would fit. 2798 2799 if (n == 0 || n == k) return 1; 2800 if (k > n) return 0; 2801 2802 if (k > n/2) 2803 k = n-k; 2804 2805 uint64_t r = 1; 2806 for (uint64_t i = 1; i <= k; ++i) { 2807 r = umul_ov(r, n-(i-1), Overflow); 2808 r /= i; 2809 } 2810 return r; 2811 } 2812 2813 /// Determine if any of the operands in this SCEV are a constant or if 2814 /// any of the add or multiply expressions in this SCEV contain a constant. 2815 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2816 struct FindConstantInAddMulChain { 2817 bool FoundConstant = false; 2818 2819 bool follow(const SCEV *S) { 2820 FoundConstant |= isa<SCEVConstant>(S); 2821 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2822 } 2823 2824 bool isDone() const { 2825 return FoundConstant; 2826 } 2827 }; 2828 2829 FindConstantInAddMulChain F; 2830 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2831 ST.visitAll(StartExpr); 2832 return F.FoundConstant; 2833 } 2834 2835 /// Get a canonical multiply expression, or something simpler if possible. 2836 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2837 SCEV::NoWrapFlags OrigFlags, 2838 unsigned Depth) { 2839 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 2840 "only nuw or nsw allowed"); 2841 assert(!Ops.empty() && "Cannot get empty mul!"); 2842 if (Ops.size() == 1) return Ops[0]; 2843 #ifndef NDEBUG 2844 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2845 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2846 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2847 "SCEVMulExpr operand types don't match!"); 2848 #endif 2849 2850 // Sort by complexity, this groups all similar expression types together. 2851 GroupByComplexity(Ops, &LI, DT); 2852 2853 // If there are any constants, fold them together. 2854 unsigned Idx = 0; 2855 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2856 ++Idx; 2857 assert(Idx < Ops.size()); 2858 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2859 // We found two constants, fold them together! 2860 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 2861 if (Ops.size() == 2) return Ops[0]; 2862 Ops.erase(Ops.begin()+1); // Erase the folded element 2863 LHSC = cast<SCEVConstant>(Ops[0]); 2864 } 2865 2866 // If we have a multiply of zero, it will always be zero. 2867 if (LHSC->getValue()->isZero()) 2868 return LHSC; 2869 2870 // If we are left with a constant one being multiplied, strip it off. 2871 if (LHSC->getValue()->isOne()) { 2872 Ops.erase(Ops.begin()); 2873 --Idx; 2874 } 2875 2876 if (Ops.size() == 1) 2877 return Ops[0]; 2878 } 2879 2880 // Delay expensive flag strengthening until necessary. 2881 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2882 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 2883 }; 2884 2885 // Limit recursion calls depth. 2886 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2887 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 2888 2889 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { 2890 // Don't strengthen flags if we have no new information. 2891 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 2892 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 2893 Mul->setNoWrapFlags(ComputeFlags(Ops)); 2894 return S; 2895 } 2896 2897 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2898 if (Ops.size() == 2) { 2899 // C1*(C2+V) -> C1*C2 + C1*V 2900 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2901 // If any of Add's ops are Adds or Muls with a constant, apply this 2902 // transformation as well. 2903 // 2904 // TODO: There are some cases where this transformation is not 2905 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2906 // this transformation should be narrowed down. 2907 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2908 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2909 SCEV::FlagAnyWrap, Depth + 1), 2910 getMulExpr(LHSC, Add->getOperand(1), 2911 SCEV::FlagAnyWrap, Depth + 1), 2912 SCEV::FlagAnyWrap, Depth + 1); 2913 2914 if (Ops[0]->isAllOnesValue()) { 2915 // If we have a mul by -1 of an add, try distributing the -1 among the 2916 // add operands. 2917 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2918 SmallVector<const SCEV *, 4> NewOps; 2919 bool AnyFolded = false; 2920 for (const SCEV *AddOp : Add->operands()) { 2921 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2922 Depth + 1); 2923 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2924 NewOps.push_back(Mul); 2925 } 2926 if (AnyFolded) 2927 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2928 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2929 // Negation preserves a recurrence's no self-wrap property. 2930 SmallVector<const SCEV *, 4> Operands; 2931 for (const SCEV *AddRecOp : AddRec->operands()) 2932 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2933 Depth + 1)); 2934 2935 return getAddRecExpr(Operands, AddRec->getLoop(), 2936 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2937 } 2938 } 2939 } 2940 } 2941 2942 // Skip over the add expression until we get to a multiply. 2943 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2944 ++Idx; 2945 2946 // If there are mul operands inline them all into this expression. 2947 if (Idx < Ops.size()) { 2948 bool DeletedMul = false; 2949 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2950 if (Ops.size() > MulOpsInlineThreshold) 2951 break; 2952 // If we have an mul, expand the mul operands onto the end of the 2953 // operands list. 2954 Ops.erase(Ops.begin()+Idx); 2955 Ops.append(Mul->op_begin(), Mul->op_end()); 2956 DeletedMul = true; 2957 } 2958 2959 // If we deleted at least one mul, we added operands to the end of the 2960 // list, and they are not necessarily sorted. Recurse to resort and 2961 // resimplify any operands we just acquired. 2962 if (DeletedMul) 2963 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2964 } 2965 2966 // If there are any add recurrences in the operands list, see if any other 2967 // added values are loop invariant. If so, we can fold them into the 2968 // recurrence. 2969 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2970 ++Idx; 2971 2972 // Scan over all recurrences, trying to fold loop invariants into them. 2973 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2974 // Scan all of the other operands to this mul and add them to the vector 2975 // if they are loop invariant w.r.t. the recurrence. 2976 SmallVector<const SCEV *, 8> LIOps; 2977 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2978 const Loop *AddRecLoop = AddRec->getLoop(); 2979 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2980 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2981 LIOps.push_back(Ops[i]); 2982 Ops.erase(Ops.begin()+i); 2983 --i; --e; 2984 } 2985 2986 // If we found some loop invariants, fold them into the recurrence. 2987 if (!LIOps.empty()) { 2988 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2989 SmallVector<const SCEV *, 4> NewOps; 2990 NewOps.reserve(AddRec->getNumOperands()); 2991 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2992 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2993 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2994 SCEV::FlagAnyWrap, Depth + 1)); 2995 2996 // Build the new addrec. Propagate the NUW and NSW flags if both the 2997 // outer mul and the inner addrec are guaranteed to have no overflow. 2998 // 2999 // No self-wrap cannot be guaranteed after changing the step size, but 3000 // will be inferred if either NUW or NSW is true. 3001 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 3002 const SCEV *NewRec = getAddRecExpr( 3003 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 3004 3005 // If all of the other operands were loop invariant, we are done. 3006 if (Ops.size() == 1) return NewRec; 3007 3008 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3009 for (unsigned i = 0;; ++i) 3010 if (Ops[i] == AddRec) { 3011 Ops[i] = NewRec; 3012 break; 3013 } 3014 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3015 } 3016 3017 // Okay, if there weren't any loop invariants to be folded, check to see 3018 // if there are multiple AddRec's with the same loop induction variable 3019 // being multiplied together. If so, we can fold them. 3020 3021 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3022 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3023 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3024 // ]]],+,...up to x=2n}. 3025 // Note that the arguments to choose() are always integers with values 3026 // known at compile time, never SCEV objects. 3027 // 3028 // The implementation avoids pointless extra computations when the two 3029 // addrec's are of different length (mathematically, it's equivalent to 3030 // an infinite stream of zeros on the right). 3031 bool OpsModified = false; 3032 for (unsigned OtherIdx = Idx+1; 3033 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3034 ++OtherIdx) { 3035 const SCEVAddRecExpr *OtherAddRec = 3036 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3037 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3038 continue; 3039 3040 // Limit max number of arguments to avoid creation of unreasonably big 3041 // SCEVAddRecs with very complex operands. 3042 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3043 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3044 continue; 3045 3046 bool Overflow = false; 3047 Type *Ty = AddRec->getType(); 3048 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3049 SmallVector<const SCEV*, 7> AddRecOps; 3050 for (int x = 0, xe = AddRec->getNumOperands() + 3051 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3052 SmallVector <const SCEV *, 7> SumOps; 3053 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3054 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3055 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3056 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3057 z < ze && !Overflow; ++z) { 3058 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3059 uint64_t Coeff; 3060 if (LargerThan64Bits) 3061 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3062 else 3063 Coeff = Coeff1*Coeff2; 3064 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3065 const SCEV *Term1 = AddRec->getOperand(y-z); 3066 const SCEV *Term2 = OtherAddRec->getOperand(z); 3067 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3068 SCEV::FlagAnyWrap, Depth + 1)); 3069 } 3070 } 3071 if (SumOps.empty()) 3072 SumOps.push_back(getZero(Ty)); 3073 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3074 } 3075 if (!Overflow) { 3076 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3077 SCEV::FlagAnyWrap); 3078 if (Ops.size() == 2) return NewAddRec; 3079 Ops[Idx] = NewAddRec; 3080 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3081 OpsModified = true; 3082 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3083 if (!AddRec) 3084 break; 3085 } 3086 } 3087 if (OpsModified) 3088 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3089 3090 // Otherwise couldn't fold anything into this recurrence. Move onto the 3091 // next one. 3092 } 3093 3094 // Okay, it looks like we really DO need an mul expr. Check to see if we 3095 // already have one, otherwise create a new one. 3096 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3097 } 3098 3099 /// Represents an unsigned remainder expression based on unsigned division. 3100 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3101 const SCEV *RHS) { 3102 assert(getEffectiveSCEVType(LHS->getType()) == 3103 getEffectiveSCEVType(RHS->getType()) && 3104 "SCEVURemExpr operand types don't match!"); 3105 3106 // Short-circuit easy cases 3107 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3108 // If constant is one, the result is trivial 3109 if (RHSC->getValue()->isOne()) 3110 return getZero(LHS->getType()); // X urem 1 --> 0 3111 3112 // If constant is a power of two, fold into a zext(trunc(LHS)). 3113 if (RHSC->getAPInt().isPowerOf2()) { 3114 Type *FullTy = LHS->getType(); 3115 Type *TruncTy = 3116 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3117 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3118 } 3119 } 3120 3121 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3122 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3123 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3124 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3125 } 3126 3127 /// Get a canonical unsigned division expression, or something simpler if 3128 /// possible. 3129 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3130 const SCEV *RHS) { 3131 assert(getEffectiveSCEVType(LHS->getType()) == 3132 getEffectiveSCEVType(RHS->getType()) && 3133 "SCEVUDivExpr operand types don't match!"); 3134 3135 FoldingSetNodeID ID; 3136 ID.AddInteger(scUDivExpr); 3137 ID.AddPointer(LHS); 3138 ID.AddPointer(RHS); 3139 void *IP = nullptr; 3140 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3141 return S; 3142 3143 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3144 if (RHSC->getValue()->isOne()) 3145 return LHS; // X udiv 1 --> x 3146 // If the denominator is zero, the result of the udiv is undefined. Don't 3147 // try to analyze it, because the resolution chosen here may differ from 3148 // the resolution chosen in other parts of the compiler. 3149 if (!RHSC->getValue()->isZero()) { 3150 // Determine if the division can be folded into the operands of 3151 // its operands. 3152 // TODO: Generalize this to non-constants by using known-bits information. 3153 Type *Ty = LHS->getType(); 3154 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3155 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3156 // For non-power-of-two values, effectively round the value up to the 3157 // nearest power of two. 3158 if (!RHSC->getAPInt().isPowerOf2()) 3159 ++MaxShiftAmt; 3160 IntegerType *ExtTy = 3161 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3162 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3163 if (const SCEVConstant *Step = 3164 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3165 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3166 const APInt &StepInt = Step->getAPInt(); 3167 const APInt &DivInt = RHSC->getAPInt(); 3168 if (!StepInt.urem(DivInt) && 3169 getZeroExtendExpr(AR, ExtTy) == 3170 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3171 getZeroExtendExpr(Step, ExtTy), 3172 AR->getLoop(), SCEV::FlagAnyWrap)) { 3173 SmallVector<const SCEV *, 4> Operands; 3174 for (const SCEV *Op : AR->operands()) 3175 Operands.push_back(getUDivExpr(Op, RHS)); 3176 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3177 } 3178 /// Get a canonical UDivExpr for a recurrence. 3179 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3180 // We can currently only fold X%N if X is constant. 3181 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3182 if (StartC && !DivInt.urem(StepInt) && 3183 getZeroExtendExpr(AR, ExtTy) == 3184 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3185 getZeroExtendExpr(Step, ExtTy), 3186 AR->getLoop(), SCEV::FlagAnyWrap)) { 3187 const APInt &StartInt = StartC->getAPInt(); 3188 const APInt &StartRem = StartInt.urem(StepInt); 3189 if (StartRem != 0) { 3190 const SCEV *NewLHS = 3191 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3192 AR->getLoop(), SCEV::FlagNW); 3193 if (LHS != NewLHS) { 3194 LHS = NewLHS; 3195 3196 // Reset the ID to include the new LHS, and check if it is 3197 // already cached. 3198 ID.clear(); 3199 ID.AddInteger(scUDivExpr); 3200 ID.AddPointer(LHS); 3201 ID.AddPointer(RHS); 3202 IP = nullptr; 3203 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3204 return S; 3205 } 3206 } 3207 } 3208 } 3209 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3210 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3211 SmallVector<const SCEV *, 4> Operands; 3212 for (const SCEV *Op : M->operands()) 3213 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3214 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3215 // Find an operand that's safely divisible. 3216 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3217 const SCEV *Op = M->getOperand(i); 3218 const SCEV *Div = getUDivExpr(Op, RHSC); 3219 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3220 Operands = SmallVector<const SCEV *, 4>(M->operands()); 3221 Operands[i] = Div; 3222 return getMulExpr(Operands); 3223 } 3224 } 3225 } 3226 3227 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3228 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3229 if (auto *DivisorConstant = 3230 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3231 bool Overflow = false; 3232 APInt NewRHS = 3233 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3234 if (Overflow) { 3235 return getConstant(RHSC->getType(), 0, false); 3236 } 3237 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3238 } 3239 } 3240 3241 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3242 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3243 SmallVector<const SCEV *, 4> Operands; 3244 for (const SCEV *Op : A->operands()) 3245 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3246 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3247 Operands.clear(); 3248 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3249 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3250 if (isa<SCEVUDivExpr>(Op) || 3251 getMulExpr(Op, RHS) != A->getOperand(i)) 3252 break; 3253 Operands.push_back(Op); 3254 } 3255 if (Operands.size() == A->getNumOperands()) 3256 return getAddExpr(Operands); 3257 } 3258 } 3259 3260 // Fold if both operands are constant. 3261 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3262 Constant *LHSCV = LHSC->getValue(); 3263 Constant *RHSCV = RHSC->getValue(); 3264 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3265 RHSCV))); 3266 } 3267 } 3268 } 3269 3270 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3271 // changes). Make sure we get a new one. 3272 IP = nullptr; 3273 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3274 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3275 LHS, RHS); 3276 UniqueSCEVs.InsertNode(S, IP); 3277 addToLoopUseLists(S); 3278 return S; 3279 } 3280 3281 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3282 APInt A = C1->getAPInt().abs(); 3283 APInt B = C2->getAPInt().abs(); 3284 uint32_t ABW = A.getBitWidth(); 3285 uint32_t BBW = B.getBitWidth(); 3286 3287 if (ABW > BBW) 3288 B = B.zext(ABW); 3289 else if (ABW < BBW) 3290 A = A.zext(BBW); 3291 3292 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3293 } 3294 3295 /// Get a canonical unsigned division expression, or something simpler if 3296 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3297 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3298 /// it's not exact because the udiv may be clearing bits. 3299 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3300 const SCEV *RHS) { 3301 // TODO: we could try to find factors in all sorts of things, but for now we 3302 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3303 // end of this file for inspiration. 3304 3305 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3306 if (!Mul || !Mul->hasNoUnsignedWrap()) 3307 return getUDivExpr(LHS, RHS); 3308 3309 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3310 // If the mulexpr multiplies by a constant, then that constant must be the 3311 // first element of the mulexpr. 3312 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3313 if (LHSCst == RHSCst) { 3314 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands())); 3315 return getMulExpr(Operands); 3316 } 3317 3318 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3319 // that there's a factor provided by one of the other terms. We need to 3320 // check. 3321 APInt Factor = gcd(LHSCst, RHSCst); 3322 if (!Factor.isIntN(1)) { 3323 LHSCst = 3324 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3325 RHSCst = 3326 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3327 SmallVector<const SCEV *, 2> Operands; 3328 Operands.push_back(LHSCst); 3329 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3330 LHS = getMulExpr(Operands); 3331 RHS = RHSCst; 3332 Mul = dyn_cast<SCEVMulExpr>(LHS); 3333 if (!Mul) 3334 return getUDivExactExpr(LHS, RHS); 3335 } 3336 } 3337 } 3338 3339 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3340 if (Mul->getOperand(i) == RHS) { 3341 SmallVector<const SCEV *, 2> Operands; 3342 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3343 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3344 return getMulExpr(Operands); 3345 } 3346 } 3347 3348 return getUDivExpr(LHS, RHS); 3349 } 3350 3351 /// Get an add recurrence expression for the specified loop. Simplify the 3352 /// expression as much as possible. 3353 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3354 const Loop *L, 3355 SCEV::NoWrapFlags Flags) { 3356 SmallVector<const SCEV *, 4> Operands; 3357 Operands.push_back(Start); 3358 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3359 if (StepChrec->getLoop() == L) { 3360 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3361 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3362 } 3363 3364 Operands.push_back(Step); 3365 return getAddRecExpr(Operands, L, Flags); 3366 } 3367 3368 /// Get an add recurrence expression for the specified loop. Simplify the 3369 /// expression as much as possible. 3370 const SCEV * 3371 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3372 const Loop *L, SCEV::NoWrapFlags Flags) { 3373 if (Operands.size() == 1) return Operands[0]; 3374 #ifndef NDEBUG 3375 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3376 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3377 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3378 "SCEVAddRecExpr operand types don't match!"); 3379 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3380 assert(isLoopInvariant(Operands[i], L) && 3381 "SCEVAddRecExpr operand is not loop-invariant!"); 3382 #endif 3383 3384 if (Operands.back()->isZero()) { 3385 Operands.pop_back(); 3386 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3387 } 3388 3389 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3390 // use that information to infer NUW and NSW flags. However, computing a 3391 // BE count requires calling getAddRecExpr, so we may not yet have a 3392 // meaningful BE count at this point (and if we don't, we'd be stuck 3393 // with a SCEVCouldNotCompute as the cached BE count). 3394 3395 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3396 3397 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3398 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3399 const Loop *NestedLoop = NestedAR->getLoop(); 3400 if (L->contains(NestedLoop) 3401 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3402 : (!NestedLoop->contains(L) && 3403 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3404 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands()); 3405 Operands[0] = NestedAR->getStart(); 3406 // AddRecs require their operands be loop-invariant with respect to their 3407 // loops. Don't perform this transformation if it would break this 3408 // requirement. 3409 bool AllInvariant = all_of( 3410 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3411 3412 if (AllInvariant) { 3413 // Create a recurrence for the outer loop with the same step size. 3414 // 3415 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3416 // inner recurrence has the same property. 3417 SCEV::NoWrapFlags OuterFlags = 3418 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3419 3420 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3421 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3422 return isLoopInvariant(Op, NestedLoop); 3423 }); 3424 3425 if (AllInvariant) { 3426 // Ok, both add recurrences are valid after the transformation. 3427 // 3428 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3429 // the outer recurrence has the same property. 3430 SCEV::NoWrapFlags InnerFlags = 3431 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3432 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3433 } 3434 } 3435 // Reset Operands to its original state. 3436 Operands[0] = NestedAR; 3437 } 3438 } 3439 3440 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3441 // already have one, otherwise create a new one. 3442 return getOrCreateAddRecExpr(Operands, L, Flags); 3443 } 3444 3445 const SCEV * 3446 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3447 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3448 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3449 // getSCEV(Base)->getType() has the same address space as Base->getType() 3450 // because SCEV::getType() preserves the address space. 3451 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3452 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3453 // instruction to its SCEV, because the Instruction may be guarded by control 3454 // flow and the no-overflow bits may not be valid for the expression in any 3455 // context. This can be fixed similarly to how these flags are handled for 3456 // adds. 3457 SCEV::NoWrapFlags OffsetWrap = 3458 GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3459 3460 Type *CurTy = GEP->getType(); 3461 bool FirstIter = true; 3462 SmallVector<const SCEV *, 4> Offsets; 3463 for (const SCEV *IndexExpr : IndexExprs) { 3464 // Compute the (potentially symbolic) offset in bytes for this index. 3465 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3466 // For a struct, add the member offset. 3467 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3468 unsigned FieldNo = Index->getZExtValue(); 3469 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3470 Offsets.push_back(FieldOffset); 3471 3472 // Update CurTy to the type of the field at Index. 3473 CurTy = STy->getTypeAtIndex(Index); 3474 } else { 3475 // Update CurTy to its element type. 3476 if (FirstIter) { 3477 assert(isa<PointerType>(CurTy) && 3478 "The first index of a GEP indexes a pointer"); 3479 CurTy = GEP->getSourceElementType(); 3480 FirstIter = false; 3481 } else { 3482 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3483 } 3484 // For an array, add the element offset, explicitly scaled. 3485 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3486 // Getelementptr indices are signed. 3487 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3488 3489 // Multiply the index by the element size to compute the element offset. 3490 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3491 Offsets.push_back(LocalOffset); 3492 } 3493 } 3494 3495 // Handle degenerate case of GEP without offsets. 3496 if (Offsets.empty()) 3497 return BaseExpr; 3498 3499 // Add the offsets together, assuming nsw if inbounds. 3500 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3501 // Add the base address and the offset. We cannot use the nsw flag, as the 3502 // base address is unsigned. However, if we know that the offset is 3503 // non-negative, we can use nuw. 3504 SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset) 3505 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3506 return getAddExpr(BaseExpr, Offset, BaseWrap); 3507 } 3508 3509 std::tuple<SCEV *, FoldingSetNodeID, void *> 3510 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3511 ArrayRef<const SCEV *> Ops) { 3512 FoldingSetNodeID ID; 3513 void *IP = nullptr; 3514 ID.AddInteger(SCEVType); 3515 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3516 ID.AddPointer(Ops[i]); 3517 return std::tuple<SCEV *, FoldingSetNodeID, void *>( 3518 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3519 } 3520 3521 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3522 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3523 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3524 } 3525 3526 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3527 SmallVectorImpl<const SCEV *> &Ops) { 3528 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3529 if (Ops.size() == 1) return Ops[0]; 3530 #ifndef NDEBUG 3531 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3532 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3533 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3534 "Operand types don't match!"); 3535 #endif 3536 3537 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3538 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3539 3540 // Sort by complexity, this groups all similar expression types together. 3541 GroupByComplexity(Ops, &LI, DT); 3542 3543 // Check if we have created the same expression before. 3544 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3545 return S; 3546 } 3547 3548 // If there are any constants, fold them together. 3549 unsigned Idx = 0; 3550 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3551 ++Idx; 3552 assert(Idx < Ops.size()); 3553 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3554 if (Kind == scSMaxExpr) 3555 return APIntOps::smax(LHS, RHS); 3556 else if (Kind == scSMinExpr) 3557 return APIntOps::smin(LHS, RHS); 3558 else if (Kind == scUMaxExpr) 3559 return APIntOps::umax(LHS, RHS); 3560 else if (Kind == scUMinExpr) 3561 return APIntOps::umin(LHS, RHS); 3562 llvm_unreachable("Unknown SCEV min/max opcode"); 3563 }; 3564 3565 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3566 // We found two constants, fold them together! 3567 ConstantInt *Fold = ConstantInt::get( 3568 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3569 Ops[0] = getConstant(Fold); 3570 Ops.erase(Ops.begin()+1); // Erase the folded element 3571 if (Ops.size() == 1) return Ops[0]; 3572 LHSC = cast<SCEVConstant>(Ops[0]); 3573 } 3574 3575 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3576 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3577 3578 if (IsMax ? IsMinV : IsMaxV) { 3579 // If we are left with a constant minimum(/maximum)-int, strip it off. 3580 Ops.erase(Ops.begin()); 3581 --Idx; 3582 } else if (IsMax ? IsMaxV : IsMinV) { 3583 // If we have a max(/min) with a constant maximum(/minimum)-int, 3584 // it will always be the extremum. 3585 return LHSC; 3586 } 3587 3588 if (Ops.size() == 1) return Ops[0]; 3589 } 3590 3591 // Find the first operation of the same kind 3592 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3593 ++Idx; 3594 3595 // Check to see if one of the operands is of the same kind. If so, expand its 3596 // operands onto our operand list, and recurse to simplify. 3597 if (Idx < Ops.size()) { 3598 bool DeletedAny = false; 3599 while (Ops[Idx]->getSCEVType() == Kind) { 3600 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3601 Ops.erase(Ops.begin()+Idx); 3602 Ops.append(SMME->op_begin(), SMME->op_end()); 3603 DeletedAny = true; 3604 } 3605 3606 if (DeletedAny) 3607 return getMinMaxExpr(Kind, Ops); 3608 } 3609 3610 // Okay, check to see if the same value occurs in the operand list twice. If 3611 // so, delete one. Since we sorted the list, these values are required to 3612 // be adjacent. 3613 llvm::CmpInst::Predicate GEPred = 3614 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3615 llvm::CmpInst::Predicate LEPred = 3616 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3617 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3618 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3619 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3620 if (Ops[i] == Ops[i + 1] || 3621 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3622 // X op Y op Y --> X op Y 3623 // X op Y --> X, if we know X, Y are ordered appropriately 3624 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3625 --i; 3626 --e; 3627 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3628 Ops[i + 1])) { 3629 // X op Y --> Y, if we know X, Y are ordered appropriately 3630 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3631 --i; 3632 --e; 3633 } 3634 } 3635 3636 if (Ops.size() == 1) return Ops[0]; 3637 3638 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3639 3640 // Okay, it looks like we really DO need an expr. Check to see if we 3641 // already have one, otherwise create a new one. 3642 const SCEV *ExistingSCEV; 3643 FoldingSetNodeID ID; 3644 void *IP; 3645 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3646 if (ExistingSCEV) 3647 return ExistingSCEV; 3648 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3649 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3650 SCEV *S = new (SCEVAllocator) 3651 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3652 3653 UniqueSCEVs.InsertNode(S, IP); 3654 addToLoopUseLists(S); 3655 return S; 3656 } 3657 3658 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3659 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3660 return getSMaxExpr(Ops); 3661 } 3662 3663 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3664 return getMinMaxExpr(scSMaxExpr, Ops); 3665 } 3666 3667 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3668 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3669 return getUMaxExpr(Ops); 3670 } 3671 3672 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3673 return getMinMaxExpr(scUMaxExpr, Ops); 3674 } 3675 3676 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3677 const SCEV *RHS) { 3678 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3679 return getSMinExpr(Ops); 3680 } 3681 3682 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3683 return getMinMaxExpr(scSMinExpr, Ops); 3684 } 3685 3686 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3687 const SCEV *RHS) { 3688 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3689 return getUMinExpr(Ops); 3690 } 3691 3692 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3693 return getMinMaxExpr(scUMinExpr, Ops); 3694 } 3695 3696 const SCEV * 3697 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 3698 ScalableVectorType *ScalableTy) { 3699 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 3700 Constant *One = ConstantInt::get(IntTy, 1); 3701 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 3702 // Note that the expression we created is the final expression, we don't 3703 // want to simplify it any further Also, if we call a normal getSCEV(), 3704 // we'll end up in an endless recursion. So just create an SCEVUnknown. 3705 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 3706 } 3707 3708 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3709 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 3710 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 3711 // We can bypass creating a target-independent constant expression and then 3712 // folding it back into a ConstantInt. This is just a compile-time 3713 // optimization. 3714 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3715 } 3716 3717 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 3718 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 3719 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 3720 // We can bypass creating a target-independent constant expression and then 3721 // folding it back into a ConstantInt. This is just a compile-time 3722 // optimization. 3723 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 3724 } 3725 3726 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3727 StructType *STy, 3728 unsigned FieldNo) { 3729 // We can bypass creating a target-independent constant expression and then 3730 // folding it back into a ConstantInt. This is just a compile-time 3731 // optimization. 3732 return getConstant( 3733 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3734 } 3735 3736 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3737 // Don't attempt to do anything other than create a SCEVUnknown object 3738 // here. createSCEV only calls getUnknown after checking for all other 3739 // interesting possibilities, and any other code that calls getUnknown 3740 // is doing so in order to hide a value from SCEV canonicalization. 3741 3742 FoldingSetNodeID ID; 3743 ID.AddInteger(scUnknown); 3744 ID.AddPointer(V); 3745 void *IP = nullptr; 3746 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3747 assert(cast<SCEVUnknown>(S)->getValue() == V && 3748 "Stale SCEVUnknown in uniquing map!"); 3749 return S; 3750 } 3751 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3752 FirstUnknown); 3753 FirstUnknown = cast<SCEVUnknown>(S); 3754 UniqueSCEVs.InsertNode(S, IP); 3755 return S; 3756 } 3757 3758 //===----------------------------------------------------------------------===// 3759 // Basic SCEV Analysis and PHI Idiom Recognition Code 3760 // 3761 3762 /// Test if values of the given type are analyzable within the SCEV 3763 /// framework. This primarily includes integer types, and it can optionally 3764 /// include pointer types if the ScalarEvolution class has access to 3765 /// target-specific information. 3766 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3767 // Integers and pointers are always SCEVable. 3768 return Ty->isIntOrPtrTy(); 3769 } 3770 3771 /// Return the size in bits of the specified type, for which isSCEVable must 3772 /// return true. 3773 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3774 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3775 if (Ty->isPointerTy()) 3776 return getDataLayout().getIndexTypeSizeInBits(Ty); 3777 return getDataLayout().getTypeSizeInBits(Ty); 3778 } 3779 3780 /// Return a type with the same bitwidth as the given type and which represents 3781 /// how SCEV will treat the given type, for which isSCEVable must return 3782 /// true. For pointer types, this is the pointer index sized integer type. 3783 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3784 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3785 3786 if (Ty->isIntegerTy()) 3787 return Ty; 3788 3789 // The only other support type is pointer. 3790 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3791 return getDataLayout().getIndexType(Ty); 3792 } 3793 3794 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3795 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3796 } 3797 3798 const SCEV *ScalarEvolution::getCouldNotCompute() { 3799 return CouldNotCompute.get(); 3800 } 3801 3802 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3803 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3804 auto *SU = dyn_cast<SCEVUnknown>(S); 3805 return SU && SU->getValue() == nullptr; 3806 }); 3807 3808 return !ContainsNulls; 3809 } 3810 3811 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3812 HasRecMapType::iterator I = HasRecMap.find(S); 3813 if (I != HasRecMap.end()) 3814 return I->second; 3815 3816 bool FoundAddRec = 3817 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3818 HasRecMap.insert({S, FoundAddRec}); 3819 return FoundAddRec; 3820 } 3821 3822 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3823 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3824 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3825 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3826 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3827 if (!Add) 3828 return {S, nullptr}; 3829 3830 if (Add->getNumOperands() != 2) 3831 return {S, nullptr}; 3832 3833 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3834 if (!ConstOp) 3835 return {S, nullptr}; 3836 3837 return {Add->getOperand(1), ConstOp->getValue()}; 3838 } 3839 3840 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3841 /// by the value and offset from any ValueOffsetPair in the set. 3842 ScalarEvolution::ValueOffsetPairSetVector * 3843 ScalarEvolution::getSCEVValues(const SCEV *S) { 3844 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3845 if (SI == ExprValueMap.end()) 3846 return nullptr; 3847 #ifndef NDEBUG 3848 if (VerifySCEVMap) { 3849 // Check there is no dangling Value in the set returned. 3850 for (const auto &VE : SI->second) 3851 assert(ValueExprMap.count(VE.first)); 3852 } 3853 #endif 3854 return &SI->second; 3855 } 3856 3857 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3858 /// cannot be used separately. eraseValueFromMap should be used to remove 3859 /// V from ValueExprMap and ExprValueMap at the same time. 3860 void ScalarEvolution::eraseValueFromMap(Value *V) { 3861 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3862 if (I != ValueExprMap.end()) { 3863 const SCEV *S = I->second; 3864 // Remove {V, 0} from the set of ExprValueMap[S] 3865 if (auto *SV = getSCEVValues(S)) 3866 SV->remove({V, nullptr}); 3867 3868 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3869 const SCEV *Stripped; 3870 ConstantInt *Offset; 3871 std::tie(Stripped, Offset) = splitAddExpr(S); 3872 if (Offset != nullptr) { 3873 if (auto *SV = getSCEVValues(Stripped)) 3874 SV->remove({V, Offset}); 3875 } 3876 ValueExprMap.erase(V); 3877 } 3878 } 3879 3880 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3881 /// TODO: In reality it is better to check the poison recursively 3882 /// but this is better than nothing. 3883 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3884 if (auto *I = dyn_cast<Instruction>(V)) { 3885 if (isa<OverflowingBinaryOperator>(I)) { 3886 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3887 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3888 return true; 3889 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3890 return true; 3891 } 3892 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3893 return true; 3894 } 3895 return false; 3896 } 3897 3898 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3899 /// create a new one. 3900 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3901 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3902 3903 const SCEV *S = getExistingSCEV(V); 3904 if (S == nullptr) { 3905 S = createSCEV(V); 3906 // During PHI resolution, it is possible to create two SCEVs for the same 3907 // V, so it is needed to double check whether V->S is inserted into 3908 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3909 std::pair<ValueExprMapType::iterator, bool> Pair = 3910 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3911 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3912 ExprValueMap[S].insert({V, nullptr}); 3913 3914 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3915 // ExprValueMap. 3916 const SCEV *Stripped = S; 3917 ConstantInt *Offset = nullptr; 3918 std::tie(Stripped, Offset) = splitAddExpr(S); 3919 // If stripped is SCEVUnknown, don't bother to save 3920 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3921 // increase the complexity of the expansion code. 3922 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3923 // because it may generate add/sub instead of GEP in SCEV expansion. 3924 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3925 !isa<GetElementPtrInst>(V)) 3926 ExprValueMap[Stripped].insert({V, Offset}); 3927 } 3928 } 3929 return S; 3930 } 3931 3932 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3933 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3934 3935 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3936 if (I != ValueExprMap.end()) { 3937 const SCEV *S = I->second; 3938 if (checkValidity(S)) 3939 return S; 3940 eraseValueFromMap(V); 3941 forgetMemoizedResults(S); 3942 } 3943 return nullptr; 3944 } 3945 3946 /// Return a SCEV corresponding to -V = -1*V 3947 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3948 SCEV::NoWrapFlags Flags) { 3949 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3950 return getConstant( 3951 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3952 3953 Type *Ty = V->getType(); 3954 Ty = getEffectiveSCEVType(Ty); 3955 return getMulExpr(V, getMinusOne(Ty), Flags); 3956 } 3957 3958 /// If Expr computes ~A, return A else return nullptr 3959 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3960 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3961 if (!Add || Add->getNumOperands() != 2 || 3962 !Add->getOperand(0)->isAllOnesValue()) 3963 return nullptr; 3964 3965 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3966 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3967 !AddRHS->getOperand(0)->isAllOnesValue()) 3968 return nullptr; 3969 3970 return AddRHS->getOperand(1); 3971 } 3972 3973 /// Return a SCEV corresponding to ~V = -1-V 3974 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3975 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3976 return getConstant( 3977 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3978 3979 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 3980 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 3981 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 3982 SmallVector<const SCEV *, 2> MatchedOperands; 3983 for (const SCEV *Operand : MME->operands()) { 3984 const SCEV *Matched = MatchNotExpr(Operand); 3985 if (!Matched) 3986 return (const SCEV *)nullptr; 3987 MatchedOperands.push_back(Matched); 3988 } 3989 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 3990 MatchedOperands); 3991 }; 3992 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 3993 return Replaced; 3994 } 3995 3996 Type *Ty = V->getType(); 3997 Ty = getEffectiveSCEVType(Ty); 3998 return getMinusSCEV(getMinusOne(Ty), V); 3999 } 4000 4001 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4002 SCEV::NoWrapFlags Flags, 4003 unsigned Depth) { 4004 // Fast path: X - X --> 0. 4005 if (LHS == RHS) 4006 return getZero(LHS->getType()); 4007 4008 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4009 // makes it so that we cannot make much use of NUW. 4010 auto AddFlags = SCEV::FlagAnyWrap; 4011 const bool RHSIsNotMinSigned = 4012 !getSignedRangeMin(RHS).isMinSignedValue(); 4013 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4014 // Let M be the minimum representable signed value. Then (-1)*RHS 4015 // signed-wraps if and only if RHS is M. That can happen even for 4016 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4017 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4018 // (-1)*RHS, we need to prove that RHS != M. 4019 // 4020 // If LHS is non-negative and we know that LHS - RHS does not 4021 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4022 // either by proving that RHS > M or that LHS >= 0. 4023 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4024 AddFlags = SCEV::FlagNSW; 4025 } 4026 } 4027 4028 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4029 // RHS is NSW and LHS >= 0. 4030 // 4031 // The difficulty here is that the NSW flag may have been proven 4032 // relative to a loop that is to be found in a recurrence in LHS and 4033 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4034 // larger scope than intended. 4035 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4036 4037 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4038 } 4039 4040 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4041 unsigned Depth) { 4042 Type *SrcTy = V->getType(); 4043 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4044 "Cannot truncate or zero extend with non-integer arguments!"); 4045 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4046 return V; // No conversion 4047 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4048 return getTruncateExpr(V, Ty, Depth); 4049 return getZeroExtendExpr(V, Ty, Depth); 4050 } 4051 4052 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4053 unsigned Depth) { 4054 Type *SrcTy = V->getType(); 4055 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4056 "Cannot truncate or zero extend with non-integer arguments!"); 4057 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4058 return V; // No conversion 4059 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4060 return getTruncateExpr(V, Ty, Depth); 4061 return getSignExtendExpr(V, Ty, Depth); 4062 } 4063 4064 const SCEV * 4065 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4066 Type *SrcTy = V->getType(); 4067 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4068 "Cannot noop or zero extend with non-integer arguments!"); 4069 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4070 "getNoopOrZeroExtend cannot truncate!"); 4071 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4072 return V; // No conversion 4073 return getZeroExtendExpr(V, Ty); 4074 } 4075 4076 const SCEV * 4077 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4078 Type *SrcTy = V->getType(); 4079 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4080 "Cannot noop or sign extend with non-integer arguments!"); 4081 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4082 "getNoopOrSignExtend cannot truncate!"); 4083 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4084 return V; // No conversion 4085 return getSignExtendExpr(V, Ty); 4086 } 4087 4088 const SCEV * 4089 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4090 Type *SrcTy = V->getType(); 4091 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4092 "Cannot noop or any extend with non-integer arguments!"); 4093 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4094 "getNoopOrAnyExtend cannot truncate!"); 4095 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4096 return V; // No conversion 4097 return getAnyExtendExpr(V, Ty); 4098 } 4099 4100 const SCEV * 4101 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4102 Type *SrcTy = V->getType(); 4103 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4104 "Cannot truncate or noop with non-integer arguments!"); 4105 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4106 "getTruncateOrNoop cannot extend!"); 4107 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4108 return V; // No conversion 4109 return getTruncateExpr(V, Ty); 4110 } 4111 4112 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4113 const SCEV *RHS) { 4114 const SCEV *PromotedLHS = LHS; 4115 const SCEV *PromotedRHS = RHS; 4116 4117 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4118 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4119 else 4120 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4121 4122 return getUMaxExpr(PromotedLHS, PromotedRHS); 4123 } 4124 4125 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4126 const SCEV *RHS) { 4127 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4128 return getUMinFromMismatchedTypes(Ops); 4129 } 4130 4131 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4132 SmallVectorImpl<const SCEV *> &Ops) { 4133 assert(!Ops.empty() && "At least one operand must be!"); 4134 // Trivial case. 4135 if (Ops.size() == 1) 4136 return Ops[0]; 4137 4138 // Find the max type first. 4139 Type *MaxType = nullptr; 4140 for (auto *S : Ops) 4141 if (MaxType) 4142 MaxType = getWiderType(MaxType, S->getType()); 4143 else 4144 MaxType = S->getType(); 4145 assert(MaxType && "Failed to find maximum type!"); 4146 4147 // Extend all ops to max type. 4148 SmallVector<const SCEV *, 2> PromotedOps; 4149 for (auto *S : Ops) 4150 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4151 4152 // Generate umin. 4153 return getUMinExpr(PromotedOps); 4154 } 4155 4156 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4157 // A pointer operand may evaluate to a nonpointer expression, such as null. 4158 if (!V->getType()->isPointerTy()) 4159 return V; 4160 4161 while (true) { 4162 if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) { 4163 V = Cast->getOperand(); 4164 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4165 const SCEV *PtrOp = nullptr; 4166 for (const SCEV *NAryOp : NAry->operands()) { 4167 if (NAryOp->getType()->isPointerTy()) { 4168 // Cannot find the base of an expression with multiple pointer ops. 4169 if (PtrOp) 4170 return V; 4171 PtrOp = NAryOp; 4172 } 4173 } 4174 if (!PtrOp) // All operands were non-pointer. 4175 return V; 4176 V = PtrOp; 4177 } else // Not something we can look further into. 4178 return V; 4179 } 4180 } 4181 4182 /// Push users of the given Instruction onto the given Worklist. 4183 static void 4184 PushDefUseChildren(Instruction *I, 4185 SmallVectorImpl<Instruction *> &Worklist) { 4186 // Push the def-use children onto the Worklist stack. 4187 for (User *U : I->users()) 4188 Worklist.push_back(cast<Instruction>(U)); 4189 } 4190 4191 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4192 SmallVector<Instruction *, 16> Worklist; 4193 PushDefUseChildren(PN, Worklist); 4194 4195 SmallPtrSet<Instruction *, 8> Visited; 4196 Visited.insert(PN); 4197 while (!Worklist.empty()) { 4198 Instruction *I = Worklist.pop_back_val(); 4199 if (!Visited.insert(I).second) 4200 continue; 4201 4202 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4203 if (It != ValueExprMap.end()) { 4204 const SCEV *Old = It->second; 4205 4206 // Short-circuit the def-use traversal if the symbolic name 4207 // ceases to appear in expressions. 4208 if (Old != SymName && !hasOperand(Old, SymName)) 4209 continue; 4210 4211 // SCEVUnknown for a PHI either means that it has an unrecognized 4212 // structure, it's a PHI that's in the progress of being computed 4213 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4214 // additional loop trip count information isn't going to change anything. 4215 // In the second case, createNodeForPHI will perform the necessary 4216 // updates on its own when it gets to that point. In the third, we do 4217 // want to forget the SCEVUnknown. 4218 if (!isa<PHINode>(I) || 4219 !isa<SCEVUnknown>(Old) || 4220 (I != PN && Old == SymName)) { 4221 eraseValueFromMap(It->first); 4222 forgetMemoizedResults(Old); 4223 } 4224 } 4225 4226 PushDefUseChildren(I, Worklist); 4227 } 4228 } 4229 4230 namespace { 4231 4232 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4233 /// expression in case its Loop is L. If it is not L then 4234 /// if IgnoreOtherLoops is true then use AddRec itself 4235 /// otherwise rewrite cannot be done. 4236 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4237 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4238 public: 4239 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4240 bool IgnoreOtherLoops = true) { 4241 SCEVInitRewriter Rewriter(L, SE); 4242 const SCEV *Result = Rewriter.visit(S); 4243 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4244 return SE.getCouldNotCompute(); 4245 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4246 ? SE.getCouldNotCompute() 4247 : Result; 4248 } 4249 4250 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4251 if (!SE.isLoopInvariant(Expr, L)) 4252 SeenLoopVariantSCEVUnknown = true; 4253 return Expr; 4254 } 4255 4256 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4257 // Only re-write AddRecExprs for this loop. 4258 if (Expr->getLoop() == L) 4259 return Expr->getStart(); 4260 SeenOtherLoops = true; 4261 return Expr; 4262 } 4263 4264 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4265 4266 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4267 4268 private: 4269 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4270 : SCEVRewriteVisitor(SE), L(L) {} 4271 4272 const Loop *L; 4273 bool SeenLoopVariantSCEVUnknown = false; 4274 bool SeenOtherLoops = false; 4275 }; 4276 4277 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4278 /// increment expression in case its Loop is L. If it is not L then 4279 /// use AddRec itself. 4280 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4281 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4282 public: 4283 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4284 SCEVPostIncRewriter Rewriter(L, SE); 4285 const SCEV *Result = Rewriter.visit(S); 4286 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4287 ? SE.getCouldNotCompute() 4288 : Result; 4289 } 4290 4291 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4292 if (!SE.isLoopInvariant(Expr, L)) 4293 SeenLoopVariantSCEVUnknown = true; 4294 return Expr; 4295 } 4296 4297 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4298 // Only re-write AddRecExprs for this loop. 4299 if (Expr->getLoop() == L) 4300 return Expr->getPostIncExpr(SE); 4301 SeenOtherLoops = true; 4302 return Expr; 4303 } 4304 4305 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4306 4307 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4308 4309 private: 4310 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4311 : SCEVRewriteVisitor(SE), L(L) {} 4312 4313 const Loop *L; 4314 bool SeenLoopVariantSCEVUnknown = false; 4315 bool SeenOtherLoops = false; 4316 }; 4317 4318 /// This class evaluates the compare condition by matching it against the 4319 /// condition of loop latch. If there is a match we assume a true value 4320 /// for the condition while building SCEV nodes. 4321 class SCEVBackedgeConditionFolder 4322 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4323 public: 4324 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4325 ScalarEvolution &SE) { 4326 bool IsPosBECond = false; 4327 Value *BECond = nullptr; 4328 if (BasicBlock *Latch = L->getLoopLatch()) { 4329 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4330 if (BI && BI->isConditional()) { 4331 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4332 "Both outgoing branches should not target same header!"); 4333 BECond = BI->getCondition(); 4334 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4335 } else { 4336 return S; 4337 } 4338 } 4339 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4340 return Rewriter.visit(S); 4341 } 4342 4343 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4344 const SCEV *Result = Expr; 4345 bool InvariantF = SE.isLoopInvariant(Expr, L); 4346 4347 if (!InvariantF) { 4348 Instruction *I = cast<Instruction>(Expr->getValue()); 4349 switch (I->getOpcode()) { 4350 case Instruction::Select: { 4351 SelectInst *SI = cast<SelectInst>(I); 4352 Optional<const SCEV *> Res = 4353 compareWithBackedgeCondition(SI->getCondition()); 4354 if (Res.hasValue()) { 4355 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4356 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4357 } 4358 break; 4359 } 4360 default: { 4361 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4362 if (Res.hasValue()) 4363 Result = Res.getValue(); 4364 break; 4365 } 4366 } 4367 } 4368 return Result; 4369 } 4370 4371 private: 4372 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4373 bool IsPosBECond, ScalarEvolution &SE) 4374 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4375 IsPositiveBECond(IsPosBECond) {} 4376 4377 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4378 4379 const Loop *L; 4380 /// Loop back condition. 4381 Value *BackedgeCond = nullptr; 4382 /// Set to true if loop back is on positive branch condition. 4383 bool IsPositiveBECond; 4384 }; 4385 4386 Optional<const SCEV *> 4387 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4388 4389 // If value matches the backedge condition for loop latch, 4390 // then return a constant evolution node based on loopback 4391 // branch taken. 4392 if (BackedgeCond == IC) 4393 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4394 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4395 return None; 4396 } 4397 4398 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4399 public: 4400 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4401 ScalarEvolution &SE) { 4402 SCEVShiftRewriter Rewriter(L, SE); 4403 const SCEV *Result = Rewriter.visit(S); 4404 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4405 } 4406 4407 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4408 // Only allow AddRecExprs for this loop. 4409 if (!SE.isLoopInvariant(Expr, L)) 4410 Valid = false; 4411 return Expr; 4412 } 4413 4414 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4415 if (Expr->getLoop() == L && Expr->isAffine()) 4416 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4417 Valid = false; 4418 return Expr; 4419 } 4420 4421 bool isValid() { return Valid; } 4422 4423 private: 4424 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4425 : SCEVRewriteVisitor(SE), L(L) {} 4426 4427 const Loop *L; 4428 bool Valid = true; 4429 }; 4430 4431 } // end anonymous namespace 4432 4433 SCEV::NoWrapFlags 4434 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4435 if (!AR->isAffine()) 4436 return SCEV::FlagAnyWrap; 4437 4438 using OBO = OverflowingBinaryOperator; 4439 4440 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4441 4442 if (!AR->hasNoSignedWrap()) { 4443 ConstantRange AddRecRange = getSignedRange(AR); 4444 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4445 4446 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4447 Instruction::Add, IncRange, OBO::NoSignedWrap); 4448 if (NSWRegion.contains(AddRecRange)) 4449 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4450 } 4451 4452 if (!AR->hasNoUnsignedWrap()) { 4453 ConstantRange AddRecRange = getUnsignedRange(AR); 4454 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4455 4456 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4457 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4458 if (NUWRegion.contains(AddRecRange)) 4459 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4460 } 4461 4462 return Result; 4463 } 4464 4465 SCEV::NoWrapFlags 4466 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4467 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4468 4469 if (AR->hasNoSignedWrap()) 4470 return Result; 4471 4472 if (!AR->isAffine()) 4473 return Result; 4474 4475 const SCEV *Step = AR->getStepRecurrence(*this); 4476 const Loop *L = AR->getLoop(); 4477 4478 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4479 // Note that this serves two purposes: It filters out loops that are 4480 // simply not analyzable, and it covers the case where this code is 4481 // being called from within backedge-taken count analysis, such that 4482 // attempting to ask for the backedge-taken count would likely result 4483 // in infinite recursion. In the later case, the analysis code will 4484 // cope with a conservative value, and it will take care to purge 4485 // that value once it has finished. 4486 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4487 4488 // Normally, in the cases we can prove no-overflow via a 4489 // backedge guarding condition, we can also compute a backedge 4490 // taken count for the loop. The exceptions are assumptions and 4491 // guards present in the loop -- SCEV is not great at exploiting 4492 // these to compute max backedge taken counts, but can still use 4493 // these to prove lack of overflow. Use this fact to avoid 4494 // doing extra work that may not pay off. 4495 4496 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4497 AC.assumptions().empty()) 4498 return Result; 4499 4500 // If the backedge is guarded by a comparison with the pre-inc value the 4501 // addrec is safe. Also, if the entry is guarded by a comparison with the 4502 // start value and the backedge is guarded by a comparison with the post-inc 4503 // value, the addrec is safe. 4504 ICmpInst::Predicate Pred; 4505 const SCEV *OverflowLimit = 4506 getSignedOverflowLimitForStep(Step, &Pred, this); 4507 if (OverflowLimit && 4508 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4509 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4510 Result = setFlags(Result, SCEV::FlagNSW); 4511 } 4512 return Result; 4513 } 4514 SCEV::NoWrapFlags 4515 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4516 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4517 4518 if (AR->hasNoUnsignedWrap()) 4519 return Result; 4520 4521 if (!AR->isAffine()) 4522 return Result; 4523 4524 const SCEV *Step = AR->getStepRecurrence(*this); 4525 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4526 const Loop *L = AR->getLoop(); 4527 4528 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4529 // Note that this serves two purposes: It filters out loops that are 4530 // simply not analyzable, and it covers the case where this code is 4531 // being called from within backedge-taken count analysis, such that 4532 // attempting to ask for the backedge-taken count would likely result 4533 // in infinite recursion. In the later case, the analysis code will 4534 // cope with a conservative value, and it will take care to purge 4535 // that value once it has finished. 4536 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4537 4538 // Normally, in the cases we can prove no-overflow via a 4539 // backedge guarding condition, we can also compute a backedge 4540 // taken count for the loop. The exceptions are assumptions and 4541 // guards present in the loop -- SCEV is not great at exploiting 4542 // these to compute max backedge taken counts, but can still use 4543 // these to prove lack of overflow. Use this fact to avoid 4544 // doing extra work that may not pay off. 4545 4546 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4547 AC.assumptions().empty()) 4548 return Result; 4549 4550 // If the backedge is guarded by a comparison with the pre-inc value the 4551 // addrec is safe. Also, if the entry is guarded by a comparison with the 4552 // start value and the backedge is guarded by a comparison with the post-inc 4553 // value, the addrec is safe. 4554 if (isKnownPositive(Step)) { 4555 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 4556 getUnsignedRangeMax(Step)); 4557 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 4558 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 4559 Result = setFlags(Result, SCEV::FlagNUW); 4560 } 4561 } 4562 4563 return Result; 4564 } 4565 4566 namespace { 4567 4568 /// Represents an abstract binary operation. This may exist as a 4569 /// normal instruction or constant expression, or may have been 4570 /// derived from an expression tree. 4571 struct BinaryOp { 4572 unsigned Opcode; 4573 Value *LHS; 4574 Value *RHS; 4575 bool IsNSW = false; 4576 bool IsNUW = false; 4577 4578 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4579 /// constant expression. 4580 Operator *Op = nullptr; 4581 4582 explicit BinaryOp(Operator *Op) 4583 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4584 Op(Op) { 4585 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4586 IsNSW = OBO->hasNoSignedWrap(); 4587 IsNUW = OBO->hasNoUnsignedWrap(); 4588 } 4589 } 4590 4591 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4592 bool IsNUW = false) 4593 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4594 }; 4595 4596 } // end anonymous namespace 4597 4598 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4599 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4600 auto *Op = dyn_cast<Operator>(V); 4601 if (!Op) 4602 return None; 4603 4604 // Implementation detail: all the cleverness here should happen without 4605 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4606 // SCEV expressions when possible, and we should not break that. 4607 4608 switch (Op->getOpcode()) { 4609 case Instruction::Add: 4610 case Instruction::Sub: 4611 case Instruction::Mul: 4612 case Instruction::UDiv: 4613 case Instruction::URem: 4614 case Instruction::And: 4615 case Instruction::Or: 4616 case Instruction::AShr: 4617 case Instruction::Shl: 4618 return BinaryOp(Op); 4619 4620 case Instruction::Xor: 4621 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4622 // If the RHS of the xor is a signmask, then this is just an add. 4623 // Instcombine turns add of signmask into xor as a strength reduction step. 4624 if (RHSC->getValue().isSignMask()) 4625 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4626 return BinaryOp(Op); 4627 4628 case Instruction::LShr: 4629 // Turn logical shift right of a constant into a unsigned divide. 4630 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4631 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4632 4633 // If the shift count is not less than the bitwidth, the result of 4634 // the shift is undefined. Don't try to analyze it, because the 4635 // resolution chosen here may differ from the resolution chosen in 4636 // other parts of the compiler. 4637 if (SA->getValue().ult(BitWidth)) { 4638 Constant *X = 4639 ConstantInt::get(SA->getContext(), 4640 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4641 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4642 } 4643 } 4644 return BinaryOp(Op); 4645 4646 case Instruction::ExtractValue: { 4647 auto *EVI = cast<ExtractValueInst>(Op); 4648 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4649 break; 4650 4651 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4652 if (!WO) 4653 break; 4654 4655 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4656 bool Signed = WO->isSigned(); 4657 // TODO: Should add nuw/nsw flags for mul as well. 4658 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4659 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4660 4661 // Now that we know that all uses of the arithmetic-result component of 4662 // CI are guarded by the overflow check, we can go ahead and pretend 4663 // that the arithmetic is non-overflowing. 4664 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4665 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4666 } 4667 4668 default: 4669 break; 4670 } 4671 4672 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4673 // semantics as a Sub, return a binary sub expression. 4674 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4675 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4676 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4677 4678 return None; 4679 } 4680 4681 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4682 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4683 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4684 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4685 /// follows one of the following patterns: 4686 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4687 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4688 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4689 /// we return the type of the truncation operation, and indicate whether the 4690 /// truncated type should be treated as signed/unsigned by setting 4691 /// \p Signed to true/false, respectively. 4692 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4693 bool &Signed, ScalarEvolution &SE) { 4694 // The case where Op == SymbolicPHI (that is, with no type conversions on 4695 // the way) is handled by the regular add recurrence creating logic and 4696 // would have already been triggered in createAddRecForPHI. Reaching it here 4697 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4698 // because one of the other operands of the SCEVAddExpr updating this PHI is 4699 // not invariant). 4700 // 4701 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4702 // this case predicates that allow us to prove that Op == SymbolicPHI will 4703 // be added. 4704 if (Op == SymbolicPHI) 4705 return nullptr; 4706 4707 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4708 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4709 if (SourceBits != NewBits) 4710 return nullptr; 4711 4712 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4713 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4714 if (!SExt && !ZExt) 4715 return nullptr; 4716 const SCEVTruncateExpr *Trunc = 4717 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4718 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4719 if (!Trunc) 4720 return nullptr; 4721 const SCEV *X = Trunc->getOperand(); 4722 if (X != SymbolicPHI) 4723 return nullptr; 4724 Signed = SExt != nullptr; 4725 return Trunc->getType(); 4726 } 4727 4728 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4729 if (!PN->getType()->isIntegerTy()) 4730 return nullptr; 4731 const Loop *L = LI.getLoopFor(PN->getParent()); 4732 if (!L || L->getHeader() != PN->getParent()) 4733 return nullptr; 4734 return L; 4735 } 4736 4737 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4738 // computation that updates the phi follows the following pattern: 4739 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4740 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4741 // If so, try to see if it can be rewritten as an AddRecExpr under some 4742 // Predicates. If successful, return them as a pair. Also cache the results 4743 // of the analysis. 4744 // 4745 // Example usage scenario: 4746 // Say the Rewriter is called for the following SCEV: 4747 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4748 // where: 4749 // %X = phi i64 (%Start, %BEValue) 4750 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4751 // and call this function with %SymbolicPHI = %X. 4752 // 4753 // The analysis will find that the value coming around the backedge has 4754 // the following SCEV: 4755 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4756 // Upon concluding that this matches the desired pattern, the function 4757 // will return the pair {NewAddRec, SmallPredsVec} where: 4758 // NewAddRec = {%Start,+,%Step} 4759 // SmallPredsVec = {P1, P2, P3} as follows: 4760 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4761 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4762 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4763 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4764 // under the predicates {P1,P2,P3}. 4765 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4766 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4767 // 4768 // TODO's: 4769 // 4770 // 1) Extend the Induction descriptor to also support inductions that involve 4771 // casts: When needed (namely, when we are called in the context of the 4772 // vectorizer induction analysis), a Set of cast instructions will be 4773 // populated by this method, and provided back to isInductionPHI. This is 4774 // needed to allow the vectorizer to properly record them to be ignored by 4775 // the cost model and to avoid vectorizing them (otherwise these casts, 4776 // which are redundant under the runtime overflow checks, will be 4777 // vectorized, which can be costly). 4778 // 4779 // 2) Support additional induction/PHISCEV patterns: We also want to support 4780 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4781 // after the induction update operation (the induction increment): 4782 // 4783 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4784 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4785 // 4786 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4787 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4788 // 4789 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4790 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4791 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4792 SmallVector<const SCEVPredicate *, 3> Predicates; 4793 4794 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4795 // return an AddRec expression under some predicate. 4796 4797 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4798 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4799 assert(L && "Expecting an integer loop header phi"); 4800 4801 // The loop may have multiple entrances or multiple exits; we can analyze 4802 // this phi as an addrec if it has a unique entry value and a unique 4803 // backedge value. 4804 Value *BEValueV = nullptr, *StartValueV = nullptr; 4805 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4806 Value *V = PN->getIncomingValue(i); 4807 if (L->contains(PN->getIncomingBlock(i))) { 4808 if (!BEValueV) { 4809 BEValueV = V; 4810 } else if (BEValueV != V) { 4811 BEValueV = nullptr; 4812 break; 4813 } 4814 } else if (!StartValueV) { 4815 StartValueV = V; 4816 } else if (StartValueV != V) { 4817 StartValueV = nullptr; 4818 break; 4819 } 4820 } 4821 if (!BEValueV || !StartValueV) 4822 return None; 4823 4824 const SCEV *BEValue = getSCEV(BEValueV); 4825 4826 // If the value coming around the backedge is an add with the symbolic 4827 // value we just inserted, possibly with casts that we can ignore under 4828 // an appropriate runtime guard, then we found a simple induction variable! 4829 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4830 if (!Add) 4831 return None; 4832 4833 // If there is a single occurrence of the symbolic value, possibly 4834 // casted, replace it with a recurrence. 4835 unsigned FoundIndex = Add->getNumOperands(); 4836 Type *TruncTy = nullptr; 4837 bool Signed; 4838 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4839 if ((TruncTy = 4840 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4841 if (FoundIndex == e) { 4842 FoundIndex = i; 4843 break; 4844 } 4845 4846 if (FoundIndex == Add->getNumOperands()) 4847 return None; 4848 4849 // Create an add with everything but the specified operand. 4850 SmallVector<const SCEV *, 8> Ops; 4851 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4852 if (i != FoundIndex) 4853 Ops.push_back(Add->getOperand(i)); 4854 const SCEV *Accum = getAddExpr(Ops); 4855 4856 // The runtime checks will not be valid if the step amount is 4857 // varying inside the loop. 4858 if (!isLoopInvariant(Accum, L)) 4859 return None; 4860 4861 // *** Part2: Create the predicates 4862 4863 // Analysis was successful: we have a phi-with-cast pattern for which we 4864 // can return an AddRec expression under the following predicates: 4865 // 4866 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4867 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4868 // P2: An Equal predicate that guarantees that 4869 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4870 // P3: An Equal predicate that guarantees that 4871 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4872 // 4873 // As we next prove, the above predicates guarantee that: 4874 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4875 // 4876 // 4877 // More formally, we want to prove that: 4878 // Expr(i+1) = Start + (i+1) * Accum 4879 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4880 // 4881 // Given that: 4882 // 1) Expr(0) = Start 4883 // 2) Expr(1) = Start + Accum 4884 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4885 // 3) Induction hypothesis (step i): 4886 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4887 // 4888 // Proof: 4889 // Expr(i+1) = 4890 // = Start + (i+1)*Accum 4891 // = (Start + i*Accum) + Accum 4892 // = Expr(i) + Accum 4893 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4894 // :: from step i 4895 // 4896 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4897 // 4898 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4899 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4900 // + Accum :: from P3 4901 // 4902 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4903 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4904 // 4905 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4906 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4907 // 4908 // By induction, the same applies to all iterations 1<=i<n: 4909 // 4910 4911 // Create a truncated addrec for which we will add a no overflow check (P1). 4912 const SCEV *StartVal = getSCEV(StartValueV); 4913 const SCEV *PHISCEV = 4914 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4915 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4916 4917 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4918 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4919 // will be constant. 4920 // 4921 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4922 // add P1. 4923 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4924 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4925 Signed ? SCEVWrapPredicate::IncrementNSSW 4926 : SCEVWrapPredicate::IncrementNUSW; 4927 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4928 Predicates.push_back(AddRecPred); 4929 } 4930 4931 // Create the Equal Predicates P2,P3: 4932 4933 // It is possible that the predicates P2 and/or P3 are computable at 4934 // compile time due to StartVal and/or Accum being constants. 4935 // If either one is, then we can check that now and escape if either P2 4936 // or P3 is false. 4937 4938 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4939 // for each of StartVal and Accum 4940 auto getExtendedExpr = [&](const SCEV *Expr, 4941 bool CreateSignExtend) -> const SCEV * { 4942 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4943 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4944 const SCEV *ExtendedExpr = 4945 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4946 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4947 return ExtendedExpr; 4948 }; 4949 4950 // Given: 4951 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4952 // = getExtendedExpr(Expr) 4953 // Determine whether the predicate P: Expr == ExtendedExpr 4954 // is known to be false at compile time 4955 auto PredIsKnownFalse = [&](const SCEV *Expr, 4956 const SCEV *ExtendedExpr) -> bool { 4957 return Expr != ExtendedExpr && 4958 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4959 }; 4960 4961 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4962 if (PredIsKnownFalse(StartVal, StartExtended)) { 4963 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4964 return None; 4965 } 4966 4967 // The Step is always Signed (because the overflow checks are either 4968 // NSSW or NUSW) 4969 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4970 if (PredIsKnownFalse(Accum, AccumExtended)) { 4971 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4972 return None; 4973 } 4974 4975 auto AppendPredicate = [&](const SCEV *Expr, 4976 const SCEV *ExtendedExpr) -> void { 4977 if (Expr != ExtendedExpr && 4978 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4979 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4980 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4981 Predicates.push_back(Pred); 4982 } 4983 }; 4984 4985 AppendPredicate(StartVal, StartExtended); 4986 AppendPredicate(Accum, AccumExtended); 4987 4988 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4989 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4990 // into NewAR if it will also add the runtime overflow checks specified in 4991 // Predicates. 4992 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4993 4994 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4995 std::make_pair(NewAR, Predicates); 4996 // Remember the result of the analysis for this SCEV at this locayyytion. 4997 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4998 return PredRewrite; 4999 } 5000 5001 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5002 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5003 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5004 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5005 if (!L) 5006 return None; 5007 5008 // Check to see if we already analyzed this PHI. 5009 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5010 if (I != PredicatedSCEVRewrites.end()) { 5011 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5012 I->second; 5013 // Analysis was done before and failed to create an AddRec: 5014 if (Rewrite.first == SymbolicPHI) 5015 return None; 5016 // Analysis was done before and succeeded to create an AddRec under 5017 // a predicate: 5018 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5019 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5020 return Rewrite; 5021 } 5022 5023 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5024 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5025 5026 // Record in the cache that the analysis failed 5027 if (!Rewrite) { 5028 SmallVector<const SCEVPredicate *, 3> Predicates; 5029 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5030 return None; 5031 } 5032 5033 return Rewrite; 5034 } 5035 5036 // FIXME: This utility is currently required because the Rewriter currently 5037 // does not rewrite this expression: 5038 // {0, +, (sext ix (trunc iy to ix) to iy)} 5039 // into {0, +, %step}, 5040 // even when the following Equal predicate exists: 5041 // "%step == (sext ix (trunc iy to ix) to iy)". 5042 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5043 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5044 if (AR1 == AR2) 5045 return true; 5046 5047 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5048 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 5049 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 5050 return false; 5051 return true; 5052 }; 5053 5054 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5055 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5056 return false; 5057 return true; 5058 } 5059 5060 /// A helper function for createAddRecFromPHI to handle simple cases. 5061 /// 5062 /// This function tries to find an AddRec expression for the simplest (yet most 5063 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5064 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5065 /// technique for finding the AddRec expression. 5066 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5067 Value *BEValueV, 5068 Value *StartValueV) { 5069 const Loop *L = LI.getLoopFor(PN->getParent()); 5070 assert(L && L->getHeader() == PN->getParent()); 5071 assert(BEValueV && StartValueV); 5072 5073 auto BO = MatchBinaryOp(BEValueV, DT); 5074 if (!BO) 5075 return nullptr; 5076 5077 if (BO->Opcode != Instruction::Add) 5078 return nullptr; 5079 5080 const SCEV *Accum = nullptr; 5081 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5082 Accum = getSCEV(BO->RHS); 5083 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5084 Accum = getSCEV(BO->LHS); 5085 5086 if (!Accum) 5087 return nullptr; 5088 5089 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5090 if (BO->IsNUW) 5091 Flags = setFlags(Flags, SCEV::FlagNUW); 5092 if (BO->IsNSW) 5093 Flags = setFlags(Flags, SCEV::FlagNSW); 5094 5095 const SCEV *StartVal = getSCEV(StartValueV); 5096 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5097 5098 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5099 5100 // We can add Flags to the post-inc expression only if we 5101 // know that it is *undefined behavior* for BEValueV to 5102 // overflow. 5103 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5104 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5105 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5106 5107 return PHISCEV; 5108 } 5109 5110 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5111 const Loop *L = LI.getLoopFor(PN->getParent()); 5112 if (!L || L->getHeader() != PN->getParent()) 5113 return nullptr; 5114 5115 // The loop may have multiple entrances or multiple exits; we can analyze 5116 // this phi as an addrec if it has a unique entry value and a unique 5117 // backedge value. 5118 Value *BEValueV = nullptr, *StartValueV = nullptr; 5119 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5120 Value *V = PN->getIncomingValue(i); 5121 if (L->contains(PN->getIncomingBlock(i))) { 5122 if (!BEValueV) { 5123 BEValueV = V; 5124 } else if (BEValueV != V) { 5125 BEValueV = nullptr; 5126 break; 5127 } 5128 } else if (!StartValueV) { 5129 StartValueV = V; 5130 } else if (StartValueV != V) { 5131 StartValueV = nullptr; 5132 break; 5133 } 5134 } 5135 if (!BEValueV || !StartValueV) 5136 return nullptr; 5137 5138 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5139 "PHI node already processed?"); 5140 5141 // First, try to find AddRec expression without creating a fictituos symbolic 5142 // value for PN. 5143 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5144 return S; 5145 5146 // Handle PHI node value symbolically. 5147 const SCEV *SymbolicName = getUnknown(PN); 5148 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5149 5150 // Using this symbolic name for the PHI, analyze the value coming around 5151 // the back-edge. 5152 const SCEV *BEValue = getSCEV(BEValueV); 5153 5154 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5155 // has a special value for the first iteration of the loop. 5156 5157 // If the value coming around the backedge is an add with the symbolic 5158 // value we just inserted, then we found a simple induction variable! 5159 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5160 // If there is a single occurrence of the symbolic value, replace it 5161 // with a recurrence. 5162 unsigned FoundIndex = Add->getNumOperands(); 5163 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5164 if (Add->getOperand(i) == SymbolicName) 5165 if (FoundIndex == e) { 5166 FoundIndex = i; 5167 break; 5168 } 5169 5170 if (FoundIndex != Add->getNumOperands()) { 5171 // Create an add with everything but the specified operand. 5172 SmallVector<const SCEV *, 8> Ops; 5173 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5174 if (i != FoundIndex) 5175 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5176 L, *this)); 5177 const SCEV *Accum = getAddExpr(Ops); 5178 5179 // This is not a valid addrec if the step amount is varying each 5180 // loop iteration, but is not itself an addrec in this loop. 5181 if (isLoopInvariant(Accum, L) || 5182 (isa<SCEVAddRecExpr>(Accum) && 5183 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5184 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5185 5186 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5187 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5188 if (BO->IsNUW) 5189 Flags = setFlags(Flags, SCEV::FlagNUW); 5190 if (BO->IsNSW) 5191 Flags = setFlags(Flags, SCEV::FlagNSW); 5192 } 5193 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5194 // If the increment is an inbounds GEP, then we know the address 5195 // space cannot be wrapped around. We cannot make any guarantee 5196 // about signed or unsigned overflow because pointers are 5197 // unsigned but we may have a negative index from the base 5198 // pointer. We can guarantee that no unsigned wrap occurs if the 5199 // indices form a positive value. 5200 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5201 Flags = setFlags(Flags, SCEV::FlagNW); 5202 5203 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5204 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5205 Flags = setFlags(Flags, SCEV::FlagNUW); 5206 } 5207 5208 // We cannot transfer nuw and nsw flags from subtraction 5209 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5210 // for instance. 5211 } 5212 5213 const SCEV *StartVal = getSCEV(StartValueV); 5214 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5215 5216 // Okay, for the entire analysis of this edge we assumed the PHI 5217 // to be symbolic. We now need to go back and purge all of the 5218 // entries for the scalars that use the symbolic expression. 5219 forgetSymbolicName(PN, SymbolicName); 5220 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5221 5222 // We can add Flags to the post-inc expression only if we 5223 // know that it is *undefined behavior* for BEValueV to 5224 // overflow. 5225 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5226 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5227 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5228 5229 return PHISCEV; 5230 } 5231 } 5232 } else { 5233 // Otherwise, this could be a loop like this: 5234 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5235 // In this case, j = {1,+,1} and BEValue is j. 5236 // Because the other in-value of i (0) fits the evolution of BEValue 5237 // i really is an addrec evolution. 5238 // 5239 // We can generalize this saying that i is the shifted value of BEValue 5240 // by one iteration: 5241 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5242 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5243 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5244 if (Shifted != getCouldNotCompute() && 5245 Start != getCouldNotCompute()) { 5246 const SCEV *StartVal = getSCEV(StartValueV); 5247 if (Start == StartVal) { 5248 // Okay, for the entire analysis of this edge we assumed the PHI 5249 // to be symbolic. We now need to go back and purge all of the 5250 // entries for the scalars that use the symbolic expression. 5251 forgetSymbolicName(PN, SymbolicName); 5252 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5253 return Shifted; 5254 } 5255 } 5256 } 5257 5258 // Remove the temporary PHI node SCEV that has been inserted while intending 5259 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5260 // as it will prevent later (possibly simpler) SCEV expressions to be added 5261 // to the ValueExprMap. 5262 eraseValueFromMap(PN); 5263 5264 return nullptr; 5265 } 5266 5267 // Checks if the SCEV S is available at BB. S is considered available at BB 5268 // if S can be materialized at BB without introducing a fault. 5269 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5270 BasicBlock *BB) { 5271 struct CheckAvailable { 5272 bool TraversalDone = false; 5273 bool Available = true; 5274 5275 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5276 BasicBlock *BB = nullptr; 5277 DominatorTree &DT; 5278 5279 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5280 : L(L), BB(BB), DT(DT) {} 5281 5282 bool setUnavailable() { 5283 TraversalDone = true; 5284 Available = false; 5285 return false; 5286 } 5287 5288 bool follow(const SCEV *S) { 5289 switch (S->getSCEVType()) { 5290 case scConstant: 5291 case scPtrToInt: 5292 case scTruncate: 5293 case scZeroExtend: 5294 case scSignExtend: 5295 case scAddExpr: 5296 case scMulExpr: 5297 case scUMaxExpr: 5298 case scSMaxExpr: 5299 case scUMinExpr: 5300 case scSMinExpr: 5301 // These expressions are available if their operand(s) is/are. 5302 return true; 5303 5304 case scAddRecExpr: { 5305 // We allow add recurrences that are on the loop BB is in, or some 5306 // outer loop. This guarantees availability because the value of the 5307 // add recurrence at BB is simply the "current" value of the induction 5308 // variable. We can relax this in the future; for instance an add 5309 // recurrence on a sibling dominating loop is also available at BB. 5310 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5311 if (L && (ARLoop == L || ARLoop->contains(L))) 5312 return true; 5313 5314 return setUnavailable(); 5315 } 5316 5317 case scUnknown: { 5318 // For SCEVUnknown, we check for simple dominance. 5319 const auto *SU = cast<SCEVUnknown>(S); 5320 Value *V = SU->getValue(); 5321 5322 if (isa<Argument>(V)) 5323 return false; 5324 5325 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5326 return false; 5327 5328 return setUnavailable(); 5329 } 5330 5331 case scUDivExpr: 5332 case scCouldNotCompute: 5333 // We do not try to smart about these at all. 5334 return setUnavailable(); 5335 } 5336 llvm_unreachable("Unknown SCEV kind!"); 5337 } 5338 5339 bool isDone() { return TraversalDone; } 5340 }; 5341 5342 CheckAvailable CA(L, BB, DT); 5343 SCEVTraversal<CheckAvailable> ST(CA); 5344 5345 ST.visitAll(S); 5346 return CA.Available; 5347 } 5348 5349 // Try to match a control flow sequence that branches out at BI and merges back 5350 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5351 // match. 5352 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5353 Value *&C, Value *&LHS, Value *&RHS) { 5354 C = BI->getCondition(); 5355 5356 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5357 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5358 5359 if (!LeftEdge.isSingleEdge()) 5360 return false; 5361 5362 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5363 5364 Use &LeftUse = Merge->getOperandUse(0); 5365 Use &RightUse = Merge->getOperandUse(1); 5366 5367 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5368 LHS = LeftUse; 5369 RHS = RightUse; 5370 return true; 5371 } 5372 5373 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5374 LHS = RightUse; 5375 RHS = LeftUse; 5376 return true; 5377 } 5378 5379 return false; 5380 } 5381 5382 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5383 auto IsReachable = 5384 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5385 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5386 const Loop *L = LI.getLoopFor(PN->getParent()); 5387 5388 // We don't want to break LCSSA, even in a SCEV expression tree. 5389 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5390 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5391 return nullptr; 5392 5393 // Try to match 5394 // 5395 // br %cond, label %left, label %right 5396 // left: 5397 // br label %merge 5398 // right: 5399 // br label %merge 5400 // merge: 5401 // V = phi [ %x, %left ], [ %y, %right ] 5402 // 5403 // as "select %cond, %x, %y" 5404 5405 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5406 assert(IDom && "At least the entry block should dominate PN"); 5407 5408 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5409 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5410 5411 if (BI && BI->isConditional() && 5412 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5413 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5414 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5415 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5416 } 5417 5418 return nullptr; 5419 } 5420 5421 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5422 if (const SCEV *S = createAddRecFromPHI(PN)) 5423 return S; 5424 5425 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5426 return S; 5427 5428 // If the PHI has a single incoming value, follow that value, unless the 5429 // PHI's incoming blocks are in a different loop, in which case doing so 5430 // risks breaking LCSSA form. Instcombine would normally zap these, but 5431 // it doesn't have DominatorTree information, so it may miss cases. 5432 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5433 if (LI.replacementPreservesLCSSAForm(PN, V)) 5434 return getSCEV(V); 5435 5436 // If it's not a loop phi, we can't handle it yet. 5437 return getUnknown(PN); 5438 } 5439 5440 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5441 Value *Cond, 5442 Value *TrueVal, 5443 Value *FalseVal) { 5444 // Handle "constant" branch or select. This can occur for instance when a 5445 // loop pass transforms an inner loop and moves on to process the outer loop. 5446 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5447 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5448 5449 // Try to match some simple smax or umax patterns. 5450 auto *ICI = dyn_cast<ICmpInst>(Cond); 5451 if (!ICI) 5452 return getUnknown(I); 5453 5454 Value *LHS = ICI->getOperand(0); 5455 Value *RHS = ICI->getOperand(1); 5456 5457 switch (ICI->getPredicate()) { 5458 case ICmpInst::ICMP_SLT: 5459 case ICmpInst::ICMP_SLE: 5460 std::swap(LHS, RHS); 5461 LLVM_FALLTHROUGH; 5462 case ICmpInst::ICMP_SGT: 5463 case ICmpInst::ICMP_SGE: 5464 // a >s b ? a+x : b+x -> smax(a, b)+x 5465 // a >s b ? b+x : a+x -> smin(a, b)+x 5466 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5467 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5468 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5469 const SCEV *LA = getSCEV(TrueVal); 5470 const SCEV *RA = getSCEV(FalseVal); 5471 const SCEV *LDiff = getMinusSCEV(LA, LS); 5472 const SCEV *RDiff = getMinusSCEV(RA, RS); 5473 if (LDiff == RDiff) 5474 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5475 LDiff = getMinusSCEV(LA, RS); 5476 RDiff = getMinusSCEV(RA, LS); 5477 if (LDiff == RDiff) 5478 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5479 } 5480 break; 5481 case ICmpInst::ICMP_ULT: 5482 case ICmpInst::ICMP_ULE: 5483 std::swap(LHS, RHS); 5484 LLVM_FALLTHROUGH; 5485 case ICmpInst::ICMP_UGT: 5486 case ICmpInst::ICMP_UGE: 5487 // a >u b ? a+x : b+x -> umax(a, b)+x 5488 // a >u b ? b+x : a+x -> umin(a, b)+x 5489 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5490 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5491 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5492 const SCEV *LA = getSCEV(TrueVal); 5493 const SCEV *RA = getSCEV(FalseVal); 5494 const SCEV *LDiff = getMinusSCEV(LA, LS); 5495 const SCEV *RDiff = getMinusSCEV(RA, RS); 5496 if (LDiff == RDiff) 5497 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5498 LDiff = getMinusSCEV(LA, RS); 5499 RDiff = getMinusSCEV(RA, LS); 5500 if (LDiff == RDiff) 5501 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5502 } 5503 break; 5504 case ICmpInst::ICMP_NE: 5505 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5506 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5507 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5508 const SCEV *One = getOne(I->getType()); 5509 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5510 const SCEV *LA = getSCEV(TrueVal); 5511 const SCEV *RA = getSCEV(FalseVal); 5512 const SCEV *LDiff = getMinusSCEV(LA, LS); 5513 const SCEV *RDiff = getMinusSCEV(RA, One); 5514 if (LDiff == RDiff) 5515 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5516 } 5517 break; 5518 case ICmpInst::ICMP_EQ: 5519 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5520 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5521 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5522 const SCEV *One = getOne(I->getType()); 5523 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5524 const SCEV *LA = getSCEV(TrueVal); 5525 const SCEV *RA = getSCEV(FalseVal); 5526 const SCEV *LDiff = getMinusSCEV(LA, One); 5527 const SCEV *RDiff = getMinusSCEV(RA, LS); 5528 if (LDiff == RDiff) 5529 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5530 } 5531 break; 5532 default: 5533 break; 5534 } 5535 5536 return getUnknown(I); 5537 } 5538 5539 /// Expand GEP instructions into add and multiply operations. This allows them 5540 /// to be analyzed by regular SCEV code. 5541 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5542 // Don't attempt to analyze GEPs over unsized objects. 5543 if (!GEP->getSourceElementType()->isSized()) 5544 return getUnknown(GEP); 5545 5546 SmallVector<const SCEV *, 4> IndexExprs; 5547 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5548 IndexExprs.push_back(getSCEV(*Index)); 5549 return getGEPExpr(GEP, IndexExprs); 5550 } 5551 5552 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5553 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5554 return C->getAPInt().countTrailingZeros(); 5555 5556 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5557 return GetMinTrailingZeros(I->getOperand()); 5558 5559 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5560 return std::min(GetMinTrailingZeros(T->getOperand()), 5561 (uint32_t)getTypeSizeInBits(T->getType())); 5562 5563 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5564 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5565 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5566 ? getTypeSizeInBits(E->getType()) 5567 : OpRes; 5568 } 5569 5570 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5571 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5572 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5573 ? getTypeSizeInBits(E->getType()) 5574 : OpRes; 5575 } 5576 5577 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5578 // The result is the min of all operands results. 5579 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5580 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5581 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5582 return MinOpRes; 5583 } 5584 5585 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5586 // The result is the sum of all operands results. 5587 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5588 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5589 for (unsigned i = 1, e = M->getNumOperands(); 5590 SumOpRes != BitWidth && i != e; ++i) 5591 SumOpRes = 5592 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5593 return SumOpRes; 5594 } 5595 5596 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5597 // The result is the min of all operands results. 5598 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5599 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5600 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5601 return MinOpRes; 5602 } 5603 5604 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5605 // The result is the min of all operands results. 5606 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5607 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5608 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5609 return MinOpRes; 5610 } 5611 5612 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5613 // The result is the min of all operands results. 5614 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5615 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5616 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5617 return MinOpRes; 5618 } 5619 5620 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5621 // For a SCEVUnknown, ask ValueTracking. 5622 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5623 return Known.countMinTrailingZeros(); 5624 } 5625 5626 // SCEVUDivExpr 5627 return 0; 5628 } 5629 5630 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5631 auto I = MinTrailingZerosCache.find(S); 5632 if (I != MinTrailingZerosCache.end()) 5633 return I->second; 5634 5635 uint32_t Result = GetMinTrailingZerosImpl(S); 5636 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5637 assert(InsertPair.second && "Should insert a new key"); 5638 return InsertPair.first->second; 5639 } 5640 5641 /// Helper method to assign a range to V from metadata present in the IR. 5642 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5643 if (Instruction *I = dyn_cast<Instruction>(V)) 5644 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5645 return getConstantRangeFromMetadata(*MD); 5646 5647 return None; 5648 } 5649 5650 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 5651 SCEV::NoWrapFlags Flags) { 5652 if (AddRec->getNoWrapFlags(Flags) != Flags) { 5653 AddRec->setNoWrapFlags(Flags); 5654 UnsignedRanges.erase(AddRec); 5655 SignedRanges.erase(AddRec); 5656 } 5657 } 5658 5659 ConstantRange ScalarEvolution:: 5660 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 5661 const DataLayout &DL = getDataLayout(); 5662 5663 unsigned BitWidth = getTypeSizeInBits(U->getType()); 5664 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 5665 5666 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 5667 // use information about the trip count to improve our available range. Note 5668 // that the trip count independent cases are already handled by known bits. 5669 // WARNING: The definition of recurrence used here is subtly different than 5670 // the one used by AddRec (and thus most of this file). Step is allowed to 5671 // be arbitrarily loop varying here, where AddRec allows only loop invariant 5672 // and other addrecs in the same loop (for non-affine addrecs). The code 5673 // below intentionally handles the case where step is not loop invariant. 5674 auto *P = dyn_cast<PHINode>(U->getValue()); 5675 if (!P) 5676 return FullSet; 5677 5678 // Make sure that no Phi input comes from an unreachable block. Otherwise, 5679 // even the values that are not available in these blocks may come from them, 5680 // and this leads to false-positive recurrence test. 5681 for (auto *Pred : predecessors(P->getParent())) 5682 if (!DT.isReachableFromEntry(Pred)) 5683 return FullSet; 5684 5685 BinaryOperator *BO; 5686 Value *Start, *Step; 5687 if (!matchSimpleRecurrence(P, BO, Start, Step)) 5688 return FullSet; 5689 5690 // If we found a recurrence in reachable code, we must be in a loop. Note 5691 // that BO might be in some subloop of L, and that's completely okay. 5692 auto *L = LI.getLoopFor(P->getParent()); 5693 assert(L && L->getHeader() == P->getParent()); 5694 if (!L->contains(BO->getParent())) 5695 // NOTE: This bailout should be an assert instead. However, asserting 5696 // the condition here exposes a case where LoopFusion is querying SCEV 5697 // with malformed loop information during the midst of the transform. 5698 // There doesn't appear to be an obvious fix, so for the moment bailout 5699 // until the caller issue can be fixed. PR49566 tracks the bug. 5700 return FullSet; 5701 5702 // TODO: Extend to other opcodes such as mul, and div 5703 switch (BO->getOpcode()) { 5704 default: 5705 return FullSet; 5706 case Instruction::AShr: 5707 case Instruction::LShr: 5708 case Instruction::Shl: 5709 break; 5710 }; 5711 5712 if (BO->getOperand(0) != P) 5713 // TODO: Handle the power function forms some day. 5714 return FullSet; 5715 5716 unsigned TC = getSmallConstantMaxTripCount(L); 5717 if (!TC || TC >= BitWidth) 5718 return FullSet; 5719 5720 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 5721 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 5722 assert(KnownStart.getBitWidth() == BitWidth && 5723 KnownStep.getBitWidth() == BitWidth); 5724 5725 // Compute total shift amount, being careful of overflow and bitwidths. 5726 auto MaxShiftAmt = KnownStep.getMaxValue(); 5727 APInt TCAP(BitWidth, TC-1); 5728 bool Overflow = false; 5729 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 5730 if (Overflow) 5731 return FullSet; 5732 5733 switch (BO->getOpcode()) { 5734 default: 5735 llvm_unreachable("filtered out above"); 5736 case Instruction::AShr: { 5737 // For each ashr, three cases: 5738 // shift = 0 => unchanged value 5739 // saturation => 0 or -1 5740 // other => a value closer to zero (of the same sign) 5741 // Thus, the end value is closer to zero than the start. 5742 auto KnownEnd = KnownBits::ashr(KnownStart, 5743 KnownBits::makeConstant(TotalShift)); 5744 if (KnownStart.isNonNegative()) 5745 // Analogous to lshr (simply not yet canonicalized) 5746 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5747 KnownStart.getMaxValue() + 1); 5748 if (KnownStart.isNegative()) 5749 // End >=u Start && End <=s Start 5750 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 5751 KnownEnd.getMaxValue() + 1); 5752 break; 5753 } 5754 case Instruction::LShr: { 5755 // For each lshr, three cases: 5756 // shift = 0 => unchanged value 5757 // saturation => 0 5758 // other => a smaller positive number 5759 // Thus, the low end of the unsigned range is the last value produced. 5760 auto KnownEnd = KnownBits::lshr(KnownStart, 5761 KnownBits::makeConstant(TotalShift)); 5762 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5763 KnownStart.getMaxValue() + 1); 5764 } 5765 case Instruction::Shl: { 5766 // Iff no bits are shifted out, value increases on every shift. 5767 auto KnownEnd = KnownBits::shl(KnownStart, 5768 KnownBits::makeConstant(TotalShift)); 5769 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 5770 return ConstantRange(KnownStart.getMinValue(), 5771 KnownEnd.getMaxValue() + 1); 5772 break; 5773 } 5774 }; 5775 return FullSet; 5776 } 5777 5778 /// Determine the range for a particular SCEV. If SignHint is 5779 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5780 /// with a "cleaner" unsigned (resp. signed) representation. 5781 const ConstantRange & 5782 ScalarEvolution::getRangeRef(const SCEV *S, 5783 ScalarEvolution::RangeSignHint SignHint) { 5784 DenseMap<const SCEV *, ConstantRange> &Cache = 5785 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5786 : SignedRanges; 5787 ConstantRange::PreferredRangeType RangeType = 5788 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5789 ? ConstantRange::Unsigned : ConstantRange::Signed; 5790 5791 // See if we've computed this range already. 5792 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5793 if (I != Cache.end()) 5794 return I->second; 5795 5796 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5797 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5798 5799 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5800 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5801 using OBO = OverflowingBinaryOperator; 5802 5803 // If the value has known zeros, the maximum value will have those known zeros 5804 // as well. 5805 uint32_t TZ = GetMinTrailingZeros(S); 5806 if (TZ != 0) { 5807 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5808 ConservativeResult = 5809 ConstantRange(APInt::getMinValue(BitWidth), 5810 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5811 else 5812 ConservativeResult = ConstantRange( 5813 APInt::getSignedMinValue(BitWidth), 5814 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5815 } 5816 5817 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5818 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5819 unsigned WrapType = OBO::AnyWrap; 5820 if (Add->hasNoSignedWrap()) 5821 WrapType |= OBO::NoSignedWrap; 5822 if (Add->hasNoUnsignedWrap()) 5823 WrapType |= OBO::NoUnsignedWrap; 5824 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5825 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 5826 WrapType, RangeType); 5827 return setRange(Add, SignHint, 5828 ConservativeResult.intersectWith(X, RangeType)); 5829 } 5830 5831 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5832 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5833 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5834 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5835 return setRange(Mul, SignHint, 5836 ConservativeResult.intersectWith(X, RangeType)); 5837 } 5838 5839 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5840 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5841 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5842 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5843 return setRange(SMax, SignHint, 5844 ConservativeResult.intersectWith(X, RangeType)); 5845 } 5846 5847 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5848 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5849 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5850 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5851 return setRange(UMax, SignHint, 5852 ConservativeResult.intersectWith(X, RangeType)); 5853 } 5854 5855 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5856 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5857 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5858 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5859 return setRange(SMin, SignHint, 5860 ConservativeResult.intersectWith(X, RangeType)); 5861 } 5862 5863 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5864 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5865 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5866 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5867 return setRange(UMin, SignHint, 5868 ConservativeResult.intersectWith(X, RangeType)); 5869 } 5870 5871 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5872 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5873 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5874 return setRange(UDiv, SignHint, 5875 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5876 } 5877 5878 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5879 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5880 return setRange(ZExt, SignHint, 5881 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5882 RangeType)); 5883 } 5884 5885 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5886 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5887 return setRange(SExt, SignHint, 5888 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5889 RangeType)); 5890 } 5891 5892 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 5893 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 5894 return setRange(PtrToInt, SignHint, X); 5895 } 5896 5897 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5898 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5899 return setRange(Trunc, SignHint, 5900 ConservativeResult.intersectWith(X.truncate(BitWidth), 5901 RangeType)); 5902 } 5903 5904 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5905 // If there's no unsigned wrap, the value will never be less than its 5906 // initial value. 5907 if (AddRec->hasNoUnsignedWrap()) { 5908 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 5909 if (!UnsignedMinValue.isNullValue()) 5910 ConservativeResult = ConservativeResult.intersectWith( 5911 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 5912 } 5913 5914 // If there's no signed wrap, and all the operands except initial value have 5915 // the same sign or zero, the value won't ever be: 5916 // 1: smaller than initial value if operands are non negative, 5917 // 2: bigger than initial value if operands are non positive. 5918 // For both cases, value can not cross signed min/max boundary. 5919 if (AddRec->hasNoSignedWrap()) { 5920 bool AllNonNeg = true; 5921 bool AllNonPos = true; 5922 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 5923 if (!isKnownNonNegative(AddRec->getOperand(i))) 5924 AllNonNeg = false; 5925 if (!isKnownNonPositive(AddRec->getOperand(i))) 5926 AllNonPos = false; 5927 } 5928 if (AllNonNeg) 5929 ConservativeResult = ConservativeResult.intersectWith( 5930 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 5931 APInt::getSignedMinValue(BitWidth)), 5932 RangeType); 5933 else if (AllNonPos) 5934 ConservativeResult = ConservativeResult.intersectWith( 5935 ConstantRange::getNonEmpty( 5936 APInt::getSignedMinValue(BitWidth), 5937 getSignedRangeMax(AddRec->getStart()) + 1), 5938 RangeType); 5939 } 5940 5941 // TODO: non-affine addrec 5942 if (AddRec->isAffine()) { 5943 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5944 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5945 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5946 auto RangeFromAffine = getRangeForAffineAR( 5947 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5948 BitWidth); 5949 ConservativeResult = 5950 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5951 5952 auto RangeFromFactoring = getRangeViaFactoring( 5953 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5954 BitWidth); 5955 ConservativeResult = 5956 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5957 } 5958 5959 // Now try symbolic BE count and more powerful methods. 5960 if (UseExpensiveRangeSharpening) { 5961 const SCEV *SymbolicMaxBECount = 5962 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 5963 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 5964 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5965 AddRec->hasNoSelfWrap()) { 5966 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 5967 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 5968 ConservativeResult = 5969 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 5970 } 5971 } 5972 } 5973 5974 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5975 } 5976 5977 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5978 5979 // Check if the IR explicitly contains !range metadata. 5980 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5981 if (MDRange.hasValue()) 5982 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5983 RangeType); 5984 5985 // Use facts about recurrences in the underlying IR. Note that add 5986 // recurrences are AddRecExprs and thus don't hit this path. This 5987 // primarily handles shift recurrences. 5988 auto CR = getRangeForUnknownRecurrence(U); 5989 ConservativeResult = ConservativeResult.intersectWith(CR); 5990 5991 // See if ValueTracking can give us a useful range. 5992 const DataLayout &DL = getDataLayout(); 5993 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5994 if (Known.getBitWidth() != BitWidth) 5995 Known = Known.zextOrTrunc(BitWidth); 5996 5997 // ValueTracking may be able to compute a tighter result for the number of 5998 // sign bits than for the value of those sign bits. 5999 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6000 if (U->getType()->isPointerTy()) { 6001 // If the pointer size is larger than the index size type, this can cause 6002 // NS to be larger than BitWidth. So compensate for this. 6003 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6004 int ptrIdxDiff = ptrSize - BitWidth; 6005 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6006 NS -= ptrIdxDiff; 6007 } 6008 6009 if (NS > 1) { 6010 // If we know any of the sign bits, we know all of the sign bits. 6011 if (!Known.Zero.getHiBits(NS).isNullValue()) 6012 Known.Zero.setHighBits(NS); 6013 if (!Known.One.getHiBits(NS).isNullValue()) 6014 Known.One.setHighBits(NS); 6015 } 6016 6017 if (Known.getMinValue() != Known.getMaxValue() + 1) 6018 ConservativeResult = ConservativeResult.intersectWith( 6019 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6020 RangeType); 6021 if (NS > 1) 6022 ConservativeResult = ConservativeResult.intersectWith( 6023 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6024 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6025 RangeType); 6026 6027 // A range of Phi is a subset of union of all ranges of its input. 6028 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 6029 // Make sure that we do not run over cycled Phis. 6030 if (PendingPhiRanges.insert(Phi).second) { 6031 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 6032 for (auto &Op : Phi->operands()) { 6033 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 6034 RangeFromOps = RangeFromOps.unionWith(OpRange); 6035 // No point to continue if we already have a full set. 6036 if (RangeFromOps.isFullSet()) 6037 break; 6038 } 6039 ConservativeResult = 6040 ConservativeResult.intersectWith(RangeFromOps, RangeType); 6041 bool Erased = PendingPhiRanges.erase(Phi); 6042 assert(Erased && "Failed to erase Phi properly?"); 6043 (void) Erased; 6044 } 6045 } 6046 6047 return setRange(U, SignHint, std::move(ConservativeResult)); 6048 } 6049 6050 return setRange(S, SignHint, std::move(ConservativeResult)); 6051 } 6052 6053 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6054 // values that the expression can take. Initially, the expression has a value 6055 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6056 // argument defines if we treat Step as signed or unsigned. 6057 static ConstantRange getRangeForAffineARHelper(APInt Step, 6058 const ConstantRange &StartRange, 6059 const APInt &MaxBECount, 6060 unsigned BitWidth, bool Signed) { 6061 // If either Step or MaxBECount is 0, then the expression won't change, and we 6062 // just need to return the initial range. 6063 if (Step == 0 || MaxBECount == 0) 6064 return StartRange; 6065 6066 // If we don't know anything about the initial value (i.e. StartRange is 6067 // FullRange), then we don't know anything about the final range either. 6068 // Return FullRange. 6069 if (StartRange.isFullSet()) 6070 return ConstantRange::getFull(BitWidth); 6071 6072 // If Step is signed and negative, then we use its absolute value, but we also 6073 // note that we're moving in the opposite direction. 6074 bool Descending = Signed && Step.isNegative(); 6075 6076 if (Signed) 6077 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6078 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6079 // This equations hold true due to the well-defined wrap-around behavior of 6080 // APInt. 6081 Step = Step.abs(); 6082 6083 // Check if Offset is more than full span of BitWidth. If it is, the 6084 // expression is guaranteed to overflow. 6085 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6086 return ConstantRange::getFull(BitWidth); 6087 6088 // Offset is by how much the expression can change. Checks above guarantee no 6089 // overflow here. 6090 APInt Offset = Step * MaxBECount; 6091 6092 // Minimum value of the final range will match the minimal value of StartRange 6093 // if the expression is increasing and will be decreased by Offset otherwise. 6094 // Maximum value of the final range will match the maximal value of StartRange 6095 // if the expression is decreasing and will be increased by Offset otherwise. 6096 APInt StartLower = StartRange.getLower(); 6097 APInt StartUpper = StartRange.getUpper() - 1; 6098 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6099 : (StartUpper + std::move(Offset)); 6100 6101 // It's possible that the new minimum/maximum value will fall into the initial 6102 // range (due to wrap around). This means that the expression can take any 6103 // value in this bitwidth, and we have to return full range. 6104 if (StartRange.contains(MovedBoundary)) 6105 return ConstantRange::getFull(BitWidth); 6106 6107 APInt NewLower = 6108 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6109 APInt NewUpper = 6110 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6111 NewUpper += 1; 6112 6113 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6114 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6115 } 6116 6117 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6118 const SCEV *Step, 6119 const SCEV *MaxBECount, 6120 unsigned BitWidth) { 6121 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6122 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6123 "Precondition!"); 6124 6125 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6126 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6127 6128 // First, consider step signed. 6129 ConstantRange StartSRange = getSignedRange(Start); 6130 ConstantRange StepSRange = getSignedRange(Step); 6131 6132 // If Step can be both positive and negative, we need to find ranges for the 6133 // maximum absolute step values in both directions and union them. 6134 ConstantRange SR = 6135 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6136 MaxBECountValue, BitWidth, /* Signed = */ true); 6137 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6138 StartSRange, MaxBECountValue, 6139 BitWidth, /* Signed = */ true)); 6140 6141 // Next, consider step unsigned. 6142 ConstantRange UR = getRangeForAffineARHelper( 6143 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6144 MaxBECountValue, BitWidth, /* Signed = */ false); 6145 6146 // Finally, intersect signed and unsigned ranges. 6147 return SR.intersectWith(UR, ConstantRange::Smallest); 6148 } 6149 6150 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6151 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6152 ScalarEvolution::RangeSignHint SignHint) { 6153 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6154 assert(AddRec->hasNoSelfWrap() && 6155 "This only works for non-self-wrapping AddRecs!"); 6156 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6157 const SCEV *Step = AddRec->getStepRecurrence(*this); 6158 // Only deal with constant step to save compile time. 6159 if (!isa<SCEVConstant>(Step)) 6160 return ConstantRange::getFull(BitWidth); 6161 // Let's make sure that we can prove that we do not self-wrap during 6162 // MaxBECount iterations. We need this because MaxBECount is a maximum 6163 // iteration count estimate, and we might infer nw from some exit for which we 6164 // do not know max exit count (or any other side reasoning). 6165 // TODO: Turn into assert at some point. 6166 if (getTypeSizeInBits(MaxBECount->getType()) > 6167 getTypeSizeInBits(AddRec->getType())) 6168 return ConstantRange::getFull(BitWidth); 6169 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6170 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6171 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6172 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6173 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6174 MaxItersWithoutWrap)) 6175 return ConstantRange::getFull(BitWidth); 6176 6177 ICmpInst::Predicate LEPred = 6178 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6179 ICmpInst::Predicate GEPred = 6180 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6181 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6182 6183 // We know that there is no self-wrap. Let's take Start and End values and 6184 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6185 // the iteration. They either lie inside the range [Min(Start, End), 6186 // Max(Start, End)] or outside it: 6187 // 6188 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6189 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6190 // 6191 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6192 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6193 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6194 // Start <= End and step is positive, or Start >= End and step is negative. 6195 const SCEV *Start = AddRec->getStart(); 6196 ConstantRange StartRange = getRangeRef(Start, SignHint); 6197 ConstantRange EndRange = getRangeRef(End, SignHint); 6198 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6199 // If they already cover full iteration space, we will know nothing useful 6200 // even if we prove what we want to prove. 6201 if (RangeBetween.isFullSet()) 6202 return RangeBetween; 6203 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6204 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6205 : RangeBetween.isWrappedSet(); 6206 if (IsWrappedSet) 6207 return ConstantRange::getFull(BitWidth); 6208 6209 if (isKnownPositive(Step) && 6210 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6211 return RangeBetween; 6212 else if (isKnownNegative(Step) && 6213 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6214 return RangeBetween; 6215 return ConstantRange::getFull(BitWidth); 6216 } 6217 6218 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6219 const SCEV *Step, 6220 const SCEV *MaxBECount, 6221 unsigned BitWidth) { 6222 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6223 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6224 6225 struct SelectPattern { 6226 Value *Condition = nullptr; 6227 APInt TrueValue; 6228 APInt FalseValue; 6229 6230 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6231 const SCEV *S) { 6232 Optional<unsigned> CastOp; 6233 APInt Offset(BitWidth, 0); 6234 6235 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6236 "Should be!"); 6237 6238 // Peel off a constant offset: 6239 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6240 // In the future we could consider being smarter here and handle 6241 // {Start+Step,+,Step} too. 6242 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6243 return; 6244 6245 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6246 S = SA->getOperand(1); 6247 } 6248 6249 // Peel off a cast operation 6250 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6251 CastOp = SCast->getSCEVType(); 6252 S = SCast->getOperand(); 6253 } 6254 6255 using namespace llvm::PatternMatch; 6256 6257 auto *SU = dyn_cast<SCEVUnknown>(S); 6258 const APInt *TrueVal, *FalseVal; 6259 if (!SU || 6260 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6261 m_APInt(FalseVal)))) { 6262 Condition = nullptr; 6263 return; 6264 } 6265 6266 TrueValue = *TrueVal; 6267 FalseValue = *FalseVal; 6268 6269 // Re-apply the cast we peeled off earlier 6270 if (CastOp.hasValue()) 6271 switch (*CastOp) { 6272 default: 6273 llvm_unreachable("Unknown SCEV cast type!"); 6274 6275 case scTruncate: 6276 TrueValue = TrueValue.trunc(BitWidth); 6277 FalseValue = FalseValue.trunc(BitWidth); 6278 break; 6279 case scZeroExtend: 6280 TrueValue = TrueValue.zext(BitWidth); 6281 FalseValue = FalseValue.zext(BitWidth); 6282 break; 6283 case scSignExtend: 6284 TrueValue = TrueValue.sext(BitWidth); 6285 FalseValue = FalseValue.sext(BitWidth); 6286 break; 6287 } 6288 6289 // Re-apply the constant offset we peeled off earlier 6290 TrueValue += Offset; 6291 FalseValue += Offset; 6292 } 6293 6294 bool isRecognized() { return Condition != nullptr; } 6295 }; 6296 6297 SelectPattern StartPattern(*this, BitWidth, Start); 6298 if (!StartPattern.isRecognized()) 6299 return ConstantRange::getFull(BitWidth); 6300 6301 SelectPattern StepPattern(*this, BitWidth, Step); 6302 if (!StepPattern.isRecognized()) 6303 return ConstantRange::getFull(BitWidth); 6304 6305 if (StartPattern.Condition != StepPattern.Condition) { 6306 // We don't handle this case today; but we could, by considering four 6307 // possibilities below instead of two. I'm not sure if there are cases where 6308 // that will help over what getRange already does, though. 6309 return ConstantRange::getFull(BitWidth); 6310 } 6311 6312 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6313 // construct arbitrary general SCEV expressions here. This function is called 6314 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6315 // say) can end up caching a suboptimal value. 6316 6317 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6318 // C2352 and C2512 (otherwise it isn't needed). 6319 6320 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6321 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6322 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6323 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6324 6325 ConstantRange TrueRange = 6326 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6327 ConstantRange FalseRange = 6328 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6329 6330 return TrueRange.unionWith(FalseRange); 6331 } 6332 6333 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6334 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6335 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6336 6337 // Return early if there are no flags to propagate to the SCEV. 6338 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6339 if (BinOp->hasNoUnsignedWrap()) 6340 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6341 if (BinOp->hasNoSignedWrap()) 6342 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6343 if (Flags == SCEV::FlagAnyWrap) 6344 return SCEV::FlagAnyWrap; 6345 6346 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6347 } 6348 6349 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6350 // Here we check that I is in the header of the innermost loop containing I, 6351 // since we only deal with instructions in the loop header. The actual loop we 6352 // need to check later will come from an add recurrence, but getting that 6353 // requires computing the SCEV of the operands, which can be expensive. This 6354 // check we can do cheaply to rule out some cases early. 6355 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6356 if (InnermostContainingLoop == nullptr || 6357 InnermostContainingLoop->getHeader() != I->getParent()) 6358 return false; 6359 6360 // Only proceed if we can prove that I does not yield poison. 6361 if (!programUndefinedIfPoison(I)) 6362 return false; 6363 6364 // At this point we know that if I is executed, then it does not wrap 6365 // according to at least one of NSW or NUW. If I is not executed, then we do 6366 // not know if the calculation that I represents would wrap. Multiple 6367 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6368 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6369 // derived from other instructions that map to the same SCEV. We cannot make 6370 // that guarantee for cases where I is not executed. So we need to find the 6371 // loop that I is considered in relation to and prove that I is executed for 6372 // every iteration of that loop. That implies that the value that I 6373 // calculates does not wrap anywhere in the loop, so then we can apply the 6374 // flags to the SCEV. 6375 // 6376 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6377 // from different loops, so that we know which loop to prove that I is 6378 // executed in. 6379 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6380 // I could be an extractvalue from a call to an overflow intrinsic. 6381 // TODO: We can do better here in some cases. 6382 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6383 return false; 6384 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6385 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6386 bool AllOtherOpsLoopInvariant = true; 6387 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6388 ++OtherOpIndex) { 6389 if (OtherOpIndex != OpIndex) { 6390 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6391 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6392 AllOtherOpsLoopInvariant = false; 6393 break; 6394 } 6395 } 6396 } 6397 if (AllOtherOpsLoopInvariant && 6398 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6399 return true; 6400 } 6401 } 6402 return false; 6403 } 6404 6405 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6406 // If we know that \c I can never be poison period, then that's enough. 6407 if (isSCEVExprNeverPoison(I)) 6408 return true; 6409 6410 // For an add recurrence specifically, we assume that infinite loops without 6411 // side effects are undefined behavior, and then reason as follows: 6412 // 6413 // If the add recurrence is poison in any iteration, it is poison on all 6414 // future iterations (since incrementing poison yields poison). If the result 6415 // of the add recurrence is fed into the loop latch condition and the loop 6416 // does not contain any throws or exiting blocks other than the latch, we now 6417 // have the ability to "choose" whether the backedge is taken or not (by 6418 // choosing a sufficiently evil value for the poison feeding into the branch) 6419 // for every iteration including and after the one in which \p I first became 6420 // poison. There are two possibilities (let's call the iteration in which \p 6421 // I first became poison as K): 6422 // 6423 // 1. In the set of iterations including and after K, the loop body executes 6424 // no side effects. In this case executing the backege an infinte number 6425 // of times will yield undefined behavior. 6426 // 6427 // 2. In the set of iterations including and after K, the loop body executes 6428 // at least one side effect. In this case, that specific instance of side 6429 // effect is control dependent on poison, which also yields undefined 6430 // behavior. 6431 6432 auto *ExitingBB = L->getExitingBlock(); 6433 auto *LatchBB = L->getLoopLatch(); 6434 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6435 return false; 6436 6437 SmallPtrSet<const Instruction *, 16> Pushed; 6438 SmallVector<const Instruction *, 8> PoisonStack; 6439 6440 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6441 // things that are known to be poison under that assumption go on the 6442 // PoisonStack. 6443 Pushed.insert(I); 6444 PoisonStack.push_back(I); 6445 6446 bool LatchControlDependentOnPoison = false; 6447 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6448 const Instruction *Poison = PoisonStack.pop_back_val(); 6449 6450 for (auto *PoisonUser : Poison->users()) { 6451 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6452 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6453 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6454 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6455 assert(BI->isConditional() && "Only possibility!"); 6456 if (BI->getParent() == LatchBB) { 6457 LatchControlDependentOnPoison = true; 6458 break; 6459 } 6460 } 6461 } 6462 } 6463 6464 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6465 } 6466 6467 ScalarEvolution::LoopProperties 6468 ScalarEvolution::getLoopProperties(const Loop *L) { 6469 using LoopProperties = ScalarEvolution::LoopProperties; 6470 6471 auto Itr = LoopPropertiesCache.find(L); 6472 if (Itr == LoopPropertiesCache.end()) { 6473 auto HasSideEffects = [](Instruction *I) { 6474 if (auto *SI = dyn_cast<StoreInst>(I)) 6475 return !SI->isSimple(); 6476 6477 return I->mayHaveSideEffects(); 6478 }; 6479 6480 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6481 /*HasNoSideEffects*/ true}; 6482 6483 for (auto *BB : L->getBlocks()) 6484 for (auto &I : *BB) { 6485 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6486 LP.HasNoAbnormalExits = false; 6487 if (HasSideEffects(&I)) 6488 LP.HasNoSideEffects = false; 6489 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6490 break; // We're already as pessimistic as we can get. 6491 } 6492 6493 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6494 assert(InsertPair.second && "We just checked!"); 6495 Itr = InsertPair.first; 6496 } 6497 6498 return Itr->second; 6499 } 6500 6501 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6502 if (!isSCEVable(V->getType())) 6503 return getUnknown(V); 6504 6505 if (Instruction *I = dyn_cast<Instruction>(V)) { 6506 // Don't attempt to analyze instructions in blocks that aren't 6507 // reachable. Such instructions don't matter, and they aren't required 6508 // to obey basic rules for definitions dominating uses which this 6509 // analysis depends on. 6510 if (!DT.isReachableFromEntry(I->getParent())) 6511 return getUnknown(UndefValue::get(V->getType())); 6512 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6513 return getConstant(CI); 6514 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6515 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6516 else if (!isa<ConstantExpr>(V)) 6517 return getUnknown(V); 6518 6519 Operator *U = cast<Operator>(V); 6520 if (auto BO = MatchBinaryOp(U, DT)) { 6521 switch (BO->Opcode) { 6522 case Instruction::Add: { 6523 // The simple thing to do would be to just call getSCEV on both operands 6524 // and call getAddExpr with the result. However if we're looking at a 6525 // bunch of things all added together, this can be quite inefficient, 6526 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6527 // Instead, gather up all the operands and make a single getAddExpr call. 6528 // LLVM IR canonical form means we need only traverse the left operands. 6529 SmallVector<const SCEV *, 4> AddOps; 6530 do { 6531 if (BO->Op) { 6532 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6533 AddOps.push_back(OpSCEV); 6534 break; 6535 } 6536 6537 // If a NUW or NSW flag can be applied to the SCEV for this 6538 // addition, then compute the SCEV for this addition by itself 6539 // with a separate call to getAddExpr. We need to do that 6540 // instead of pushing the operands of the addition onto AddOps, 6541 // since the flags are only known to apply to this particular 6542 // addition - they may not apply to other additions that can be 6543 // formed with operands from AddOps. 6544 const SCEV *RHS = getSCEV(BO->RHS); 6545 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6546 if (Flags != SCEV::FlagAnyWrap) { 6547 const SCEV *LHS = getSCEV(BO->LHS); 6548 if (BO->Opcode == Instruction::Sub) 6549 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6550 else 6551 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6552 break; 6553 } 6554 } 6555 6556 if (BO->Opcode == Instruction::Sub) 6557 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6558 else 6559 AddOps.push_back(getSCEV(BO->RHS)); 6560 6561 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6562 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6563 NewBO->Opcode != Instruction::Sub)) { 6564 AddOps.push_back(getSCEV(BO->LHS)); 6565 break; 6566 } 6567 BO = NewBO; 6568 } while (true); 6569 6570 return getAddExpr(AddOps); 6571 } 6572 6573 case Instruction::Mul: { 6574 SmallVector<const SCEV *, 4> MulOps; 6575 do { 6576 if (BO->Op) { 6577 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6578 MulOps.push_back(OpSCEV); 6579 break; 6580 } 6581 6582 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6583 if (Flags != SCEV::FlagAnyWrap) { 6584 MulOps.push_back( 6585 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6586 break; 6587 } 6588 } 6589 6590 MulOps.push_back(getSCEV(BO->RHS)); 6591 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6592 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6593 MulOps.push_back(getSCEV(BO->LHS)); 6594 break; 6595 } 6596 BO = NewBO; 6597 } while (true); 6598 6599 return getMulExpr(MulOps); 6600 } 6601 case Instruction::UDiv: 6602 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6603 case Instruction::URem: 6604 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6605 case Instruction::Sub: { 6606 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6607 if (BO->Op) 6608 Flags = getNoWrapFlagsFromUB(BO->Op); 6609 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6610 } 6611 case Instruction::And: 6612 // For an expression like x&255 that merely masks off the high bits, 6613 // use zext(trunc(x)) as the SCEV expression. 6614 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6615 if (CI->isZero()) 6616 return getSCEV(BO->RHS); 6617 if (CI->isMinusOne()) 6618 return getSCEV(BO->LHS); 6619 const APInt &A = CI->getValue(); 6620 6621 // Instcombine's ShrinkDemandedConstant may strip bits out of 6622 // constants, obscuring what would otherwise be a low-bits mask. 6623 // Use computeKnownBits to compute what ShrinkDemandedConstant 6624 // knew about to reconstruct a low-bits mask value. 6625 unsigned LZ = A.countLeadingZeros(); 6626 unsigned TZ = A.countTrailingZeros(); 6627 unsigned BitWidth = A.getBitWidth(); 6628 KnownBits Known(BitWidth); 6629 computeKnownBits(BO->LHS, Known, getDataLayout(), 6630 0, &AC, nullptr, &DT); 6631 6632 APInt EffectiveMask = 6633 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6634 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6635 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6636 const SCEV *LHS = getSCEV(BO->LHS); 6637 const SCEV *ShiftedLHS = nullptr; 6638 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6639 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6640 // For an expression like (x * 8) & 8, simplify the multiply. 6641 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6642 unsigned GCD = std::min(MulZeros, TZ); 6643 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6644 SmallVector<const SCEV*, 4> MulOps; 6645 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6646 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6647 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6648 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6649 } 6650 } 6651 if (!ShiftedLHS) 6652 ShiftedLHS = getUDivExpr(LHS, MulCount); 6653 return getMulExpr( 6654 getZeroExtendExpr( 6655 getTruncateExpr(ShiftedLHS, 6656 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6657 BO->LHS->getType()), 6658 MulCount); 6659 } 6660 } 6661 break; 6662 6663 case Instruction::Or: 6664 // If the RHS of the Or is a constant, we may have something like: 6665 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6666 // optimizations will transparently handle this case. 6667 // 6668 // In order for this transformation to be safe, the LHS must be of the 6669 // form X*(2^n) and the Or constant must be less than 2^n. 6670 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6671 const SCEV *LHS = getSCEV(BO->LHS); 6672 const APInt &CIVal = CI->getValue(); 6673 if (GetMinTrailingZeros(LHS) >= 6674 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6675 // Build a plain add SCEV. 6676 return getAddExpr(LHS, getSCEV(CI), 6677 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6678 } 6679 } 6680 break; 6681 6682 case Instruction::Xor: 6683 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6684 // If the RHS of xor is -1, then this is a not operation. 6685 if (CI->isMinusOne()) 6686 return getNotSCEV(getSCEV(BO->LHS)); 6687 6688 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6689 // This is a variant of the check for xor with -1, and it handles 6690 // the case where instcombine has trimmed non-demanded bits out 6691 // of an xor with -1. 6692 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6693 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6694 if (LBO->getOpcode() == Instruction::And && 6695 LCI->getValue() == CI->getValue()) 6696 if (const SCEVZeroExtendExpr *Z = 6697 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6698 Type *UTy = BO->LHS->getType(); 6699 const SCEV *Z0 = Z->getOperand(); 6700 Type *Z0Ty = Z0->getType(); 6701 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6702 6703 // If C is a low-bits mask, the zero extend is serving to 6704 // mask off the high bits. Complement the operand and 6705 // re-apply the zext. 6706 if (CI->getValue().isMask(Z0TySize)) 6707 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6708 6709 // If C is a single bit, it may be in the sign-bit position 6710 // before the zero-extend. In this case, represent the xor 6711 // using an add, which is equivalent, and re-apply the zext. 6712 APInt Trunc = CI->getValue().trunc(Z0TySize); 6713 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6714 Trunc.isSignMask()) 6715 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6716 UTy); 6717 } 6718 } 6719 break; 6720 6721 case Instruction::Shl: 6722 // Turn shift left of a constant amount into a multiply. 6723 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6724 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6725 6726 // If the shift count is not less than the bitwidth, the result of 6727 // the shift is undefined. Don't try to analyze it, because the 6728 // resolution chosen here may differ from the resolution chosen in 6729 // other parts of the compiler. 6730 if (SA->getValue().uge(BitWidth)) 6731 break; 6732 6733 // We can safely preserve the nuw flag in all cases. It's also safe to 6734 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6735 // requires special handling. It can be preserved as long as we're not 6736 // left shifting by bitwidth - 1. 6737 auto Flags = SCEV::FlagAnyWrap; 6738 if (BO->Op) { 6739 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6740 if ((MulFlags & SCEV::FlagNSW) && 6741 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6742 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6743 if (MulFlags & SCEV::FlagNUW) 6744 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6745 } 6746 6747 Constant *X = ConstantInt::get( 6748 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6749 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6750 } 6751 break; 6752 6753 case Instruction::AShr: { 6754 // AShr X, C, where C is a constant. 6755 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6756 if (!CI) 6757 break; 6758 6759 Type *OuterTy = BO->LHS->getType(); 6760 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6761 // If the shift count is not less than the bitwidth, the result of 6762 // the shift is undefined. Don't try to analyze it, because the 6763 // resolution chosen here may differ from the resolution chosen in 6764 // other parts of the compiler. 6765 if (CI->getValue().uge(BitWidth)) 6766 break; 6767 6768 if (CI->isZero()) 6769 return getSCEV(BO->LHS); // shift by zero --> noop 6770 6771 uint64_t AShrAmt = CI->getZExtValue(); 6772 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6773 6774 Operator *L = dyn_cast<Operator>(BO->LHS); 6775 if (L && L->getOpcode() == Instruction::Shl) { 6776 // X = Shl A, n 6777 // Y = AShr X, m 6778 // Both n and m are constant. 6779 6780 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6781 if (L->getOperand(1) == BO->RHS) 6782 // For a two-shift sext-inreg, i.e. n = m, 6783 // use sext(trunc(x)) as the SCEV expression. 6784 return getSignExtendExpr( 6785 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6786 6787 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6788 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6789 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6790 if (ShlAmt > AShrAmt) { 6791 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6792 // expression. We already checked that ShlAmt < BitWidth, so 6793 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6794 // ShlAmt - AShrAmt < Amt. 6795 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6796 ShlAmt - AShrAmt); 6797 return getSignExtendExpr( 6798 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6799 getConstant(Mul)), OuterTy); 6800 } 6801 } 6802 } 6803 break; 6804 } 6805 } 6806 } 6807 6808 switch (U->getOpcode()) { 6809 case Instruction::Trunc: 6810 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6811 6812 case Instruction::ZExt: 6813 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6814 6815 case Instruction::SExt: 6816 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6817 // The NSW flag of a subtract does not always survive the conversion to 6818 // A + (-1)*B. By pushing sign extension onto its operands we are much 6819 // more likely to preserve NSW and allow later AddRec optimisations. 6820 // 6821 // NOTE: This is effectively duplicating this logic from getSignExtend: 6822 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6823 // but by that point the NSW information has potentially been lost. 6824 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6825 Type *Ty = U->getType(); 6826 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6827 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6828 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6829 } 6830 } 6831 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6832 6833 case Instruction::BitCast: 6834 // BitCasts are no-op casts so we just eliminate the cast. 6835 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6836 return getSCEV(U->getOperand(0)); 6837 break; 6838 6839 case Instruction::PtrToInt: { 6840 // Pointer to integer cast is straight-forward, so do model it. 6841 const SCEV *Op = getSCEV(U->getOperand(0)); 6842 Type *DstIntTy = U->getType(); 6843 // But only if effective SCEV (integer) type is wide enough to represent 6844 // all possible pointer values. 6845 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 6846 if (isa<SCEVCouldNotCompute>(IntOp)) 6847 return getUnknown(V); 6848 return IntOp; 6849 } 6850 case Instruction::IntToPtr: 6851 // Just don't deal with inttoptr casts. 6852 return getUnknown(V); 6853 6854 case Instruction::SDiv: 6855 // If both operands are non-negative, this is just an udiv. 6856 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6857 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6858 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6859 break; 6860 6861 case Instruction::SRem: 6862 // If both operands are non-negative, this is just an urem. 6863 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6864 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6865 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6866 break; 6867 6868 case Instruction::GetElementPtr: 6869 return createNodeForGEP(cast<GEPOperator>(U)); 6870 6871 case Instruction::PHI: 6872 return createNodeForPHI(cast<PHINode>(U)); 6873 6874 case Instruction::Select: 6875 // U can also be a select constant expr, which let fall through. Since 6876 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6877 // constant expressions cannot have instructions as operands, we'd have 6878 // returned getUnknown for a select constant expressions anyway. 6879 if (isa<Instruction>(U)) 6880 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6881 U->getOperand(1), U->getOperand(2)); 6882 break; 6883 6884 case Instruction::Call: 6885 case Instruction::Invoke: 6886 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 6887 return getSCEV(RV); 6888 6889 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 6890 switch (II->getIntrinsicID()) { 6891 case Intrinsic::abs: 6892 return getAbsExpr( 6893 getSCEV(II->getArgOperand(0)), 6894 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 6895 case Intrinsic::umax: 6896 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 6897 getSCEV(II->getArgOperand(1))); 6898 case Intrinsic::umin: 6899 return getUMinExpr(getSCEV(II->getArgOperand(0)), 6900 getSCEV(II->getArgOperand(1))); 6901 case Intrinsic::smax: 6902 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 6903 getSCEV(II->getArgOperand(1))); 6904 case Intrinsic::smin: 6905 return getSMinExpr(getSCEV(II->getArgOperand(0)), 6906 getSCEV(II->getArgOperand(1))); 6907 case Intrinsic::usub_sat: { 6908 const SCEV *X = getSCEV(II->getArgOperand(0)); 6909 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6910 const SCEV *ClampedY = getUMinExpr(X, Y); 6911 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 6912 } 6913 case Intrinsic::uadd_sat: { 6914 const SCEV *X = getSCEV(II->getArgOperand(0)); 6915 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6916 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 6917 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 6918 } 6919 case Intrinsic::start_loop_iterations: 6920 // A start_loop_iterations is just equivalent to the first operand for 6921 // SCEV purposes. 6922 return getSCEV(II->getArgOperand(0)); 6923 default: 6924 break; 6925 } 6926 } 6927 break; 6928 } 6929 6930 return getUnknown(V); 6931 } 6932 6933 //===----------------------------------------------------------------------===// 6934 // Iteration Count Computation Code 6935 // 6936 6937 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) { 6938 // Get the trip count from the BE count by adding 1. Overflow, results 6939 // in zero which means "unknown". 6940 return getAddExpr(ExitCount, getOne(ExitCount->getType())); 6941 } 6942 6943 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6944 if (!ExitCount) 6945 return 0; 6946 6947 ConstantInt *ExitConst = ExitCount->getValue(); 6948 6949 // Guard against huge trip counts. 6950 if (ExitConst->getValue().getActiveBits() > 32) 6951 return 0; 6952 6953 // In case of integer overflow, this returns 0, which is correct. 6954 return ((unsigned)ExitConst->getZExtValue()) + 1; 6955 } 6956 6957 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6958 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 6959 return getConstantTripCount(ExitCount); 6960 } 6961 6962 unsigned 6963 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6964 const BasicBlock *ExitingBlock) { 6965 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6966 assert(L->isLoopExiting(ExitingBlock) && 6967 "Exiting block must actually branch out of the loop!"); 6968 const SCEVConstant *ExitCount = 6969 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6970 return getConstantTripCount(ExitCount); 6971 } 6972 6973 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6974 const auto *MaxExitCount = 6975 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6976 return getConstantTripCount(MaxExitCount); 6977 } 6978 6979 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6980 SmallVector<BasicBlock *, 8> ExitingBlocks; 6981 L->getExitingBlocks(ExitingBlocks); 6982 6983 Optional<unsigned> Res = None; 6984 for (auto *ExitingBB : ExitingBlocks) { 6985 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 6986 if (!Res) 6987 Res = Multiple; 6988 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 6989 } 6990 return Res.getValueOr(1); 6991 } 6992 6993 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6994 const SCEV *ExitCount) { 6995 if (ExitCount == getCouldNotCompute()) 6996 return 1; 6997 6998 // Get the trip count 6999 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7000 7001 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7002 if (!TC) 7003 // Attempt to factor more general cases. Returns the greatest power of 7004 // two divisor. If overflow happens, the trip count expression is still 7005 // divisible by the greatest power of 2 divisor returned. 7006 return 1U << std::min((uint32_t)31, 7007 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7008 7009 ConstantInt *Result = TC->getValue(); 7010 7011 // Guard against huge trip counts (this requires checking 7012 // for zero to handle the case where the trip count == -1 and the 7013 // addition wraps). 7014 if (!Result || Result->getValue().getActiveBits() > 32 || 7015 Result->getValue().getActiveBits() == 0) 7016 return 1; 7017 7018 return (unsigned)Result->getZExtValue(); 7019 } 7020 7021 /// Returns the largest constant divisor of the trip count of this loop as a 7022 /// normal unsigned value, if possible. This means that the actual trip count is 7023 /// always a multiple of the returned value (don't forget the trip count could 7024 /// very well be zero as well!). 7025 /// 7026 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7027 /// multiple of a constant (which is also the case if the trip count is simply 7028 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7029 /// if the trip count is very large (>= 2^32). 7030 /// 7031 /// As explained in the comments for getSmallConstantTripCount, this assumes 7032 /// that control exits the loop via ExitingBlock. 7033 unsigned 7034 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7035 const BasicBlock *ExitingBlock) { 7036 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7037 assert(L->isLoopExiting(ExitingBlock) && 7038 "Exiting block must actually branch out of the loop!"); 7039 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7040 return getSmallConstantTripMultiple(L, ExitCount); 7041 } 7042 7043 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7044 const BasicBlock *ExitingBlock, 7045 ExitCountKind Kind) { 7046 switch (Kind) { 7047 case Exact: 7048 case SymbolicMaximum: 7049 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7050 case ConstantMaximum: 7051 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7052 }; 7053 llvm_unreachable("Invalid ExitCountKind!"); 7054 } 7055 7056 const SCEV * 7057 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7058 SCEVUnionPredicate &Preds) { 7059 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7060 } 7061 7062 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7063 ExitCountKind Kind) { 7064 switch (Kind) { 7065 case Exact: 7066 return getBackedgeTakenInfo(L).getExact(L, this); 7067 case ConstantMaximum: 7068 return getBackedgeTakenInfo(L).getConstantMax(this); 7069 case SymbolicMaximum: 7070 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7071 }; 7072 llvm_unreachable("Invalid ExitCountKind!"); 7073 } 7074 7075 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7076 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7077 } 7078 7079 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7080 static void 7081 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 7082 BasicBlock *Header = L->getHeader(); 7083 7084 // Push all Loop-header PHIs onto the Worklist stack. 7085 for (PHINode &PN : Header->phis()) 7086 Worklist.push_back(&PN); 7087 } 7088 7089 const ScalarEvolution::BackedgeTakenInfo & 7090 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7091 auto &BTI = getBackedgeTakenInfo(L); 7092 if (BTI.hasFullInfo()) 7093 return BTI; 7094 7095 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7096 7097 if (!Pair.second) 7098 return Pair.first->second; 7099 7100 BackedgeTakenInfo Result = 7101 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7102 7103 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7104 } 7105 7106 ScalarEvolution::BackedgeTakenInfo & 7107 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7108 // Initially insert an invalid entry for this loop. If the insertion 7109 // succeeds, proceed to actually compute a backedge-taken count and 7110 // update the value. The temporary CouldNotCompute value tells SCEV 7111 // code elsewhere that it shouldn't attempt to request a new 7112 // backedge-taken count, which could result in infinite recursion. 7113 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7114 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7115 if (!Pair.second) 7116 return Pair.first->second; 7117 7118 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7119 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7120 // must be cleared in this scope. 7121 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7122 7123 // In product build, there are no usage of statistic. 7124 (void)NumTripCountsComputed; 7125 (void)NumTripCountsNotComputed; 7126 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7127 const SCEV *BEExact = Result.getExact(L, this); 7128 if (BEExact != getCouldNotCompute()) { 7129 assert(isLoopInvariant(BEExact, L) && 7130 isLoopInvariant(Result.getConstantMax(this), L) && 7131 "Computed backedge-taken count isn't loop invariant for loop!"); 7132 ++NumTripCountsComputed; 7133 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7134 isa<PHINode>(L->getHeader()->begin())) { 7135 // Only count loops that have phi nodes as not being computable. 7136 ++NumTripCountsNotComputed; 7137 } 7138 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7139 7140 // Now that we know more about the trip count for this loop, forget any 7141 // existing SCEV values for PHI nodes in this loop since they are only 7142 // conservative estimates made without the benefit of trip count 7143 // information. This is similar to the code in forgetLoop, except that 7144 // it handles SCEVUnknown PHI nodes specially. 7145 if (Result.hasAnyInfo()) { 7146 SmallVector<Instruction *, 16> Worklist; 7147 PushLoopPHIs(L, Worklist); 7148 7149 SmallPtrSet<Instruction *, 8> Discovered; 7150 while (!Worklist.empty()) { 7151 Instruction *I = Worklist.pop_back_val(); 7152 7153 ValueExprMapType::iterator It = 7154 ValueExprMap.find_as(static_cast<Value *>(I)); 7155 if (It != ValueExprMap.end()) { 7156 const SCEV *Old = It->second; 7157 7158 // SCEVUnknown for a PHI either means that it has an unrecognized 7159 // structure, or it's a PHI that's in the progress of being computed 7160 // by createNodeForPHI. In the former case, additional loop trip 7161 // count information isn't going to change anything. In the later 7162 // case, createNodeForPHI will perform the necessary updates on its 7163 // own when it gets to that point. 7164 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 7165 eraseValueFromMap(It->first); 7166 forgetMemoizedResults(Old); 7167 } 7168 if (PHINode *PN = dyn_cast<PHINode>(I)) 7169 ConstantEvolutionLoopExitValue.erase(PN); 7170 } 7171 7172 // Since we don't need to invalidate anything for correctness and we're 7173 // only invalidating to make SCEV's results more precise, we get to stop 7174 // early to avoid invalidating too much. This is especially important in 7175 // cases like: 7176 // 7177 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 7178 // loop0: 7179 // %pn0 = phi 7180 // ... 7181 // loop1: 7182 // %pn1 = phi 7183 // ... 7184 // 7185 // where both loop0 and loop1's backedge taken count uses the SCEV 7186 // expression for %v. If we don't have the early stop below then in cases 7187 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 7188 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 7189 // count for loop1, effectively nullifying SCEV's trip count cache. 7190 for (auto *U : I->users()) 7191 if (auto *I = dyn_cast<Instruction>(U)) { 7192 auto *LoopForUser = LI.getLoopFor(I->getParent()); 7193 if (LoopForUser && L->contains(LoopForUser) && 7194 Discovered.insert(I).second) 7195 Worklist.push_back(I); 7196 } 7197 } 7198 } 7199 7200 // Re-lookup the insert position, since the call to 7201 // computeBackedgeTakenCount above could result in a 7202 // recusive call to getBackedgeTakenInfo (on a different 7203 // loop), which would invalidate the iterator computed 7204 // earlier. 7205 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7206 } 7207 7208 void ScalarEvolution::forgetAllLoops() { 7209 // This method is intended to forget all info about loops. It should 7210 // invalidate caches as if the following happened: 7211 // - The trip counts of all loops have changed arbitrarily 7212 // - Every llvm::Value has been updated in place to produce a different 7213 // result. 7214 BackedgeTakenCounts.clear(); 7215 PredicatedBackedgeTakenCounts.clear(); 7216 LoopPropertiesCache.clear(); 7217 ConstantEvolutionLoopExitValue.clear(); 7218 ValueExprMap.clear(); 7219 ValuesAtScopes.clear(); 7220 LoopDispositions.clear(); 7221 BlockDispositions.clear(); 7222 UnsignedRanges.clear(); 7223 SignedRanges.clear(); 7224 ExprValueMap.clear(); 7225 HasRecMap.clear(); 7226 MinTrailingZerosCache.clear(); 7227 PredicatedSCEVRewrites.clear(); 7228 } 7229 7230 void ScalarEvolution::forgetLoop(const Loop *L) { 7231 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7232 SmallVector<Instruction *, 32> Worklist; 7233 SmallPtrSet<Instruction *, 16> Visited; 7234 7235 // Iterate over all the loops and sub-loops to drop SCEV information. 7236 while (!LoopWorklist.empty()) { 7237 auto *CurrL = LoopWorklist.pop_back_val(); 7238 7239 // Drop any stored trip count value. 7240 BackedgeTakenCounts.erase(CurrL); 7241 PredicatedBackedgeTakenCounts.erase(CurrL); 7242 7243 // Drop information about predicated SCEV rewrites for this loop. 7244 for (auto I = PredicatedSCEVRewrites.begin(); 7245 I != PredicatedSCEVRewrites.end();) { 7246 std::pair<const SCEV *, const Loop *> Entry = I->first; 7247 if (Entry.second == CurrL) 7248 PredicatedSCEVRewrites.erase(I++); 7249 else 7250 ++I; 7251 } 7252 7253 auto LoopUsersItr = LoopUsers.find(CurrL); 7254 if (LoopUsersItr != LoopUsers.end()) { 7255 for (auto *S : LoopUsersItr->second) 7256 forgetMemoizedResults(S); 7257 LoopUsers.erase(LoopUsersItr); 7258 } 7259 7260 // Drop information about expressions based on loop-header PHIs. 7261 PushLoopPHIs(CurrL, Worklist); 7262 7263 while (!Worklist.empty()) { 7264 Instruction *I = Worklist.pop_back_val(); 7265 if (!Visited.insert(I).second) 7266 continue; 7267 7268 ValueExprMapType::iterator It = 7269 ValueExprMap.find_as(static_cast<Value *>(I)); 7270 if (It != ValueExprMap.end()) { 7271 eraseValueFromMap(It->first); 7272 forgetMemoizedResults(It->second); 7273 if (PHINode *PN = dyn_cast<PHINode>(I)) 7274 ConstantEvolutionLoopExitValue.erase(PN); 7275 } 7276 7277 PushDefUseChildren(I, Worklist); 7278 } 7279 7280 LoopPropertiesCache.erase(CurrL); 7281 // Forget all contained loops too, to avoid dangling entries in the 7282 // ValuesAtScopes map. 7283 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7284 } 7285 } 7286 7287 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7288 while (Loop *Parent = L->getParentLoop()) 7289 L = Parent; 7290 forgetLoop(L); 7291 } 7292 7293 void ScalarEvolution::forgetValue(Value *V) { 7294 Instruction *I = dyn_cast<Instruction>(V); 7295 if (!I) return; 7296 7297 // Drop information about expressions based on loop-header PHIs. 7298 SmallVector<Instruction *, 16> Worklist; 7299 Worklist.push_back(I); 7300 7301 SmallPtrSet<Instruction *, 8> Visited; 7302 while (!Worklist.empty()) { 7303 I = Worklist.pop_back_val(); 7304 if (!Visited.insert(I).second) 7305 continue; 7306 7307 ValueExprMapType::iterator It = 7308 ValueExprMap.find_as(static_cast<Value *>(I)); 7309 if (It != ValueExprMap.end()) { 7310 eraseValueFromMap(It->first); 7311 forgetMemoizedResults(It->second); 7312 if (PHINode *PN = dyn_cast<PHINode>(I)) 7313 ConstantEvolutionLoopExitValue.erase(PN); 7314 } 7315 7316 PushDefUseChildren(I, Worklist); 7317 } 7318 } 7319 7320 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7321 LoopDispositions.clear(); 7322 } 7323 7324 /// Get the exact loop backedge taken count considering all loop exits. A 7325 /// computable result can only be returned for loops with all exiting blocks 7326 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7327 /// is never skipped. This is a valid assumption as long as the loop exits via 7328 /// that test. For precise results, it is the caller's responsibility to specify 7329 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7330 const SCEV * 7331 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7332 SCEVUnionPredicate *Preds) const { 7333 // If any exits were not computable, the loop is not computable. 7334 if (!isComplete() || ExitNotTaken.empty()) 7335 return SE->getCouldNotCompute(); 7336 7337 const BasicBlock *Latch = L->getLoopLatch(); 7338 // All exiting blocks we have collected must dominate the only backedge. 7339 if (!Latch) 7340 return SE->getCouldNotCompute(); 7341 7342 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7343 // count is simply a minimum out of all these calculated exit counts. 7344 SmallVector<const SCEV *, 2> Ops; 7345 for (auto &ENT : ExitNotTaken) { 7346 const SCEV *BECount = ENT.ExactNotTaken; 7347 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7348 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7349 "We should only have known counts for exiting blocks that dominate " 7350 "latch!"); 7351 7352 Ops.push_back(BECount); 7353 7354 if (Preds && !ENT.hasAlwaysTruePredicate()) 7355 Preds->add(ENT.Predicate.get()); 7356 7357 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7358 "Predicate should be always true!"); 7359 } 7360 7361 return SE->getUMinFromMismatchedTypes(Ops); 7362 } 7363 7364 /// Get the exact not taken count for this loop exit. 7365 const SCEV * 7366 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7367 ScalarEvolution *SE) const { 7368 for (auto &ENT : ExitNotTaken) 7369 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7370 return ENT.ExactNotTaken; 7371 7372 return SE->getCouldNotCompute(); 7373 } 7374 7375 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7376 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7377 for (auto &ENT : ExitNotTaken) 7378 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7379 return ENT.MaxNotTaken; 7380 7381 return SE->getCouldNotCompute(); 7382 } 7383 7384 /// getConstantMax - Get the constant max backedge taken count for the loop. 7385 const SCEV * 7386 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7387 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7388 return !ENT.hasAlwaysTruePredicate(); 7389 }; 7390 7391 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax()) 7392 return SE->getCouldNotCompute(); 7393 7394 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7395 isa<SCEVConstant>(getConstantMax())) && 7396 "No point in having a non-constant max backedge taken count!"); 7397 return getConstantMax(); 7398 } 7399 7400 const SCEV * 7401 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 7402 ScalarEvolution *SE) { 7403 if (!SymbolicMax) 7404 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 7405 return SymbolicMax; 7406 } 7407 7408 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 7409 ScalarEvolution *SE) const { 7410 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7411 return !ENT.hasAlwaysTruePredicate(); 7412 }; 7413 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7414 } 7415 7416 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const { 7417 return Operands.contains(S); 7418 } 7419 7420 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7421 : ExactNotTaken(E), MaxNotTaken(E) { 7422 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7423 isa<SCEVConstant>(MaxNotTaken)) && 7424 "No point in having a non-constant max backedge taken count!"); 7425 } 7426 7427 ScalarEvolution::ExitLimit::ExitLimit( 7428 const SCEV *E, const SCEV *M, bool MaxOrZero, 7429 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7430 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7431 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7432 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7433 "Exact is not allowed to be less precise than Max"); 7434 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7435 isa<SCEVConstant>(MaxNotTaken)) && 7436 "No point in having a non-constant max backedge taken count!"); 7437 for (auto *PredSet : PredSetList) 7438 for (auto *P : *PredSet) 7439 addPredicate(P); 7440 } 7441 7442 ScalarEvolution::ExitLimit::ExitLimit( 7443 const SCEV *E, const SCEV *M, bool MaxOrZero, 7444 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7445 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7446 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7447 isa<SCEVConstant>(MaxNotTaken)) && 7448 "No point in having a non-constant max backedge taken count!"); 7449 } 7450 7451 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7452 bool MaxOrZero) 7453 : ExitLimit(E, M, MaxOrZero, None) { 7454 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7455 isa<SCEVConstant>(MaxNotTaken)) && 7456 "No point in having a non-constant max backedge taken count!"); 7457 } 7458 7459 class SCEVRecordOperands { 7460 SmallPtrSetImpl<const SCEV *> &Operands; 7461 7462 public: 7463 SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands) 7464 : Operands(Operands) {} 7465 bool follow(const SCEV *S) { 7466 Operands.insert(S); 7467 return true; 7468 } 7469 bool isDone() { return false; } 7470 }; 7471 7472 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7473 /// computable exit into a persistent ExitNotTakenInfo array. 7474 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7475 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 7476 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 7477 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 7478 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7479 7480 ExitNotTaken.reserve(ExitCounts.size()); 7481 std::transform( 7482 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7483 [&](const EdgeExitInfo &EEI) { 7484 BasicBlock *ExitBB = EEI.first; 7485 const ExitLimit &EL = EEI.second; 7486 if (EL.Predicates.empty()) 7487 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7488 nullptr); 7489 7490 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7491 for (auto *Pred : EL.Predicates) 7492 Predicate->add(Pred); 7493 7494 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7495 std::move(Predicate)); 7496 }); 7497 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 7498 isa<SCEVConstant>(ConstantMax)) && 7499 "No point in having a non-constant max backedge taken count!"); 7500 7501 SCEVRecordOperands RecordOperands(Operands); 7502 SCEVTraversal<SCEVRecordOperands> ST(RecordOperands); 7503 if (!isa<SCEVCouldNotCompute>(ConstantMax)) 7504 ST.visitAll(ConstantMax); 7505 for (auto &ENT : ExitNotTaken) 7506 if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken)) 7507 ST.visitAll(ENT.ExactNotTaken); 7508 } 7509 7510 /// Compute the number of times the backedge of the specified loop will execute. 7511 ScalarEvolution::BackedgeTakenInfo 7512 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7513 bool AllowPredicates) { 7514 SmallVector<BasicBlock *, 8> ExitingBlocks; 7515 L->getExitingBlocks(ExitingBlocks); 7516 7517 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7518 7519 SmallVector<EdgeExitInfo, 4> ExitCounts; 7520 bool CouldComputeBECount = true; 7521 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7522 const SCEV *MustExitMaxBECount = nullptr; 7523 const SCEV *MayExitMaxBECount = nullptr; 7524 bool MustExitMaxOrZero = false; 7525 7526 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7527 // and compute maxBECount. 7528 // Do a union of all the predicates here. 7529 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7530 BasicBlock *ExitBB = ExitingBlocks[i]; 7531 7532 // We canonicalize untaken exits to br (constant), ignore them so that 7533 // proving an exit untaken doesn't negatively impact our ability to reason 7534 // about the loop as whole. 7535 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7536 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7537 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7538 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7539 continue; 7540 } 7541 7542 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7543 7544 assert((AllowPredicates || EL.Predicates.empty()) && 7545 "Predicated exit limit when predicates are not allowed!"); 7546 7547 // 1. For each exit that can be computed, add an entry to ExitCounts. 7548 // CouldComputeBECount is true only if all exits can be computed. 7549 if (EL.ExactNotTaken == getCouldNotCompute()) 7550 // We couldn't compute an exact value for this exit, so 7551 // we won't be able to compute an exact value for the loop. 7552 CouldComputeBECount = false; 7553 else 7554 ExitCounts.emplace_back(ExitBB, EL); 7555 7556 // 2. Derive the loop's MaxBECount from each exit's max number of 7557 // non-exiting iterations. Partition the loop exits into two kinds: 7558 // LoopMustExits and LoopMayExits. 7559 // 7560 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7561 // is a LoopMayExit. If any computable LoopMustExit is found, then 7562 // MaxBECount is the minimum EL.MaxNotTaken of computable 7563 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7564 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7565 // computable EL.MaxNotTaken. 7566 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7567 DT.dominates(ExitBB, Latch)) { 7568 if (!MustExitMaxBECount) { 7569 MustExitMaxBECount = EL.MaxNotTaken; 7570 MustExitMaxOrZero = EL.MaxOrZero; 7571 } else { 7572 MustExitMaxBECount = 7573 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7574 } 7575 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7576 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7577 MayExitMaxBECount = EL.MaxNotTaken; 7578 else { 7579 MayExitMaxBECount = 7580 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7581 } 7582 } 7583 } 7584 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7585 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7586 // The loop backedge will be taken the maximum or zero times if there's 7587 // a single exit that must be taken the maximum or zero times. 7588 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7589 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7590 MaxBECount, MaxOrZero); 7591 } 7592 7593 ScalarEvolution::ExitLimit 7594 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7595 bool AllowPredicates) { 7596 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7597 // If our exiting block does not dominate the latch, then its connection with 7598 // loop's exit limit may be far from trivial. 7599 const BasicBlock *Latch = L->getLoopLatch(); 7600 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7601 return getCouldNotCompute(); 7602 7603 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7604 Instruction *Term = ExitingBlock->getTerminator(); 7605 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7606 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7607 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7608 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7609 "It should have one successor in loop and one exit block!"); 7610 // Proceed to the next level to examine the exit condition expression. 7611 return computeExitLimitFromCond( 7612 L, BI->getCondition(), ExitIfTrue, 7613 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7614 } 7615 7616 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7617 // For switch, make sure that there is a single exit from the loop. 7618 BasicBlock *Exit = nullptr; 7619 for (auto *SBB : successors(ExitingBlock)) 7620 if (!L->contains(SBB)) { 7621 if (Exit) // Multiple exit successors. 7622 return getCouldNotCompute(); 7623 Exit = SBB; 7624 } 7625 assert(Exit && "Exiting block must have at least one exit"); 7626 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7627 /*ControlsExit=*/IsOnlyExit); 7628 } 7629 7630 return getCouldNotCompute(); 7631 } 7632 7633 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7634 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7635 bool ControlsExit, bool AllowPredicates) { 7636 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7637 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7638 ControlsExit, AllowPredicates); 7639 } 7640 7641 Optional<ScalarEvolution::ExitLimit> 7642 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7643 bool ExitIfTrue, bool ControlsExit, 7644 bool AllowPredicates) { 7645 (void)this->L; 7646 (void)this->ExitIfTrue; 7647 (void)this->AllowPredicates; 7648 7649 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7650 this->AllowPredicates == AllowPredicates && 7651 "Variance in assumed invariant key components!"); 7652 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7653 if (Itr == TripCountMap.end()) 7654 return None; 7655 return Itr->second; 7656 } 7657 7658 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7659 bool ExitIfTrue, 7660 bool ControlsExit, 7661 bool AllowPredicates, 7662 const ExitLimit &EL) { 7663 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7664 this->AllowPredicates == AllowPredicates && 7665 "Variance in assumed invariant key components!"); 7666 7667 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7668 assert(InsertResult.second && "Expected successful insertion!"); 7669 (void)InsertResult; 7670 (void)ExitIfTrue; 7671 } 7672 7673 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7674 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7675 bool ControlsExit, bool AllowPredicates) { 7676 7677 if (auto MaybeEL = 7678 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7679 return *MaybeEL; 7680 7681 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7682 ControlsExit, AllowPredicates); 7683 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7684 return EL; 7685 } 7686 7687 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7688 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7689 bool ControlsExit, bool AllowPredicates) { 7690 // Handle BinOp conditions (And, Or). 7691 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 7692 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7693 return *LimitFromBinOp; 7694 7695 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7696 // Proceed to the next level to examine the icmp. 7697 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7698 ExitLimit EL = 7699 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7700 if (EL.hasFullInfo() || !AllowPredicates) 7701 return EL; 7702 7703 // Try again, but use SCEV predicates this time. 7704 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7705 /*AllowPredicates=*/true); 7706 } 7707 7708 // Check for a constant condition. These are normally stripped out by 7709 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7710 // preserve the CFG and is temporarily leaving constant conditions 7711 // in place. 7712 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7713 if (ExitIfTrue == !CI->getZExtValue()) 7714 // The backedge is always taken. 7715 return getCouldNotCompute(); 7716 else 7717 // The backedge is never taken. 7718 return getZero(CI->getType()); 7719 } 7720 7721 // If it's not an integer or pointer comparison then compute it the hard way. 7722 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7723 } 7724 7725 Optional<ScalarEvolution::ExitLimit> 7726 ScalarEvolution::computeExitLimitFromCondFromBinOp( 7727 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7728 bool ControlsExit, bool AllowPredicates) { 7729 // Check if the controlling expression for this loop is an And or Or. 7730 Value *Op0, *Op1; 7731 bool IsAnd = false; 7732 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 7733 IsAnd = true; 7734 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 7735 IsAnd = false; 7736 else 7737 return None; 7738 7739 // EitherMayExit is true in these two cases: 7740 // br (and Op0 Op1), loop, exit 7741 // br (or Op0 Op1), exit, loop 7742 bool EitherMayExit = IsAnd ^ ExitIfTrue; 7743 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 7744 ControlsExit && !EitherMayExit, 7745 AllowPredicates); 7746 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 7747 ControlsExit && !EitherMayExit, 7748 AllowPredicates); 7749 7750 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 7751 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 7752 if (isa<ConstantInt>(Op1)) 7753 return Op1 == NeutralElement ? EL0 : EL1; 7754 if (isa<ConstantInt>(Op0)) 7755 return Op0 == NeutralElement ? EL1 : EL0; 7756 7757 const SCEV *BECount = getCouldNotCompute(); 7758 const SCEV *MaxBECount = getCouldNotCompute(); 7759 if (EitherMayExit) { 7760 // Both conditions must be same for the loop to continue executing. 7761 // Choose the less conservative count. 7762 // If ExitCond is a short-circuit form (select), using 7763 // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general. 7764 // To see the detailed examples, please see 7765 // test/Analysis/ScalarEvolution/exit-count-select.ll 7766 bool PoisonSafe = isa<BinaryOperator>(ExitCond); 7767 if (!PoisonSafe) 7768 // Even if ExitCond is select, we can safely derive BECount using both 7769 // EL0 and EL1 in these cases: 7770 // (1) EL0.ExactNotTaken is non-zero 7771 // (2) EL1.ExactNotTaken is non-poison 7772 // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and 7773 // it cannot be umin(0, ..)) 7774 // The PoisonSafe assignment below is simplified and the assertion after 7775 // BECount calculation fully guarantees the condition (3). 7776 PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) || 7777 isa<SCEVConstant>(EL1.ExactNotTaken); 7778 if (EL0.ExactNotTaken != getCouldNotCompute() && 7779 EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) { 7780 BECount = 7781 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7782 7783 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 7784 // it should have been simplified to zero (see the condition (3) above) 7785 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 7786 BECount->isZero()); 7787 } 7788 if (EL0.MaxNotTaken == getCouldNotCompute()) 7789 MaxBECount = EL1.MaxNotTaken; 7790 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7791 MaxBECount = EL0.MaxNotTaken; 7792 else 7793 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7794 } else { 7795 // Both conditions must be same at the same time for the loop to exit. 7796 // For now, be conservative. 7797 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7798 BECount = EL0.ExactNotTaken; 7799 } 7800 7801 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7802 // to be more aggressive when computing BECount than when computing 7803 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7804 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7805 // to not. 7806 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7807 !isa<SCEVCouldNotCompute>(BECount)) 7808 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7809 7810 return ExitLimit(BECount, MaxBECount, false, 7811 { &EL0.Predicates, &EL1.Predicates }); 7812 } 7813 7814 ScalarEvolution::ExitLimit 7815 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7816 ICmpInst *ExitCond, 7817 bool ExitIfTrue, 7818 bool ControlsExit, 7819 bool AllowPredicates) { 7820 // If the condition was exit on true, convert the condition to exit on false 7821 ICmpInst::Predicate Pred; 7822 if (!ExitIfTrue) 7823 Pred = ExitCond->getPredicate(); 7824 else 7825 Pred = ExitCond->getInversePredicate(); 7826 const ICmpInst::Predicate OriginalPred = Pred; 7827 7828 // Handle common loops like: for (X = "string"; *X; ++X) 7829 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7830 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7831 ExitLimit ItCnt = 7832 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7833 if (ItCnt.hasAnyInfo()) 7834 return ItCnt; 7835 } 7836 7837 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7838 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7839 7840 // Try to evaluate any dependencies out of the loop. 7841 LHS = getSCEVAtScope(LHS, L); 7842 RHS = getSCEVAtScope(RHS, L); 7843 7844 // At this point, we would like to compute how many iterations of the 7845 // loop the predicate will return true for these inputs. 7846 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7847 // If there is a loop-invariant, force it into the RHS. 7848 std::swap(LHS, RHS); 7849 Pred = ICmpInst::getSwappedPredicate(Pred); 7850 } 7851 7852 // Simplify the operands before analyzing them. 7853 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7854 7855 // If we have a comparison of a chrec against a constant, try to use value 7856 // ranges to answer this query. 7857 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7858 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7859 if (AddRec->getLoop() == L) { 7860 // Form the constant range. 7861 ConstantRange CompRange = 7862 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7863 7864 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7865 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7866 } 7867 7868 switch (Pred) { 7869 case ICmpInst::ICMP_NE: { // while (X != Y) 7870 // Convert to: while (X-Y != 0) 7871 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7872 AllowPredicates); 7873 if (EL.hasAnyInfo()) return EL; 7874 break; 7875 } 7876 case ICmpInst::ICMP_EQ: { // while (X == Y) 7877 // Convert to: while (X-Y == 0) 7878 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7879 if (EL.hasAnyInfo()) return EL; 7880 break; 7881 } 7882 case ICmpInst::ICMP_SLT: 7883 case ICmpInst::ICMP_ULT: { // while (X < Y) 7884 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7885 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7886 AllowPredicates); 7887 if (EL.hasAnyInfo()) return EL; 7888 break; 7889 } 7890 case ICmpInst::ICMP_SGT: 7891 case ICmpInst::ICMP_UGT: { // while (X > Y) 7892 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7893 ExitLimit EL = 7894 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7895 AllowPredicates); 7896 if (EL.hasAnyInfo()) return EL; 7897 break; 7898 } 7899 default: 7900 break; 7901 } 7902 7903 auto *ExhaustiveCount = 7904 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7905 7906 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7907 return ExhaustiveCount; 7908 7909 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7910 ExitCond->getOperand(1), L, OriginalPred); 7911 } 7912 7913 ScalarEvolution::ExitLimit 7914 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7915 SwitchInst *Switch, 7916 BasicBlock *ExitingBlock, 7917 bool ControlsExit) { 7918 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7919 7920 // Give up if the exit is the default dest of a switch. 7921 if (Switch->getDefaultDest() == ExitingBlock) 7922 return getCouldNotCompute(); 7923 7924 assert(L->contains(Switch->getDefaultDest()) && 7925 "Default case must not exit the loop!"); 7926 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7927 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7928 7929 // while (X != Y) --> while (X-Y != 0) 7930 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7931 if (EL.hasAnyInfo()) 7932 return EL; 7933 7934 return getCouldNotCompute(); 7935 } 7936 7937 static ConstantInt * 7938 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7939 ScalarEvolution &SE) { 7940 const SCEV *InVal = SE.getConstant(C); 7941 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7942 assert(isa<SCEVConstant>(Val) && 7943 "Evaluation of SCEV at constant didn't fold correctly?"); 7944 return cast<SCEVConstant>(Val)->getValue(); 7945 } 7946 7947 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7948 /// compute the backedge execution count. 7949 ScalarEvolution::ExitLimit 7950 ScalarEvolution::computeLoadConstantCompareExitLimit( 7951 LoadInst *LI, 7952 Constant *RHS, 7953 const Loop *L, 7954 ICmpInst::Predicate predicate) { 7955 if (LI->isVolatile()) return getCouldNotCompute(); 7956 7957 // Check to see if the loaded pointer is a getelementptr of a global. 7958 // TODO: Use SCEV instead of manually grubbing with GEPs. 7959 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7960 if (!GEP) return getCouldNotCompute(); 7961 7962 // Make sure that it is really a constant global we are gepping, with an 7963 // initializer, and make sure the first IDX is really 0. 7964 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7965 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7966 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7967 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7968 return getCouldNotCompute(); 7969 7970 // Okay, we allow one non-constant index into the GEP instruction. 7971 Value *VarIdx = nullptr; 7972 std::vector<Constant*> Indexes; 7973 unsigned VarIdxNum = 0; 7974 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7975 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7976 Indexes.push_back(CI); 7977 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7978 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7979 VarIdx = GEP->getOperand(i); 7980 VarIdxNum = i-2; 7981 Indexes.push_back(nullptr); 7982 } 7983 7984 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7985 if (!VarIdx) 7986 return getCouldNotCompute(); 7987 7988 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7989 // Check to see if X is a loop variant variable value now. 7990 const SCEV *Idx = getSCEV(VarIdx); 7991 Idx = getSCEVAtScope(Idx, L); 7992 7993 // We can only recognize very limited forms of loop index expressions, in 7994 // particular, only affine AddRec's like {C1,+,C2}<L>. 7995 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7996 if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() || 7997 isLoopInvariant(IdxExpr, L) || 7998 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7999 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 8000 return getCouldNotCompute(); 8001 8002 unsigned MaxSteps = MaxBruteForceIterations; 8003 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 8004 ConstantInt *ItCst = ConstantInt::get( 8005 cast<IntegerType>(IdxExpr->getType()), IterationNum); 8006 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 8007 8008 // Form the GEP offset. 8009 Indexes[VarIdxNum] = Val; 8010 8011 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 8012 Indexes); 8013 if (!Result) break; // Cannot compute! 8014 8015 // Evaluate the condition for this iteration. 8016 Result = ConstantExpr::getICmp(predicate, Result, RHS); 8017 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 8018 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 8019 ++NumArrayLenItCounts; 8020 return getConstant(ItCst); // Found terminating iteration! 8021 } 8022 } 8023 return getCouldNotCompute(); 8024 } 8025 8026 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8027 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8028 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8029 if (!RHS) 8030 return getCouldNotCompute(); 8031 8032 const BasicBlock *Latch = L->getLoopLatch(); 8033 if (!Latch) 8034 return getCouldNotCompute(); 8035 8036 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8037 if (!Predecessor) 8038 return getCouldNotCompute(); 8039 8040 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8041 // Return LHS in OutLHS and shift_opt in OutOpCode. 8042 auto MatchPositiveShift = 8043 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8044 8045 using namespace PatternMatch; 8046 8047 ConstantInt *ShiftAmt; 8048 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8049 OutOpCode = Instruction::LShr; 8050 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8051 OutOpCode = Instruction::AShr; 8052 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8053 OutOpCode = Instruction::Shl; 8054 else 8055 return false; 8056 8057 return ShiftAmt->getValue().isStrictlyPositive(); 8058 }; 8059 8060 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8061 // 8062 // loop: 8063 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8064 // %iv.shifted = lshr i32 %iv, <positive constant> 8065 // 8066 // Return true on a successful match. Return the corresponding PHI node (%iv 8067 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8068 auto MatchShiftRecurrence = 8069 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8070 Optional<Instruction::BinaryOps> PostShiftOpCode; 8071 8072 { 8073 Instruction::BinaryOps OpC; 8074 Value *V; 8075 8076 // If we encounter a shift instruction, "peel off" the shift operation, 8077 // and remember that we did so. Later when we inspect %iv's backedge 8078 // value, we will make sure that the backedge value uses the same 8079 // operation. 8080 // 8081 // Note: the peeled shift operation does not have to be the same 8082 // instruction as the one feeding into the PHI's backedge value. We only 8083 // really care about it being the same *kind* of shift instruction -- 8084 // that's all that is required for our later inferences to hold. 8085 if (MatchPositiveShift(LHS, V, OpC)) { 8086 PostShiftOpCode = OpC; 8087 LHS = V; 8088 } 8089 } 8090 8091 PNOut = dyn_cast<PHINode>(LHS); 8092 if (!PNOut || PNOut->getParent() != L->getHeader()) 8093 return false; 8094 8095 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8096 Value *OpLHS; 8097 8098 return 8099 // The backedge value for the PHI node must be a shift by a positive 8100 // amount 8101 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8102 8103 // of the PHI node itself 8104 OpLHS == PNOut && 8105 8106 // and the kind of shift should be match the kind of shift we peeled 8107 // off, if any. 8108 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8109 }; 8110 8111 PHINode *PN; 8112 Instruction::BinaryOps OpCode; 8113 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8114 return getCouldNotCompute(); 8115 8116 const DataLayout &DL = getDataLayout(); 8117 8118 // The key rationale for this optimization is that for some kinds of shift 8119 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8120 // within a finite number of iterations. If the condition guarding the 8121 // backedge (in the sense that the backedge is taken if the condition is true) 8122 // is false for the value the shift recurrence stabilizes to, then we know 8123 // that the backedge is taken only a finite number of times. 8124 8125 ConstantInt *StableValue = nullptr; 8126 switch (OpCode) { 8127 default: 8128 llvm_unreachable("Impossible case!"); 8129 8130 case Instruction::AShr: { 8131 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8132 // bitwidth(K) iterations. 8133 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8134 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8135 Predecessor->getTerminator(), &DT); 8136 auto *Ty = cast<IntegerType>(RHS->getType()); 8137 if (Known.isNonNegative()) 8138 StableValue = ConstantInt::get(Ty, 0); 8139 else if (Known.isNegative()) 8140 StableValue = ConstantInt::get(Ty, -1, true); 8141 else 8142 return getCouldNotCompute(); 8143 8144 break; 8145 } 8146 case Instruction::LShr: 8147 case Instruction::Shl: 8148 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8149 // stabilize to 0 in at most bitwidth(K) iterations. 8150 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8151 break; 8152 } 8153 8154 auto *Result = 8155 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8156 assert(Result->getType()->isIntegerTy(1) && 8157 "Otherwise cannot be an operand to a branch instruction"); 8158 8159 if (Result->isZeroValue()) { 8160 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8161 const SCEV *UpperBound = 8162 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8163 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8164 } 8165 8166 return getCouldNotCompute(); 8167 } 8168 8169 /// Return true if we can constant fold an instruction of the specified type, 8170 /// assuming that all operands were constants. 8171 static bool CanConstantFold(const Instruction *I) { 8172 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8173 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8174 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8175 return true; 8176 8177 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8178 if (const Function *F = CI->getCalledFunction()) 8179 return canConstantFoldCallTo(CI, F); 8180 return false; 8181 } 8182 8183 /// Determine whether this instruction can constant evolve within this loop 8184 /// assuming its operands can all constant evolve. 8185 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8186 // An instruction outside of the loop can't be derived from a loop PHI. 8187 if (!L->contains(I)) return false; 8188 8189 if (isa<PHINode>(I)) { 8190 // We don't currently keep track of the control flow needed to evaluate 8191 // PHIs, so we cannot handle PHIs inside of loops. 8192 return L->getHeader() == I->getParent(); 8193 } 8194 8195 // If we won't be able to constant fold this expression even if the operands 8196 // are constants, bail early. 8197 return CanConstantFold(I); 8198 } 8199 8200 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8201 /// recursing through each instruction operand until reaching a loop header phi. 8202 static PHINode * 8203 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8204 DenseMap<Instruction *, PHINode *> &PHIMap, 8205 unsigned Depth) { 8206 if (Depth > MaxConstantEvolvingDepth) 8207 return nullptr; 8208 8209 // Otherwise, we can evaluate this instruction if all of its operands are 8210 // constant or derived from a PHI node themselves. 8211 PHINode *PHI = nullptr; 8212 for (Value *Op : UseInst->operands()) { 8213 if (isa<Constant>(Op)) continue; 8214 8215 Instruction *OpInst = dyn_cast<Instruction>(Op); 8216 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8217 8218 PHINode *P = dyn_cast<PHINode>(OpInst); 8219 if (!P) 8220 // If this operand is already visited, reuse the prior result. 8221 // We may have P != PHI if this is the deepest point at which the 8222 // inconsistent paths meet. 8223 P = PHIMap.lookup(OpInst); 8224 if (!P) { 8225 // Recurse and memoize the results, whether a phi is found or not. 8226 // This recursive call invalidates pointers into PHIMap. 8227 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8228 PHIMap[OpInst] = P; 8229 } 8230 if (!P) 8231 return nullptr; // Not evolving from PHI 8232 if (PHI && PHI != P) 8233 return nullptr; // Evolving from multiple different PHIs. 8234 PHI = P; 8235 } 8236 // This is a expression evolving from a constant PHI! 8237 return PHI; 8238 } 8239 8240 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8241 /// in the loop that V is derived from. We allow arbitrary operations along the 8242 /// way, but the operands of an operation must either be constants or a value 8243 /// derived from a constant PHI. If this expression does not fit with these 8244 /// constraints, return null. 8245 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8246 Instruction *I = dyn_cast<Instruction>(V); 8247 if (!I || !canConstantEvolve(I, L)) return nullptr; 8248 8249 if (PHINode *PN = dyn_cast<PHINode>(I)) 8250 return PN; 8251 8252 // Record non-constant instructions contained by the loop. 8253 DenseMap<Instruction *, PHINode *> PHIMap; 8254 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8255 } 8256 8257 /// EvaluateExpression - Given an expression that passes the 8258 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8259 /// in the loop has the value PHIVal. If we can't fold this expression for some 8260 /// reason, return null. 8261 static Constant *EvaluateExpression(Value *V, const Loop *L, 8262 DenseMap<Instruction *, Constant *> &Vals, 8263 const DataLayout &DL, 8264 const TargetLibraryInfo *TLI) { 8265 // Convenient constant check, but redundant for recursive calls. 8266 if (Constant *C = dyn_cast<Constant>(V)) return C; 8267 Instruction *I = dyn_cast<Instruction>(V); 8268 if (!I) return nullptr; 8269 8270 if (Constant *C = Vals.lookup(I)) return C; 8271 8272 // An instruction inside the loop depends on a value outside the loop that we 8273 // weren't given a mapping for, or a value such as a call inside the loop. 8274 if (!canConstantEvolve(I, L)) return nullptr; 8275 8276 // An unmapped PHI can be due to a branch or another loop inside this loop, 8277 // or due to this not being the initial iteration through a loop where we 8278 // couldn't compute the evolution of this particular PHI last time. 8279 if (isa<PHINode>(I)) return nullptr; 8280 8281 std::vector<Constant*> Operands(I->getNumOperands()); 8282 8283 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8284 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8285 if (!Operand) { 8286 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8287 if (!Operands[i]) return nullptr; 8288 continue; 8289 } 8290 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8291 Vals[Operand] = C; 8292 if (!C) return nullptr; 8293 Operands[i] = C; 8294 } 8295 8296 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8297 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8298 Operands[1], DL, TLI); 8299 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8300 if (!LI->isVolatile()) 8301 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8302 } 8303 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8304 } 8305 8306 8307 // If every incoming value to PN except the one for BB is a specific Constant, 8308 // return that, else return nullptr. 8309 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8310 Constant *IncomingVal = nullptr; 8311 8312 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8313 if (PN->getIncomingBlock(i) == BB) 8314 continue; 8315 8316 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8317 if (!CurrentVal) 8318 return nullptr; 8319 8320 if (IncomingVal != CurrentVal) { 8321 if (IncomingVal) 8322 return nullptr; 8323 IncomingVal = CurrentVal; 8324 } 8325 } 8326 8327 return IncomingVal; 8328 } 8329 8330 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8331 /// in the header of its containing loop, we know the loop executes a 8332 /// constant number of times, and the PHI node is just a recurrence 8333 /// involving constants, fold it. 8334 Constant * 8335 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8336 const APInt &BEs, 8337 const Loop *L) { 8338 auto I = ConstantEvolutionLoopExitValue.find(PN); 8339 if (I != ConstantEvolutionLoopExitValue.end()) 8340 return I->second; 8341 8342 if (BEs.ugt(MaxBruteForceIterations)) 8343 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8344 8345 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8346 8347 DenseMap<Instruction *, Constant *> CurrentIterVals; 8348 BasicBlock *Header = L->getHeader(); 8349 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8350 8351 BasicBlock *Latch = L->getLoopLatch(); 8352 if (!Latch) 8353 return nullptr; 8354 8355 for (PHINode &PHI : Header->phis()) { 8356 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8357 CurrentIterVals[&PHI] = StartCST; 8358 } 8359 if (!CurrentIterVals.count(PN)) 8360 return RetVal = nullptr; 8361 8362 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8363 8364 // Execute the loop symbolically to determine the exit value. 8365 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8366 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8367 8368 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8369 unsigned IterationNum = 0; 8370 const DataLayout &DL = getDataLayout(); 8371 for (; ; ++IterationNum) { 8372 if (IterationNum == NumIterations) 8373 return RetVal = CurrentIterVals[PN]; // Got exit value! 8374 8375 // Compute the value of the PHIs for the next iteration. 8376 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8377 DenseMap<Instruction *, Constant *> NextIterVals; 8378 Constant *NextPHI = 8379 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8380 if (!NextPHI) 8381 return nullptr; // Couldn't evaluate! 8382 NextIterVals[PN] = NextPHI; 8383 8384 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8385 8386 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8387 // cease to be able to evaluate one of them or if they stop evolving, 8388 // because that doesn't necessarily prevent us from computing PN. 8389 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8390 for (const auto &I : CurrentIterVals) { 8391 PHINode *PHI = dyn_cast<PHINode>(I.first); 8392 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8393 PHIsToCompute.emplace_back(PHI, I.second); 8394 } 8395 // We use two distinct loops because EvaluateExpression may invalidate any 8396 // iterators into CurrentIterVals. 8397 for (const auto &I : PHIsToCompute) { 8398 PHINode *PHI = I.first; 8399 Constant *&NextPHI = NextIterVals[PHI]; 8400 if (!NextPHI) { // Not already computed. 8401 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8402 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8403 } 8404 if (NextPHI != I.second) 8405 StoppedEvolving = false; 8406 } 8407 8408 // If all entries in CurrentIterVals == NextIterVals then we can stop 8409 // iterating, the loop can't continue to change. 8410 if (StoppedEvolving) 8411 return RetVal = CurrentIterVals[PN]; 8412 8413 CurrentIterVals.swap(NextIterVals); 8414 } 8415 } 8416 8417 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8418 Value *Cond, 8419 bool ExitWhen) { 8420 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8421 if (!PN) return getCouldNotCompute(); 8422 8423 // If the loop is canonicalized, the PHI will have exactly two entries. 8424 // That's the only form we support here. 8425 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8426 8427 DenseMap<Instruction *, Constant *> CurrentIterVals; 8428 BasicBlock *Header = L->getHeader(); 8429 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8430 8431 BasicBlock *Latch = L->getLoopLatch(); 8432 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8433 8434 for (PHINode &PHI : Header->phis()) { 8435 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8436 CurrentIterVals[&PHI] = StartCST; 8437 } 8438 if (!CurrentIterVals.count(PN)) 8439 return getCouldNotCompute(); 8440 8441 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8442 // the loop symbolically to determine when the condition gets a value of 8443 // "ExitWhen". 8444 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8445 const DataLayout &DL = getDataLayout(); 8446 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8447 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8448 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8449 8450 // Couldn't symbolically evaluate. 8451 if (!CondVal) return getCouldNotCompute(); 8452 8453 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8454 ++NumBruteForceTripCountsComputed; 8455 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8456 } 8457 8458 // Update all the PHI nodes for the next iteration. 8459 DenseMap<Instruction *, Constant *> NextIterVals; 8460 8461 // Create a list of which PHIs we need to compute. We want to do this before 8462 // calling EvaluateExpression on them because that may invalidate iterators 8463 // into CurrentIterVals. 8464 SmallVector<PHINode *, 8> PHIsToCompute; 8465 for (const auto &I : CurrentIterVals) { 8466 PHINode *PHI = dyn_cast<PHINode>(I.first); 8467 if (!PHI || PHI->getParent() != Header) continue; 8468 PHIsToCompute.push_back(PHI); 8469 } 8470 for (PHINode *PHI : PHIsToCompute) { 8471 Constant *&NextPHI = NextIterVals[PHI]; 8472 if (NextPHI) continue; // Already computed! 8473 8474 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8475 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8476 } 8477 CurrentIterVals.swap(NextIterVals); 8478 } 8479 8480 // Too many iterations were needed to evaluate. 8481 return getCouldNotCompute(); 8482 } 8483 8484 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8485 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8486 ValuesAtScopes[V]; 8487 // Check to see if we've folded this expression at this loop before. 8488 for (auto &LS : Values) 8489 if (LS.first == L) 8490 return LS.second ? LS.second : V; 8491 8492 Values.emplace_back(L, nullptr); 8493 8494 // Otherwise compute it. 8495 const SCEV *C = computeSCEVAtScope(V, L); 8496 for (auto &LS : reverse(ValuesAtScopes[V])) 8497 if (LS.first == L) { 8498 LS.second = C; 8499 break; 8500 } 8501 return C; 8502 } 8503 8504 /// This builds up a Constant using the ConstantExpr interface. That way, we 8505 /// will return Constants for objects which aren't represented by a 8506 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8507 /// Returns NULL if the SCEV isn't representable as a Constant. 8508 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8509 switch (V->getSCEVType()) { 8510 case scCouldNotCompute: 8511 case scAddRecExpr: 8512 return nullptr; 8513 case scConstant: 8514 return cast<SCEVConstant>(V)->getValue(); 8515 case scUnknown: 8516 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8517 case scSignExtend: { 8518 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8519 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8520 return ConstantExpr::getSExt(CastOp, SS->getType()); 8521 return nullptr; 8522 } 8523 case scZeroExtend: { 8524 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8525 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8526 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8527 return nullptr; 8528 } 8529 case scPtrToInt: { 8530 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 8531 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 8532 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 8533 8534 return nullptr; 8535 } 8536 case scTruncate: { 8537 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8538 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8539 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8540 return nullptr; 8541 } 8542 case scAddExpr: { 8543 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8544 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8545 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8546 unsigned AS = PTy->getAddressSpace(); 8547 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8548 C = ConstantExpr::getBitCast(C, DestPtrTy); 8549 } 8550 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8551 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8552 if (!C2) 8553 return nullptr; 8554 8555 // First pointer! 8556 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8557 unsigned AS = C2->getType()->getPointerAddressSpace(); 8558 std::swap(C, C2); 8559 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8560 // The offsets have been converted to bytes. We can add bytes to an 8561 // i8* by GEP with the byte count in the first index. 8562 C = ConstantExpr::getBitCast(C, DestPtrTy); 8563 } 8564 8565 // Don't bother trying to sum two pointers. We probably can't 8566 // statically compute a load that results from it anyway. 8567 if (C2->getType()->isPointerTy()) 8568 return nullptr; 8569 8570 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8571 if (PTy->getElementType()->isStructTy()) 8572 C2 = ConstantExpr::getIntegerCast( 8573 C2, Type::getInt32Ty(C->getContext()), true); 8574 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8575 } else 8576 C = ConstantExpr::getAdd(C, C2); 8577 } 8578 return C; 8579 } 8580 return nullptr; 8581 } 8582 case scMulExpr: { 8583 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8584 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8585 // Don't bother with pointers at all. 8586 if (C->getType()->isPointerTy()) 8587 return nullptr; 8588 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8589 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8590 if (!C2 || C2->getType()->isPointerTy()) 8591 return nullptr; 8592 C = ConstantExpr::getMul(C, C2); 8593 } 8594 return C; 8595 } 8596 return nullptr; 8597 } 8598 case scUDivExpr: { 8599 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8600 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8601 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8602 if (LHS->getType() == RHS->getType()) 8603 return ConstantExpr::getUDiv(LHS, RHS); 8604 return nullptr; 8605 } 8606 case scSMaxExpr: 8607 case scUMaxExpr: 8608 case scSMinExpr: 8609 case scUMinExpr: 8610 return nullptr; // TODO: smax, umax, smin, umax. 8611 } 8612 llvm_unreachable("Unknown SCEV kind!"); 8613 } 8614 8615 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8616 if (isa<SCEVConstant>(V)) return V; 8617 8618 // If this instruction is evolved from a constant-evolving PHI, compute the 8619 // exit value from the loop without using SCEVs. 8620 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8621 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8622 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8623 const Loop *CurrLoop = this->LI[I->getParent()]; 8624 // Looking for loop exit value. 8625 if (CurrLoop && CurrLoop->getParentLoop() == L && 8626 PN->getParent() == CurrLoop->getHeader()) { 8627 // Okay, there is no closed form solution for the PHI node. Check 8628 // to see if the loop that contains it has a known backedge-taken 8629 // count. If so, we may be able to force computation of the exit 8630 // value. 8631 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8632 // This trivial case can show up in some degenerate cases where 8633 // the incoming IR has not yet been fully simplified. 8634 if (BackedgeTakenCount->isZero()) { 8635 Value *InitValue = nullptr; 8636 bool MultipleInitValues = false; 8637 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8638 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8639 if (!InitValue) 8640 InitValue = PN->getIncomingValue(i); 8641 else if (InitValue != PN->getIncomingValue(i)) { 8642 MultipleInitValues = true; 8643 break; 8644 } 8645 } 8646 } 8647 if (!MultipleInitValues && InitValue) 8648 return getSCEV(InitValue); 8649 } 8650 // Do we have a loop invariant value flowing around the backedge 8651 // for a loop which must execute the backedge? 8652 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8653 isKnownPositive(BackedgeTakenCount) && 8654 PN->getNumIncomingValues() == 2) { 8655 8656 unsigned InLoopPred = 8657 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8658 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8659 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8660 return getSCEV(BackedgeVal); 8661 } 8662 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8663 // Okay, we know how many times the containing loop executes. If 8664 // this is a constant evolving PHI node, get the final value at 8665 // the specified iteration number. 8666 Constant *RV = getConstantEvolutionLoopExitValue( 8667 PN, BTCC->getAPInt(), CurrLoop); 8668 if (RV) return getSCEV(RV); 8669 } 8670 } 8671 8672 // If there is a single-input Phi, evaluate it at our scope. If we can 8673 // prove that this replacement does not break LCSSA form, use new value. 8674 if (PN->getNumOperands() == 1) { 8675 const SCEV *Input = getSCEV(PN->getOperand(0)); 8676 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8677 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8678 // for the simplest case just support constants. 8679 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8680 } 8681 } 8682 8683 // Okay, this is an expression that we cannot symbolically evaluate 8684 // into a SCEV. Check to see if it's possible to symbolically evaluate 8685 // the arguments into constants, and if so, try to constant propagate the 8686 // result. This is particularly useful for computing loop exit values. 8687 if (CanConstantFold(I)) { 8688 SmallVector<Constant *, 4> Operands; 8689 bool MadeImprovement = false; 8690 for (Value *Op : I->operands()) { 8691 if (Constant *C = dyn_cast<Constant>(Op)) { 8692 Operands.push_back(C); 8693 continue; 8694 } 8695 8696 // If any of the operands is non-constant and if they are 8697 // non-integer and non-pointer, don't even try to analyze them 8698 // with scev techniques. 8699 if (!isSCEVable(Op->getType())) 8700 return V; 8701 8702 const SCEV *OrigV = getSCEV(Op); 8703 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8704 MadeImprovement |= OrigV != OpV; 8705 8706 Constant *C = BuildConstantFromSCEV(OpV); 8707 if (!C) return V; 8708 if (C->getType() != Op->getType()) 8709 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8710 Op->getType(), 8711 false), 8712 C, Op->getType()); 8713 Operands.push_back(C); 8714 } 8715 8716 // Check to see if getSCEVAtScope actually made an improvement. 8717 if (MadeImprovement) { 8718 Constant *C = nullptr; 8719 const DataLayout &DL = getDataLayout(); 8720 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8721 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8722 Operands[1], DL, &TLI); 8723 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8724 if (!Load->isVolatile()) 8725 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8726 DL); 8727 } else 8728 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8729 if (!C) return V; 8730 return getSCEV(C); 8731 } 8732 } 8733 } 8734 8735 // This is some other type of SCEVUnknown, just return it. 8736 return V; 8737 } 8738 8739 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8740 // Avoid performing the look-up in the common case where the specified 8741 // expression has no loop-variant portions. 8742 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8743 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8744 if (OpAtScope != Comm->getOperand(i)) { 8745 // Okay, at least one of these operands is loop variant but might be 8746 // foldable. Build a new instance of the folded commutative expression. 8747 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8748 Comm->op_begin()+i); 8749 NewOps.push_back(OpAtScope); 8750 8751 for (++i; i != e; ++i) { 8752 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8753 NewOps.push_back(OpAtScope); 8754 } 8755 if (isa<SCEVAddExpr>(Comm)) 8756 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8757 if (isa<SCEVMulExpr>(Comm)) 8758 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8759 if (isa<SCEVMinMaxExpr>(Comm)) 8760 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8761 llvm_unreachable("Unknown commutative SCEV type!"); 8762 } 8763 } 8764 // If we got here, all operands are loop invariant. 8765 return Comm; 8766 } 8767 8768 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8769 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8770 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8771 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8772 return Div; // must be loop invariant 8773 return getUDivExpr(LHS, RHS); 8774 } 8775 8776 // If this is a loop recurrence for a loop that does not contain L, then we 8777 // are dealing with the final value computed by the loop. 8778 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8779 // First, attempt to evaluate each operand. 8780 // Avoid performing the look-up in the common case where the specified 8781 // expression has no loop-variant portions. 8782 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8783 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8784 if (OpAtScope == AddRec->getOperand(i)) 8785 continue; 8786 8787 // Okay, at least one of these operands is loop variant but might be 8788 // foldable. Build a new instance of the folded commutative expression. 8789 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8790 AddRec->op_begin()+i); 8791 NewOps.push_back(OpAtScope); 8792 for (++i; i != e; ++i) 8793 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8794 8795 const SCEV *FoldedRec = 8796 getAddRecExpr(NewOps, AddRec->getLoop(), 8797 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8798 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8799 // The addrec may be folded to a nonrecurrence, for example, if the 8800 // induction variable is multiplied by zero after constant folding. Go 8801 // ahead and return the folded value. 8802 if (!AddRec) 8803 return FoldedRec; 8804 break; 8805 } 8806 8807 // If the scope is outside the addrec's loop, evaluate it by using the 8808 // loop exit value of the addrec. 8809 if (!AddRec->getLoop()->contains(L)) { 8810 // To evaluate this recurrence, we need to know how many times the AddRec 8811 // loop iterates. Compute this now. 8812 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8813 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8814 8815 // Then, evaluate the AddRec. 8816 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8817 } 8818 8819 return AddRec; 8820 } 8821 8822 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8823 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8824 if (Op == Cast->getOperand()) 8825 return Cast; // must be loop invariant 8826 return getZeroExtendExpr(Op, Cast->getType()); 8827 } 8828 8829 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8830 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8831 if (Op == Cast->getOperand()) 8832 return Cast; // must be loop invariant 8833 return getSignExtendExpr(Op, Cast->getType()); 8834 } 8835 8836 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8837 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8838 if (Op == Cast->getOperand()) 8839 return Cast; // must be loop invariant 8840 return getTruncateExpr(Op, Cast->getType()); 8841 } 8842 8843 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 8844 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8845 if (Op == Cast->getOperand()) 8846 return Cast; // must be loop invariant 8847 return getPtrToIntExpr(Op, Cast->getType()); 8848 } 8849 8850 llvm_unreachable("Unknown SCEV type!"); 8851 } 8852 8853 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8854 return getSCEVAtScope(getSCEV(V), L); 8855 } 8856 8857 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8858 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8859 return stripInjectiveFunctions(ZExt->getOperand()); 8860 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8861 return stripInjectiveFunctions(SExt->getOperand()); 8862 return S; 8863 } 8864 8865 /// Finds the minimum unsigned root of the following equation: 8866 /// 8867 /// A * X = B (mod N) 8868 /// 8869 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8870 /// A and B isn't important. 8871 /// 8872 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8873 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8874 ScalarEvolution &SE) { 8875 uint32_t BW = A.getBitWidth(); 8876 assert(BW == SE.getTypeSizeInBits(B->getType())); 8877 assert(A != 0 && "A must be non-zero."); 8878 8879 // 1. D = gcd(A, N) 8880 // 8881 // The gcd of A and N may have only one prime factor: 2. The number of 8882 // trailing zeros in A is its multiplicity 8883 uint32_t Mult2 = A.countTrailingZeros(); 8884 // D = 2^Mult2 8885 8886 // 2. Check if B is divisible by D. 8887 // 8888 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8889 // is not less than multiplicity of this prime factor for D. 8890 if (SE.GetMinTrailingZeros(B) < Mult2) 8891 return SE.getCouldNotCompute(); 8892 8893 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8894 // modulo (N / D). 8895 // 8896 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8897 // (N / D) in general. The inverse itself always fits into BW bits, though, 8898 // so we immediately truncate it. 8899 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8900 APInt Mod(BW + 1, 0); 8901 Mod.setBit(BW - Mult2); // Mod = N / D 8902 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8903 8904 // 4. Compute the minimum unsigned root of the equation: 8905 // I * (B / D) mod (N / D) 8906 // To simplify the computation, we factor out the divide by D: 8907 // (I * B mod N) / D 8908 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8909 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8910 } 8911 8912 /// For a given quadratic addrec, generate coefficients of the corresponding 8913 /// quadratic equation, multiplied by a common value to ensure that they are 8914 /// integers. 8915 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8916 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8917 /// were multiplied by, and BitWidth is the bit width of the original addrec 8918 /// coefficients. 8919 /// This function returns None if the addrec coefficients are not compile- 8920 /// time constants. 8921 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8922 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8923 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8924 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8925 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8926 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8927 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8928 << *AddRec << '\n'); 8929 8930 // We currently can only solve this if the coefficients are constants. 8931 if (!LC || !MC || !NC) { 8932 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8933 return None; 8934 } 8935 8936 APInt L = LC->getAPInt(); 8937 APInt M = MC->getAPInt(); 8938 APInt N = NC->getAPInt(); 8939 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8940 8941 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8942 unsigned NewWidth = BitWidth + 1; 8943 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8944 << BitWidth << '\n'); 8945 // The sign-extension (as opposed to a zero-extension) here matches the 8946 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8947 N = N.sext(NewWidth); 8948 M = M.sext(NewWidth); 8949 L = L.sext(NewWidth); 8950 8951 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8952 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8953 // L+M, L+2M+N, L+3M+3N, ... 8954 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8955 // 8956 // The equation Acc = 0 is then 8957 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8958 // In a quadratic form it becomes: 8959 // N n^2 + (2M-N) n + 2L = 0. 8960 8961 APInt A = N; 8962 APInt B = 2 * M - A; 8963 APInt C = 2 * L; 8964 APInt T = APInt(NewWidth, 2); 8965 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8966 << "x + " << C << ", coeff bw: " << NewWidth 8967 << ", multiplied by " << T << '\n'); 8968 return std::make_tuple(A, B, C, T, BitWidth); 8969 } 8970 8971 /// Helper function to compare optional APInts: 8972 /// (a) if X and Y both exist, return min(X, Y), 8973 /// (b) if neither X nor Y exist, return None, 8974 /// (c) if exactly one of X and Y exists, return that value. 8975 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8976 if (X.hasValue() && Y.hasValue()) { 8977 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8978 APInt XW = X->sextOrSelf(W); 8979 APInt YW = Y->sextOrSelf(W); 8980 return XW.slt(YW) ? *X : *Y; 8981 } 8982 if (!X.hasValue() && !Y.hasValue()) 8983 return None; 8984 return X.hasValue() ? *X : *Y; 8985 } 8986 8987 /// Helper function to truncate an optional APInt to a given BitWidth. 8988 /// When solving addrec-related equations, it is preferable to return a value 8989 /// that has the same bit width as the original addrec's coefficients. If the 8990 /// solution fits in the original bit width, truncate it (except for i1). 8991 /// Returning a value of a different bit width may inhibit some optimizations. 8992 /// 8993 /// In general, a solution to a quadratic equation generated from an addrec 8994 /// may require BW+1 bits, where BW is the bit width of the addrec's 8995 /// coefficients. The reason is that the coefficients of the quadratic 8996 /// equation are BW+1 bits wide (to avoid truncation when converting from 8997 /// the addrec to the equation). 8998 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8999 if (!X.hasValue()) 9000 return None; 9001 unsigned W = X->getBitWidth(); 9002 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9003 return X->trunc(BitWidth); 9004 return X; 9005 } 9006 9007 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9008 /// iterations. The values L, M, N are assumed to be signed, and they 9009 /// should all have the same bit widths. 9010 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9011 /// where BW is the bit width of the addrec's coefficients. 9012 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9013 /// returned as such, otherwise the bit width of the returned value may 9014 /// be greater than BW. 9015 /// 9016 /// This function returns None if 9017 /// (a) the addrec coefficients are not constant, or 9018 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9019 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9020 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9021 static Optional<APInt> 9022 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9023 APInt A, B, C, M; 9024 unsigned BitWidth; 9025 auto T = GetQuadraticEquation(AddRec); 9026 if (!T.hasValue()) 9027 return None; 9028 9029 std::tie(A, B, C, M, BitWidth) = *T; 9030 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9031 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9032 if (!X.hasValue()) 9033 return None; 9034 9035 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9036 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9037 if (!V->isZero()) 9038 return None; 9039 9040 return TruncIfPossible(X, BitWidth); 9041 } 9042 9043 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9044 /// iterations. The values M, N are assumed to be signed, and they 9045 /// should all have the same bit widths. 9046 /// Find the least n such that c(n) does not belong to the given range, 9047 /// while c(n-1) does. 9048 /// 9049 /// This function returns None if 9050 /// (a) the addrec coefficients are not constant, or 9051 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9052 /// bounds of the range. 9053 static Optional<APInt> 9054 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9055 const ConstantRange &Range, ScalarEvolution &SE) { 9056 assert(AddRec->getOperand(0)->isZero() && 9057 "Starting value of addrec should be 0"); 9058 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9059 << Range << ", addrec " << *AddRec << '\n'); 9060 // This case is handled in getNumIterationsInRange. Here we can assume that 9061 // we start in the range. 9062 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9063 "Addrec's initial value should be in range"); 9064 9065 APInt A, B, C, M; 9066 unsigned BitWidth; 9067 auto T = GetQuadraticEquation(AddRec); 9068 if (!T.hasValue()) 9069 return None; 9070 9071 // Be careful about the return value: there can be two reasons for not 9072 // returning an actual number. First, if no solutions to the equations 9073 // were found, and second, if the solutions don't leave the given range. 9074 // The first case means that the actual solution is "unknown", the second 9075 // means that it's known, but not valid. If the solution is unknown, we 9076 // cannot make any conclusions. 9077 // Return a pair: the optional solution and a flag indicating if the 9078 // solution was found. 9079 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9080 // Solve for signed overflow and unsigned overflow, pick the lower 9081 // solution. 9082 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9083 << Bound << " (before multiplying by " << M << ")\n"); 9084 Bound *= M; // The quadratic equation multiplier. 9085 9086 Optional<APInt> SO = None; 9087 if (BitWidth > 1) { 9088 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9089 "signed overflow\n"); 9090 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9091 } 9092 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9093 "unsigned overflow\n"); 9094 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9095 BitWidth+1); 9096 9097 auto LeavesRange = [&] (const APInt &X) { 9098 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9099 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9100 if (Range.contains(V0->getValue())) 9101 return false; 9102 // X should be at least 1, so X-1 is non-negative. 9103 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9104 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9105 if (Range.contains(V1->getValue())) 9106 return true; 9107 return false; 9108 }; 9109 9110 // If SolveQuadraticEquationWrap returns None, it means that there can 9111 // be a solution, but the function failed to find it. We cannot treat it 9112 // as "no solution". 9113 if (!SO.hasValue() || !UO.hasValue()) 9114 return { None, false }; 9115 9116 // Check the smaller value first to see if it leaves the range. 9117 // At this point, both SO and UO must have values. 9118 Optional<APInt> Min = MinOptional(SO, UO); 9119 if (LeavesRange(*Min)) 9120 return { Min, true }; 9121 Optional<APInt> Max = Min == SO ? UO : SO; 9122 if (LeavesRange(*Max)) 9123 return { Max, true }; 9124 9125 // Solutions were found, but were eliminated, hence the "true". 9126 return { None, true }; 9127 }; 9128 9129 std::tie(A, B, C, M, BitWidth) = *T; 9130 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9131 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9132 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9133 auto SL = SolveForBoundary(Lower); 9134 auto SU = SolveForBoundary(Upper); 9135 // If any of the solutions was unknown, no meaninigful conclusions can 9136 // be made. 9137 if (!SL.second || !SU.second) 9138 return None; 9139 9140 // Claim: The correct solution is not some value between Min and Max. 9141 // 9142 // Justification: Assuming that Min and Max are different values, one of 9143 // them is when the first signed overflow happens, the other is when the 9144 // first unsigned overflow happens. Crossing the range boundary is only 9145 // possible via an overflow (treating 0 as a special case of it, modeling 9146 // an overflow as crossing k*2^W for some k). 9147 // 9148 // The interesting case here is when Min was eliminated as an invalid 9149 // solution, but Max was not. The argument is that if there was another 9150 // overflow between Min and Max, it would also have been eliminated if 9151 // it was considered. 9152 // 9153 // For a given boundary, it is possible to have two overflows of the same 9154 // type (signed/unsigned) without having the other type in between: this 9155 // can happen when the vertex of the parabola is between the iterations 9156 // corresponding to the overflows. This is only possible when the two 9157 // overflows cross k*2^W for the same k. In such case, if the second one 9158 // left the range (and was the first one to do so), the first overflow 9159 // would have to enter the range, which would mean that either we had left 9160 // the range before or that we started outside of it. Both of these cases 9161 // are contradictions. 9162 // 9163 // Claim: In the case where SolveForBoundary returns None, the correct 9164 // solution is not some value between the Max for this boundary and the 9165 // Min of the other boundary. 9166 // 9167 // Justification: Assume that we had such Max_A and Min_B corresponding 9168 // to range boundaries A and B and such that Max_A < Min_B. If there was 9169 // a solution between Max_A and Min_B, it would have to be caused by an 9170 // overflow corresponding to either A or B. It cannot correspond to B, 9171 // since Min_B is the first occurrence of such an overflow. If it 9172 // corresponded to A, it would have to be either a signed or an unsigned 9173 // overflow that is larger than both eliminated overflows for A. But 9174 // between the eliminated overflows and this overflow, the values would 9175 // cover the entire value space, thus crossing the other boundary, which 9176 // is a contradiction. 9177 9178 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9179 } 9180 9181 ScalarEvolution::ExitLimit 9182 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9183 bool AllowPredicates) { 9184 9185 // This is only used for loops with a "x != y" exit test. The exit condition 9186 // is now expressed as a single expression, V = x-y. So the exit test is 9187 // effectively V != 0. We know and take advantage of the fact that this 9188 // expression only being used in a comparison by zero context. 9189 9190 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9191 // If the value is a constant 9192 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9193 // If the value is already zero, the branch will execute zero times. 9194 if (C->getValue()->isZero()) return C; 9195 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9196 } 9197 9198 const SCEVAddRecExpr *AddRec = 9199 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9200 9201 if (!AddRec && AllowPredicates) 9202 // Try to make this an AddRec using runtime tests, in the first X 9203 // iterations of this loop, where X is the SCEV expression found by the 9204 // algorithm below. 9205 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9206 9207 if (!AddRec || AddRec->getLoop() != L) 9208 return getCouldNotCompute(); 9209 9210 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9211 // the quadratic equation to solve it. 9212 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9213 // We can only use this value if the chrec ends up with an exact zero 9214 // value at this index. When solving for "X*X != 5", for example, we 9215 // should not accept a root of 2. 9216 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9217 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9218 return ExitLimit(R, R, false, Predicates); 9219 } 9220 return getCouldNotCompute(); 9221 } 9222 9223 // Otherwise we can only handle this if it is affine. 9224 if (!AddRec->isAffine()) 9225 return getCouldNotCompute(); 9226 9227 // If this is an affine expression, the execution count of this branch is 9228 // the minimum unsigned root of the following equation: 9229 // 9230 // Start + Step*N = 0 (mod 2^BW) 9231 // 9232 // equivalent to: 9233 // 9234 // Step*N = -Start (mod 2^BW) 9235 // 9236 // where BW is the common bit width of Start and Step. 9237 9238 // Get the initial value for the loop. 9239 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9240 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9241 9242 // For now we handle only constant steps. 9243 // 9244 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9245 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9246 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9247 // We have not yet seen any such cases. 9248 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9249 if (!StepC || StepC->getValue()->isZero()) 9250 return getCouldNotCompute(); 9251 9252 // For positive steps (counting up until unsigned overflow): 9253 // N = -Start/Step (as unsigned) 9254 // For negative steps (counting down to zero): 9255 // N = Start/-Step 9256 // First compute the unsigned distance from zero in the direction of Step. 9257 bool CountDown = StepC->getAPInt().isNegative(); 9258 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9259 9260 // Handle unitary steps, which cannot wraparound. 9261 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9262 // N = Distance (as unsigned) 9263 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9264 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9265 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 9266 if (MaxBECountBase.ult(MaxBECount)) 9267 MaxBECount = MaxBECountBase; 9268 9269 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9270 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9271 // case, and see if we can improve the bound. 9272 // 9273 // Explicitly handling this here is necessary because getUnsignedRange 9274 // isn't context-sensitive; it doesn't know that we only care about the 9275 // range inside the loop. 9276 const SCEV *Zero = getZero(Distance->getType()); 9277 const SCEV *One = getOne(Distance->getType()); 9278 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9279 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9280 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9281 // as "unsigned_max(Distance + 1) - 1". 9282 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9283 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9284 } 9285 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9286 } 9287 9288 // If the condition controls loop exit (the loop exits only if the expression 9289 // is true) and the addition is no-wrap we can use unsigned divide to 9290 // compute the backedge count. In this case, the step may not divide the 9291 // distance, but we don't care because if the condition is "missed" the loop 9292 // will have undefined behavior due to wrapping. 9293 if (ControlsExit && AddRec->hasNoSelfWrap() && 9294 loopHasNoAbnormalExits(AddRec->getLoop())) { 9295 const SCEV *Exact = 9296 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9297 const SCEV *Max = getCouldNotCompute(); 9298 if (Exact != getCouldNotCompute()) { 9299 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 9300 APInt BaseMaxInt = getUnsignedRangeMax(Exact); 9301 if (BaseMaxInt.ult(MaxInt)) 9302 Max = getConstant(BaseMaxInt); 9303 else 9304 Max = getConstant(MaxInt); 9305 } 9306 return ExitLimit(Exact, Max, false, Predicates); 9307 } 9308 9309 // Solve the general equation. 9310 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9311 getNegativeSCEV(Start), *this); 9312 const SCEV *M = E == getCouldNotCompute() 9313 ? E 9314 : getConstant(getUnsignedRangeMax(E)); 9315 return ExitLimit(E, M, false, Predicates); 9316 } 9317 9318 ScalarEvolution::ExitLimit 9319 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9320 // Loops that look like: while (X == 0) are very strange indeed. We don't 9321 // handle them yet except for the trivial case. This could be expanded in the 9322 // future as needed. 9323 9324 // If the value is a constant, check to see if it is known to be non-zero 9325 // already. If so, the backedge will execute zero times. 9326 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9327 if (!C->getValue()->isZero()) 9328 return getZero(C->getType()); 9329 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9330 } 9331 9332 // We could implement others, but I really doubt anyone writes loops like 9333 // this, and if they did, they would already be constant folded. 9334 return getCouldNotCompute(); 9335 } 9336 9337 std::pair<const BasicBlock *, const BasicBlock *> 9338 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9339 const { 9340 // If the block has a unique predecessor, then there is no path from the 9341 // predecessor to the block that does not go through the direct edge 9342 // from the predecessor to the block. 9343 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9344 return {Pred, BB}; 9345 9346 // A loop's header is defined to be a block that dominates the loop. 9347 // If the header has a unique predecessor outside the loop, it must be 9348 // a block that has exactly one successor that can reach the loop. 9349 if (const Loop *L = LI.getLoopFor(BB)) 9350 return {L->getLoopPredecessor(), L->getHeader()}; 9351 9352 return {nullptr, nullptr}; 9353 } 9354 9355 /// SCEV structural equivalence is usually sufficient for testing whether two 9356 /// expressions are equal, however for the purposes of looking for a condition 9357 /// guarding a loop, it can be useful to be a little more general, since a 9358 /// front-end may have replicated the controlling expression. 9359 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9360 // Quick check to see if they are the same SCEV. 9361 if (A == B) return true; 9362 9363 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9364 // Not all instructions that are "identical" compute the same value. For 9365 // instance, two distinct alloca instructions allocating the same type are 9366 // identical and do not read memory; but compute distinct values. 9367 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9368 }; 9369 9370 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9371 // two different instructions with the same value. Check for this case. 9372 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9373 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9374 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9375 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9376 if (ComputesEqualValues(AI, BI)) 9377 return true; 9378 9379 // Otherwise assume they may have a different value. 9380 return false; 9381 } 9382 9383 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9384 const SCEV *&LHS, const SCEV *&RHS, 9385 unsigned Depth) { 9386 bool Changed = false; 9387 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9388 // '0 != 0'. 9389 auto TrivialCase = [&](bool TriviallyTrue) { 9390 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9391 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9392 return true; 9393 }; 9394 // If we hit the max recursion limit bail out. 9395 if (Depth >= 3) 9396 return false; 9397 9398 // Canonicalize a constant to the right side. 9399 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9400 // Check for both operands constant. 9401 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9402 if (ConstantExpr::getICmp(Pred, 9403 LHSC->getValue(), 9404 RHSC->getValue())->isNullValue()) 9405 return TrivialCase(false); 9406 else 9407 return TrivialCase(true); 9408 } 9409 // Otherwise swap the operands to put the constant on the right. 9410 std::swap(LHS, RHS); 9411 Pred = ICmpInst::getSwappedPredicate(Pred); 9412 Changed = true; 9413 } 9414 9415 // If we're comparing an addrec with a value which is loop-invariant in the 9416 // addrec's loop, put the addrec on the left. Also make a dominance check, 9417 // as both operands could be addrecs loop-invariant in each other's loop. 9418 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9419 const Loop *L = AR->getLoop(); 9420 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9421 std::swap(LHS, RHS); 9422 Pred = ICmpInst::getSwappedPredicate(Pred); 9423 Changed = true; 9424 } 9425 } 9426 9427 // If there's a constant operand, canonicalize comparisons with boundary 9428 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9429 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9430 const APInt &RA = RC->getAPInt(); 9431 9432 bool SimplifiedByConstantRange = false; 9433 9434 if (!ICmpInst::isEquality(Pred)) { 9435 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9436 if (ExactCR.isFullSet()) 9437 return TrivialCase(true); 9438 else if (ExactCR.isEmptySet()) 9439 return TrivialCase(false); 9440 9441 APInt NewRHS; 9442 CmpInst::Predicate NewPred; 9443 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9444 ICmpInst::isEquality(NewPred)) { 9445 // We were able to convert an inequality to an equality. 9446 Pred = NewPred; 9447 RHS = getConstant(NewRHS); 9448 Changed = SimplifiedByConstantRange = true; 9449 } 9450 } 9451 9452 if (!SimplifiedByConstantRange) { 9453 switch (Pred) { 9454 default: 9455 break; 9456 case ICmpInst::ICMP_EQ: 9457 case ICmpInst::ICMP_NE: 9458 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9459 if (!RA) 9460 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9461 if (const SCEVMulExpr *ME = 9462 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9463 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9464 ME->getOperand(0)->isAllOnesValue()) { 9465 RHS = AE->getOperand(1); 9466 LHS = ME->getOperand(1); 9467 Changed = true; 9468 } 9469 break; 9470 9471 9472 // The "Should have been caught earlier!" messages refer to the fact 9473 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9474 // should have fired on the corresponding cases, and canonicalized the 9475 // check to trivial case. 9476 9477 case ICmpInst::ICMP_UGE: 9478 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9479 Pred = ICmpInst::ICMP_UGT; 9480 RHS = getConstant(RA - 1); 9481 Changed = true; 9482 break; 9483 case ICmpInst::ICMP_ULE: 9484 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9485 Pred = ICmpInst::ICMP_ULT; 9486 RHS = getConstant(RA + 1); 9487 Changed = true; 9488 break; 9489 case ICmpInst::ICMP_SGE: 9490 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9491 Pred = ICmpInst::ICMP_SGT; 9492 RHS = getConstant(RA - 1); 9493 Changed = true; 9494 break; 9495 case ICmpInst::ICMP_SLE: 9496 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9497 Pred = ICmpInst::ICMP_SLT; 9498 RHS = getConstant(RA + 1); 9499 Changed = true; 9500 break; 9501 } 9502 } 9503 } 9504 9505 // Check for obvious equality. 9506 if (HasSameValue(LHS, RHS)) { 9507 if (ICmpInst::isTrueWhenEqual(Pred)) 9508 return TrivialCase(true); 9509 if (ICmpInst::isFalseWhenEqual(Pred)) 9510 return TrivialCase(false); 9511 } 9512 9513 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9514 // adding or subtracting 1 from one of the operands. 9515 switch (Pred) { 9516 case ICmpInst::ICMP_SLE: 9517 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9518 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9519 SCEV::FlagNSW); 9520 Pred = ICmpInst::ICMP_SLT; 9521 Changed = true; 9522 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9523 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9524 SCEV::FlagNSW); 9525 Pred = ICmpInst::ICMP_SLT; 9526 Changed = true; 9527 } 9528 break; 9529 case ICmpInst::ICMP_SGE: 9530 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9531 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9532 SCEV::FlagNSW); 9533 Pred = ICmpInst::ICMP_SGT; 9534 Changed = true; 9535 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9536 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9537 SCEV::FlagNSW); 9538 Pred = ICmpInst::ICMP_SGT; 9539 Changed = true; 9540 } 9541 break; 9542 case ICmpInst::ICMP_ULE: 9543 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9544 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9545 SCEV::FlagNUW); 9546 Pred = ICmpInst::ICMP_ULT; 9547 Changed = true; 9548 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9549 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9550 Pred = ICmpInst::ICMP_ULT; 9551 Changed = true; 9552 } 9553 break; 9554 case ICmpInst::ICMP_UGE: 9555 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9556 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9557 Pred = ICmpInst::ICMP_UGT; 9558 Changed = true; 9559 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9560 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9561 SCEV::FlagNUW); 9562 Pred = ICmpInst::ICMP_UGT; 9563 Changed = true; 9564 } 9565 break; 9566 default: 9567 break; 9568 } 9569 9570 // TODO: More simplifications are possible here. 9571 9572 // Recursively simplify until we either hit a recursion limit or nothing 9573 // changes. 9574 if (Changed) 9575 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9576 9577 return Changed; 9578 } 9579 9580 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9581 return getSignedRangeMax(S).isNegative(); 9582 } 9583 9584 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9585 return getSignedRangeMin(S).isStrictlyPositive(); 9586 } 9587 9588 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9589 return !getSignedRangeMin(S).isNegative(); 9590 } 9591 9592 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9593 return !getSignedRangeMax(S).isStrictlyPositive(); 9594 } 9595 9596 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9597 return isKnownNegative(S) || isKnownPositive(S); 9598 } 9599 9600 std::pair<const SCEV *, const SCEV *> 9601 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9602 // Compute SCEV on entry of loop L. 9603 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9604 if (Start == getCouldNotCompute()) 9605 return { Start, Start }; 9606 // Compute post increment SCEV for loop L. 9607 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9608 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9609 return { Start, PostInc }; 9610 } 9611 9612 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9613 const SCEV *LHS, const SCEV *RHS) { 9614 // First collect all loops. 9615 SmallPtrSet<const Loop *, 8> LoopsUsed; 9616 getUsedLoops(LHS, LoopsUsed); 9617 getUsedLoops(RHS, LoopsUsed); 9618 9619 if (LoopsUsed.empty()) 9620 return false; 9621 9622 // Domination relationship must be a linear order on collected loops. 9623 #ifndef NDEBUG 9624 for (auto *L1 : LoopsUsed) 9625 for (auto *L2 : LoopsUsed) 9626 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9627 DT.dominates(L2->getHeader(), L1->getHeader())) && 9628 "Domination relationship is not a linear order"); 9629 #endif 9630 9631 const Loop *MDL = 9632 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9633 [&](const Loop *L1, const Loop *L2) { 9634 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9635 }); 9636 9637 // Get init and post increment value for LHS. 9638 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9639 // if LHS contains unknown non-invariant SCEV then bail out. 9640 if (SplitLHS.first == getCouldNotCompute()) 9641 return false; 9642 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9643 // Get init and post increment value for RHS. 9644 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9645 // if RHS contains unknown non-invariant SCEV then bail out. 9646 if (SplitRHS.first == getCouldNotCompute()) 9647 return false; 9648 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9649 // It is possible that init SCEV contains an invariant load but it does 9650 // not dominate MDL and is not available at MDL loop entry, so we should 9651 // check it here. 9652 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9653 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9654 return false; 9655 9656 // It seems backedge guard check is faster than entry one so in some cases 9657 // it can speed up whole estimation by short circuit 9658 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9659 SplitRHS.second) && 9660 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9661 } 9662 9663 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9664 const SCEV *LHS, const SCEV *RHS) { 9665 // Canonicalize the inputs first. 9666 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9667 9668 if (isKnownViaInduction(Pred, LHS, RHS)) 9669 return true; 9670 9671 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9672 return true; 9673 9674 // Otherwise see what can be done with some simple reasoning. 9675 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9676 } 9677 9678 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 9679 const SCEV *LHS, 9680 const SCEV *RHS) { 9681 if (isKnownPredicate(Pred, LHS, RHS)) 9682 return true; 9683 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 9684 return false; 9685 return None; 9686 } 9687 9688 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9689 const SCEV *LHS, const SCEV *RHS, 9690 const Instruction *Context) { 9691 // TODO: Analyze guards and assumes from Context's block. 9692 return isKnownPredicate(Pred, LHS, RHS) || 9693 isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS); 9694 } 9695 9696 Optional<bool> 9697 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS, 9698 const SCEV *RHS, 9699 const Instruction *Context) { 9700 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 9701 if (KnownWithoutContext) 9702 return KnownWithoutContext; 9703 9704 if (isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS)) 9705 return true; 9706 else if (isBasicBlockEntryGuardedByCond(Context->getParent(), 9707 ICmpInst::getInversePredicate(Pred), 9708 LHS, RHS)) 9709 return false; 9710 return None; 9711 } 9712 9713 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9714 const SCEVAddRecExpr *LHS, 9715 const SCEV *RHS) { 9716 const Loop *L = LHS->getLoop(); 9717 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9718 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9719 } 9720 9721 Optional<ScalarEvolution::MonotonicPredicateType> 9722 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 9723 ICmpInst::Predicate Pred) { 9724 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 9725 9726 #ifndef NDEBUG 9727 // Verify an invariant: inverting the predicate should turn a monotonically 9728 // increasing change to a monotonically decreasing one, and vice versa. 9729 if (Result) { 9730 auto ResultSwapped = 9731 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 9732 9733 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 9734 assert(ResultSwapped.getValue() != Result.getValue() && 9735 "monotonicity should flip as we flip the predicate"); 9736 } 9737 #endif 9738 9739 return Result; 9740 } 9741 9742 Optional<ScalarEvolution::MonotonicPredicateType> 9743 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 9744 ICmpInst::Predicate Pred) { 9745 // A zero step value for LHS means the induction variable is essentially a 9746 // loop invariant value. We don't really depend on the predicate actually 9747 // flipping from false to true (for increasing predicates, and the other way 9748 // around for decreasing predicates), all we care about is that *if* the 9749 // predicate changes then it only changes from false to true. 9750 // 9751 // A zero step value in itself is not very useful, but there may be places 9752 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9753 // as general as possible. 9754 9755 // Only handle LE/LT/GE/GT predicates. 9756 if (!ICmpInst::isRelational(Pred)) 9757 return None; 9758 9759 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 9760 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 9761 "Should be greater or less!"); 9762 9763 // Check that AR does not wrap. 9764 if (ICmpInst::isUnsigned(Pred)) { 9765 if (!LHS->hasNoUnsignedWrap()) 9766 return None; 9767 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9768 } else { 9769 assert(ICmpInst::isSigned(Pred) && 9770 "Relational predicate is either signed or unsigned!"); 9771 if (!LHS->hasNoSignedWrap()) 9772 return None; 9773 9774 const SCEV *Step = LHS->getStepRecurrence(*this); 9775 9776 if (isKnownNonNegative(Step)) 9777 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9778 9779 if (isKnownNonPositive(Step)) 9780 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9781 9782 return None; 9783 } 9784 } 9785 9786 Optional<ScalarEvolution::LoopInvariantPredicate> 9787 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 9788 const SCEV *LHS, const SCEV *RHS, 9789 const Loop *L) { 9790 9791 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9792 if (!isLoopInvariant(RHS, L)) { 9793 if (!isLoopInvariant(LHS, L)) 9794 return None; 9795 9796 std::swap(LHS, RHS); 9797 Pred = ICmpInst::getSwappedPredicate(Pred); 9798 } 9799 9800 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9801 if (!ArLHS || ArLHS->getLoop() != L) 9802 return None; 9803 9804 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 9805 if (!MonotonicType) 9806 return None; 9807 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9808 // true as the loop iterates, and the backedge is control dependent on 9809 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9810 // 9811 // * if the predicate was false in the first iteration then the predicate 9812 // is never evaluated again, since the loop exits without taking the 9813 // backedge. 9814 // * if the predicate was true in the first iteration then it will 9815 // continue to be true for all future iterations since it is 9816 // monotonically increasing. 9817 // 9818 // For both the above possibilities, we can replace the loop varying 9819 // predicate with its value on the first iteration of the loop (which is 9820 // loop invariant). 9821 // 9822 // A similar reasoning applies for a monotonically decreasing predicate, by 9823 // replacing true with false and false with true in the above two bullets. 9824 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 9825 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9826 9827 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9828 return None; 9829 9830 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 9831 } 9832 9833 Optional<ScalarEvolution::LoopInvariantPredicate> 9834 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 9835 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9836 const Instruction *Context, const SCEV *MaxIter) { 9837 // Try to prove the following set of facts: 9838 // - The predicate is monotonic in the iteration space. 9839 // - If the check does not fail on the 1st iteration: 9840 // - No overflow will happen during first MaxIter iterations; 9841 // - It will not fail on the MaxIter'th iteration. 9842 // If the check does fail on the 1st iteration, we leave the loop and no 9843 // other checks matter. 9844 9845 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9846 if (!isLoopInvariant(RHS, L)) { 9847 if (!isLoopInvariant(LHS, L)) 9848 return None; 9849 9850 std::swap(LHS, RHS); 9851 Pred = ICmpInst::getSwappedPredicate(Pred); 9852 } 9853 9854 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 9855 if (!AR || AR->getLoop() != L) 9856 return None; 9857 9858 // The predicate must be relational (i.e. <, <=, >=, >). 9859 if (!ICmpInst::isRelational(Pred)) 9860 return None; 9861 9862 // TODO: Support steps other than +/- 1. 9863 const SCEV *Step = AR->getStepRecurrence(*this); 9864 auto *One = getOne(Step->getType()); 9865 auto *MinusOne = getNegativeSCEV(One); 9866 if (Step != One && Step != MinusOne) 9867 return None; 9868 9869 // Type mismatch here means that MaxIter is potentially larger than max 9870 // unsigned value in start type, which mean we cannot prove no wrap for the 9871 // indvar. 9872 if (AR->getType() != MaxIter->getType()) 9873 return None; 9874 9875 // Value of IV on suggested last iteration. 9876 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 9877 // Does it still meet the requirement? 9878 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 9879 return None; 9880 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 9881 // not exceed max unsigned value of this type), this effectively proves 9882 // that there is no wrap during the iteration. To prove that there is no 9883 // signed/unsigned wrap, we need to check that 9884 // Start <= Last for step = 1 or Start >= Last for step = -1. 9885 ICmpInst::Predicate NoOverflowPred = 9886 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 9887 if (Step == MinusOne) 9888 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 9889 const SCEV *Start = AR->getStart(); 9890 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context)) 9891 return None; 9892 9893 // Everything is fine. 9894 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 9895 } 9896 9897 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9898 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9899 if (HasSameValue(LHS, RHS)) 9900 return ICmpInst::isTrueWhenEqual(Pred); 9901 9902 // This code is split out from isKnownPredicate because it is called from 9903 // within isLoopEntryGuardedByCond. 9904 9905 auto CheckRanges = [&](const ConstantRange &RangeLHS, 9906 const ConstantRange &RangeRHS) { 9907 return RangeLHS.icmp(Pred, RangeRHS); 9908 }; 9909 9910 // The check at the top of the function catches the case where the values are 9911 // known to be equal. 9912 if (Pred == CmpInst::ICMP_EQ) 9913 return false; 9914 9915 if (Pred == CmpInst::ICMP_NE) 9916 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9917 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9918 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9919 9920 if (CmpInst::isSigned(Pred)) 9921 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9922 9923 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9924 } 9925 9926 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9927 const SCEV *LHS, 9928 const SCEV *RHS) { 9929 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9930 // Return Y via OutY. 9931 auto MatchBinaryAddToConst = 9932 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9933 SCEV::NoWrapFlags ExpectedFlags) { 9934 const SCEV *NonConstOp, *ConstOp; 9935 SCEV::NoWrapFlags FlagsPresent; 9936 9937 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9938 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9939 return false; 9940 9941 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9942 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9943 }; 9944 9945 APInt C; 9946 9947 switch (Pred) { 9948 default: 9949 break; 9950 9951 case ICmpInst::ICMP_SGE: 9952 std::swap(LHS, RHS); 9953 LLVM_FALLTHROUGH; 9954 case ICmpInst::ICMP_SLE: 9955 // X s<= (X + C)<nsw> if C >= 0 9956 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9957 return true; 9958 9959 // (X + C)<nsw> s<= X if C <= 0 9960 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9961 !C.isStrictlyPositive()) 9962 return true; 9963 break; 9964 9965 case ICmpInst::ICMP_SGT: 9966 std::swap(LHS, RHS); 9967 LLVM_FALLTHROUGH; 9968 case ICmpInst::ICMP_SLT: 9969 // X s< (X + C)<nsw> if C > 0 9970 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9971 C.isStrictlyPositive()) 9972 return true; 9973 9974 // (X + C)<nsw> s< X if C < 0 9975 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9976 return true; 9977 break; 9978 9979 case ICmpInst::ICMP_UGE: 9980 std::swap(LHS, RHS); 9981 LLVM_FALLTHROUGH; 9982 case ICmpInst::ICMP_ULE: 9983 // X u<= (X + C)<nuw> for any C 9984 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW)) 9985 return true; 9986 break; 9987 9988 case ICmpInst::ICMP_UGT: 9989 std::swap(LHS, RHS); 9990 LLVM_FALLTHROUGH; 9991 case ICmpInst::ICMP_ULT: 9992 // X u< (X + C)<nuw> if C != 0 9993 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue()) 9994 return true; 9995 break; 9996 } 9997 9998 return false; 9999 } 10000 10001 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10002 const SCEV *LHS, 10003 const SCEV *RHS) { 10004 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10005 return false; 10006 10007 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10008 // the stack can result in exponential time complexity. 10009 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10010 10011 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10012 // 10013 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10014 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10015 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10016 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10017 // use isKnownPredicate later if needed. 10018 return isKnownNonNegative(RHS) && 10019 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10020 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10021 } 10022 10023 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10024 ICmpInst::Predicate Pred, 10025 const SCEV *LHS, const SCEV *RHS) { 10026 // No need to even try if we know the module has no guards. 10027 if (!HasGuards) 10028 return false; 10029 10030 return any_of(*BB, [&](const Instruction &I) { 10031 using namespace llvm::PatternMatch; 10032 10033 Value *Condition; 10034 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10035 m_Value(Condition))) && 10036 isImpliedCond(Pred, LHS, RHS, Condition, false); 10037 }); 10038 } 10039 10040 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10041 /// protected by a conditional between LHS and RHS. This is used to 10042 /// to eliminate casts. 10043 bool 10044 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10045 ICmpInst::Predicate Pred, 10046 const SCEV *LHS, const SCEV *RHS) { 10047 // Interpret a null as meaning no loop, where there is obviously no guard 10048 // (interprocedural conditions notwithstanding). 10049 if (!L) return true; 10050 10051 if (VerifyIR) 10052 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10053 "This cannot be done on broken IR!"); 10054 10055 10056 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10057 return true; 10058 10059 BasicBlock *Latch = L->getLoopLatch(); 10060 if (!Latch) 10061 return false; 10062 10063 BranchInst *LoopContinuePredicate = 10064 dyn_cast<BranchInst>(Latch->getTerminator()); 10065 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10066 isImpliedCond(Pred, LHS, RHS, 10067 LoopContinuePredicate->getCondition(), 10068 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10069 return true; 10070 10071 // We don't want more than one activation of the following loops on the stack 10072 // -- that can lead to O(n!) time complexity. 10073 if (WalkingBEDominatingConds) 10074 return false; 10075 10076 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10077 10078 // See if we can exploit a trip count to prove the predicate. 10079 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10080 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10081 if (LatchBECount != getCouldNotCompute()) { 10082 // We know that Latch branches back to the loop header exactly 10083 // LatchBECount times. This means the backdege condition at Latch is 10084 // equivalent to "{0,+,1} u< LatchBECount". 10085 Type *Ty = LatchBECount->getType(); 10086 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10087 const SCEV *LoopCounter = 10088 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10089 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10090 LatchBECount)) 10091 return true; 10092 } 10093 10094 // Check conditions due to any @llvm.assume intrinsics. 10095 for (auto &AssumeVH : AC.assumptions()) { 10096 if (!AssumeVH) 10097 continue; 10098 auto *CI = cast<CallInst>(AssumeVH); 10099 if (!DT.dominates(CI, Latch->getTerminator())) 10100 continue; 10101 10102 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10103 return true; 10104 } 10105 10106 // If the loop is not reachable from the entry block, we risk running into an 10107 // infinite loop as we walk up into the dom tree. These loops do not matter 10108 // anyway, so we just return a conservative answer when we see them. 10109 if (!DT.isReachableFromEntry(L->getHeader())) 10110 return false; 10111 10112 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10113 return true; 10114 10115 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10116 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10117 assert(DTN && "should reach the loop header before reaching the root!"); 10118 10119 BasicBlock *BB = DTN->getBlock(); 10120 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10121 return true; 10122 10123 BasicBlock *PBB = BB->getSinglePredecessor(); 10124 if (!PBB) 10125 continue; 10126 10127 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10128 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10129 continue; 10130 10131 Value *Condition = ContinuePredicate->getCondition(); 10132 10133 // If we have an edge `E` within the loop body that dominates the only 10134 // latch, the condition guarding `E` also guards the backedge. This 10135 // reasoning works only for loops with a single latch. 10136 10137 BasicBlockEdge DominatingEdge(PBB, BB); 10138 if (DominatingEdge.isSingleEdge()) { 10139 // We're constructively (and conservatively) enumerating edges within the 10140 // loop body that dominate the latch. The dominator tree better agree 10141 // with us on this: 10142 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10143 10144 if (isImpliedCond(Pred, LHS, RHS, Condition, 10145 BB != ContinuePredicate->getSuccessor(0))) 10146 return true; 10147 } 10148 } 10149 10150 return false; 10151 } 10152 10153 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10154 ICmpInst::Predicate Pred, 10155 const SCEV *LHS, 10156 const SCEV *RHS) { 10157 if (VerifyIR) 10158 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10159 "This cannot be done on broken IR!"); 10160 10161 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10162 // the facts (a >= b && a != b) separately. A typical situation is when the 10163 // non-strict comparison is known from ranges and non-equality is known from 10164 // dominating predicates. If we are proving strict comparison, we always try 10165 // to prove non-equality and non-strict comparison separately. 10166 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10167 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10168 bool ProvedNonStrictComparison = false; 10169 bool ProvedNonEquality = false; 10170 10171 auto SplitAndProve = 10172 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10173 if (!ProvedNonStrictComparison) 10174 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10175 if (!ProvedNonEquality) 10176 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10177 if (ProvedNonStrictComparison && ProvedNonEquality) 10178 return true; 10179 return false; 10180 }; 10181 10182 if (ProvingStrictComparison) { 10183 auto ProofFn = [&](ICmpInst::Predicate P) { 10184 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10185 }; 10186 if (SplitAndProve(ProofFn)) 10187 return true; 10188 } 10189 10190 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10191 auto ProveViaGuard = [&](const BasicBlock *Block) { 10192 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10193 return true; 10194 if (ProvingStrictComparison) { 10195 auto ProofFn = [&](ICmpInst::Predicate P) { 10196 return isImpliedViaGuard(Block, P, LHS, RHS); 10197 }; 10198 if (SplitAndProve(ProofFn)) 10199 return true; 10200 } 10201 return false; 10202 }; 10203 10204 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10205 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10206 const Instruction *Context = &BB->front(); 10207 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context)) 10208 return true; 10209 if (ProvingStrictComparison) { 10210 auto ProofFn = [&](ICmpInst::Predicate P) { 10211 return isImpliedCond(P, LHS, RHS, Condition, Inverse, Context); 10212 }; 10213 if (SplitAndProve(ProofFn)) 10214 return true; 10215 } 10216 return false; 10217 }; 10218 10219 // Starting at the block's predecessor, climb up the predecessor chain, as long 10220 // as there are predecessors that can be found that have unique successors 10221 // leading to the original block. 10222 const Loop *ContainingLoop = LI.getLoopFor(BB); 10223 const BasicBlock *PredBB; 10224 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10225 PredBB = ContainingLoop->getLoopPredecessor(); 10226 else 10227 PredBB = BB->getSinglePredecessor(); 10228 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10229 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10230 if (ProveViaGuard(Pair.first)) 10231 return true; 10232 10233 const BranchInst *LoopEntryPredicate = 10234 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10235 if (!LoopEntryPredicate || 10236 LoopEntryPredicate->isUnconditional()) 10237 continue; 10238 10239 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10240 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10241 return true; 10242 } 10243 10244 // Check conditions due to any @llvm.assume intrinsics. 10245 for (auto &AssumeVH : AC.assumptions()) { 10246 if (!AssumeVH) 10247 continue; 10248 auto *CI = cast<CallInst>(AssumeVH); 10249 if (!DT.dominates(CI, BB)) 10250 continue; 10251 10252 if (ProveViaCond(CI->getArgOperand(0), false)) 10253 return true; 10254 } 10255 10256 return false; 10257 } 10258 10259 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10260 ICmpInst::Predicate Pred, 10261 const SCEV *LHS, 10262 const SCEV *RHS) { 10263 // Interpret a null as meaning no loop, where there is obviously no guard 10264 // (interprocedural conditions notwithstanding). 10265 if (!L) 10266 return false; 10267 10268 // Both LHS and RHS must be available at loop entry. 10269 assert(isAvailableAtLoopEntry(LHS, L) && 10270 "LHS is not available at Loop Entry"); 10271 assert(isAvailableAtLoopEntry(RHS, L) && 10272 "RHS is not available at Loop Entry"); 10273 10274 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10275 return true; 10276 10277 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10278 } 10279 10280 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10281 const SCEV *RHS, 10282 const Value *FoundCondValue, bool Inverse, 10283 const Instruction *Context) { 10284 // False conditions implies anything. Do not bother analyzing it further. 10285 if (FoundCondValue == 10286 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 10287 return true; 10288 10289 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10290 return false; 10291 10292 auto ClearOnExit = 10293 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10294 10295 // Recursively handle And and Or conditions. 10296 const Value *Op0, *Op1; 10297 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 10298 if (!Inverse) 10299 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) || 10300 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context); 10301 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 10302 if (Inverse) 10303 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) || 10304 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context); 10305 } 10306 10307 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10308 if (!ICI) return false; 10309 10310 // Now that we found a conditional branch that dominates the loop or controls 10311 // the loop latch. Check to see if it is the comparison we are looking for. 10312 ICmpInst::Predicate FoundPred; 10313 if (Inverse) 10314 FoundPred = ICI->getInversePredicate(); 10315 else 10316 FoundPred = ICI->getPredicate(); 10317 10318 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10319 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10320 10321 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context); 10322 } 10323 10324 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10325 const SCEV *RHS, 10326 ICmpInst::Predicate FoundPred, 10327 const SCEV *FoundLHS, const SCEV *FoundRHS, 10328 const Instruction *Context) { 10329 // Balance the types. 10330 if (getTypeSizeInBits(LHS->getType()) < 10331 getTypeSizeInBits(FoundLHS->getType())) { 10332 // For unsigned and equality predicates, try to prove that both found 10333 // operands fit into narrow unsigned range. If so, try to prove facts in 10334 // narrow types. 10335 if (!CmpInst::isSigned(FoundPred)) { 10336 auto *NarrowType = LHS->getType(); 10337 auto *WideType = FoundLHS->getType(); 10338 auto BitWidth = getTypeSizeInBits(NarrowType); 10339 const SCEV *MaxValue = getZeroExtendExpr( 10340 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10341 if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) && 10342 isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) { 10343 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10344 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10345 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10346 TruncFoundRHS, Context)) 10347 return true; 10348 } 10349 } 10350 10351 if (CmpInst::isSigned(Pred)) { 10352 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10353 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10354 } else { 10355 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10356 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10357 } 10358 } else if (getTypeSizeInBits(LHS->getType()) > 10359 getTypeSizeInBits(FoundLHS->getType())) { 10360 if (CmpInst::isSigned(FoundPred)) { 10361 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10362 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10363 } else { 10364 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10365 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10366 } 10367 } 10368 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10369 FoundRHS, Context); 10370 } 10371 10372 bool ScalarEvolution::isImpliedCondBalancedTypes( 10373 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10374 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10375 const Instruction *Context) { 10376 assert(getTypeSizeInBits(LHS->getType()) == 10377 getTypeSizeInBits(FoundLHS->getType()) && 10378 "Types should be balanced!"); 10379 // Canonicalize the query to match the way instcombine will have 10380 // canonicalized the comparison. 10381 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10382 if (LHS == RHS) 10383 return CmpInst::isTrueWhenEqual(Pred); 10384 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10385 if (FoundLHS == FoundRHS) 10386 return CmpInst::isFalseWhenEqual(FoundPred); 10387 10388 // Check to see if we can make the LHS or RHS match. 10389 if (LHS == FoundRHS || RHS == FoundLHS) { 10390 if (isa<SCEVConstant>(RHS)) { 10391 std::swap(FoundLHS, FoundRHS); 10392 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10393 } else { 10394 std::swap(LHS, RHS); 10395 Pred = ICmpInst::getSwappedPredicate(Pred); 10396 } 10397 } 10398 10399 // Check whether the found predicate is the same as the desired predicate. 10400 if (FoundPred == Pred) 10401 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10402 10403 // Check whether swapping the found predicate makes it the same as the 10404 // desired predicate. 10405 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 10406 // We can write the implication 10407 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 10408 // using one of the following ways: 10409 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 10410 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 10411 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 10412 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 10413 // Forms 1. and 2. require swapping the operands of one condition. Don't 10414 // do this if it would break canonical constant/addrec ordering. 10415 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 10416 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 10417 Context); 10418 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 10419 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context); 10420 10421 // There's no clear preference between forms 3. and 4., try both. 10422 return isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 10423 FoundLHS, FoundRHS, Context) || 10424 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 10425 getNotSCEV(FoundRHS), Context); 10426 } 10427 10428 // Unsigned comparison is the same as signed comparison when both the operands 10429 // are non-negative. 10430 if (CmpInst::isUnsigned(FoundPred) && 10431 CmpInst::getSignedPredicate(FoundPred) == Pred && 10432 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 10433 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10434 10435 // Check if we can make progress by sharpening ranges. 10436 if (FoundPred == ICmpInst::ICMP_NE && 10437 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 10438 10439 const SCEVConstant *C = nullptr; 10440 const SCEV *V = nullptr; 10441 10442 if (isa<SCEVConstant>(FoundLHS)) { 10443 C = cast<SCEVConstant>(FoundLHS); 10444 V = FoundRHS; 10445 } else { 10446 C = cast<SCEVConstant>(FoundRHS); 10447 V = FoundLHS; 10448 } 10449 10450 // The guarding predicate tells us that C != V. If the known range 10451 // of V is [C, t), we can sharpen the range to [C + 1, t). The 10452 // range we consider has to correspond to same signedness as the 10453 // predicate we're interested in folding. 10454 10455 APInt Min = ICmpInst::isSigned(Pred) ? 10456 getSignedRangeMin(V) : getUnsignedRangeMin(V); 10457 10458 if (Min == C->getAPInt()) { 10459 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 10460 // This is true even if (Min + 1) wraps around -- in case of 10461 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 10462 10463 APInt SharperMin = Min + 1; 10464 10465 switch (Pred) { 10466 case ICmpInst::ICMP_SGE: 10467 case ICmpInst::ICMP_UGE: 10468 // We know V `Pred` SharperMin. If this implies LHS `Pred` 10469 // RHS, we're done. 10470 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 10471 Context)) 10472 return true; 10473 LLVM_FALLTHROUGH; 10474 10475 case ICmpInst::ICMP_SGT: 10476 case ICmpInst::ICMP_UGT: 10477 // We know from the range information that (V `Pred` Min || 10478 // V == Min). We know from the guarding condition that !(V 10479 // == Min). This gives us 10480 // 10481 // V `Pred` Min || V == Min && !(V == Min) 10482 // => V `Pred` Min 10483 // 10484 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 10485 10486 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), 10487 Context)) 10488 return true; 10489 break; 10490 10491 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 10492 case ICmpInst::ICMP_SLE: 10493 case ICmpInst::ICMP_ULE: 10494 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10495 LHS, V, getConstant(SharperMin), Context)) 10496 return true; 10497 LLVM_FALLTHROUGH; 10498 10499 case ICmpInst::ICMP_SLT: 10500 case ICmpInst::ICMP_ULT: 10501 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10502 LHS, V, getConstant(Min), Context)) 10503 return true; 10504 break; 10505 10506 default: 10507 // No change 10508 break; 10509 } 10510 } 10511 } 10512 10513 // Check whether the actual condition is beyond sufficient. 10514 if (FoundPred == ICmpInst::ICMP_EQ) 10515 if (ICmpInst::isTrueWhenEqual(Pred)) 10516 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context)) 10517 return true; 10518 if (Pred == ICmpInst::ICMP_NE) 10519 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 10520 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, 10521 Context)) 10522 return true; 10523 10524 // Otherwise assume the worst. 10525 return false; 10526 } 10527 10528 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 10529 const SCEV *&L, const SCEV *&R, 10530 SCEV::NoWrapFlags &Flags) { 10531 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 10532 if (!AE || AE->getNumOperands() != 2) 10533 return false; 10534 10535 L = AE->getOperand(0); 10536 R = AE->getOperand(1); 10537 Flags = AE->getNoWrapFlags(); 10538 return true; 10539 } 10540 10541 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 10542 const SCEV *Less) { 10543 // We avoid subtracting expressions here because this function is usually 10544 // fairly deep in the call stack (i.e. is called many times). 10545 10546 // X - X = 0. 10547 if (More == Less) 10548 return APInt(getTypeSizeInBits(More->getType()), 0); 10549 10550 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 10551 const auto *LAR = cast<SCEVAddRecExpr>(Less); 10552 const auto *MAR = cast<SCEVAddRecExpr>(More); 10553 10554 if (LAR->getLoop() != MAR->getLoop()) 10555 return None; 10556 10557 // We look at affine expressions only; not for correctness but to keep 10558 // getStepRecurrence cheap. 10559 if (!LAR->isAffine() || !MAR->isAffine()) 10560 return None; 10561 10562 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 10563 return None; 10564 10565 Less = LAR->getStart(); 10566 More = MAR->getStart(); 10567 10568 // fall through 10569 } 10570 10571 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10572 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10573 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10574 return M - L; 10575 } 10576 10577 SCEV::NoWrapFlags Flags; 10578 const SCEV *LLess = nullptr, *RLess = nullptr; 10579 const SCEV *LMore = nullptr, *RMore = nullptr; 10580 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10581 // Compare (X + C1) vs X. 10582 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10583 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10584 if (RLess == More) 10585 return -(C1->getAPInt()); 10586 10587 // Compare X vs (X + C2). 10588 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10589 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10590 if (RMore == Less) 10591 return C2->getAPInt(); 10592 10593 // Compare (X + C1) vs (X + C2). 10594 if (C1 && C2 && RLess == RMore) 10595 return C2->getAPInt() - C1->getAPInt(); 10596 10597 return None; 10598 } 10599 10600 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10601 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10602 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) { 10603 // Try to recognize the following pattern: 10604 // 10605 // FoundRHS = ... 10606 // ... 10607 // loop: 10608 // FoundLHS = {Start,+,W} 10609 // context_bb: // Basic block from the same loop 10610 // known(Pred, FoundLHS, FoundRHS) 10611 // 10612 // If some predicate is known in the context of a loop, it is also known on 10613 // each iteration of this loop, including the first iteration. Therefore, in 10614 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10615 // prove the original pred using this fact. 10616 if (!Context) 10617 return false; 10618 const BasicBlock *ContextBB = Context->getParent(); 10619 // Make sure AR varies in the context block. 10620 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10621 const Loop *L = AR->getLoop(); 10622 // Make sure that context belongs to the loop and executes on 1st iteration 10623 // (if it ever executes at all). 10624 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10625 return false; 10626 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10627 return false; 10628 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10629 } 10630 10631 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10632 const Loop *L = AR->getLoop(); 10633 // Make sure that context belongs to the loop and executes on 1st iteration 10634 // (if it ever executes at all). 10635 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10636 return false; 10637 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10638 return false; 10639 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10640 } 10641 10642 return false; 10643 } 10644 10645 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10646 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10647 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10648 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10649 return false; 10650 10651 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10652 if (!AddRecLHS) 10653 return false; 10654 10655 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10656 if (!AddRecFoundLHS) 10657 return false; 10658 10659 // We'd like to let SCEV reason about control dependencies, so we constrain 10660 // both the inequalities to be about add recurrences on the same loop. This 10661 // way we can use isLoopEntryGuardedByCond later. 10662 10663 const Loop *L = AddRecFoundLHS->getLoop(); 10664 if (L != AddRecLHS->getLoop()) 10665 return false; 10666 10667 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10668 // 10669 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10670 // ... (2) 10671 // 10672 // Informal proof for (2), assuming (1) [*]: 10673 // 10674 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10675 // 10676 // Then 10677 // 10678 // FoundLHS s< FoundRHS s< INT_MIN - C 10679 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10680 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10681 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10682 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10683 // <=> FoundLHS + C s< FoundRHS + C 10684 // 10685 // [*]: (1) can be proved by ruling out overflow. 10686 // 10687 // [**]: This can be proved by analyzing all the four possibilities: 10688 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10689 // (A s>= 0, B s>= 0). 10690 // 10691 // Note: 10692 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10693 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10694 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10695 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10696 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10697 // C)". 10698 10699 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10700 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10701 if (!LDiff || !RDiff || *LDiff != *RDiff) 10702 return false; 10703 10704 if (LDiff->isMinValue()) 10705 return true; 10706 10707 APInt FoundRHSLimit; 10708 10709 if (Pred == CmpInst::ICMP_ULT) { 10710 FoundRHSLimit = -(*RDiff); 10711 } else { 10712 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10713 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10714 } 10715 10716 // Try to prove (1) or (2), as needed. 10717 return isAvailableAtLoopEntry(FoundRHS, L) && 10718 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10719 getConstant(FoundRHSLimit)); 10720 } 10721 10722 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10723 const SCEV *LHS, const SCEV *RHS, 10724 const SCEV *FoundLHS, 10725 const SCEV *FoundRHS, unsigned Depth) { 10726 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10727 10728 auto ClearOnExit = make_scope_exit([&]() { 10729 if (LPhi) { 10730 bool Erased = PendingMerges.erase(LPhi); 10731 assert(Erased && "Failed to erase LPhi!"); 10732 (void)Erased; 10733 } 10734 if (RPhi) { 10735 bool Erased = PendingMerges.erase(RPhi); 10736 assert(Erased && "Failed to erase RPhi!"); 10737 (void)Erased; 10738 } 10739 }); 10740 10741 // Find respective Phis and check that they are not being pending. 10742 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10743 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10744 if (!PendingMerges.insert(Phi).second) 10745 return false; 10746 LPhi = Phi; 10747 } 10748 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10749 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10750 // If we detect a loop of Phi nodes being processed by this method, for 10751 // example: 10752 // 10753 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10754 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10755 // 10756 // we don't want to deal with a case that complex, so return conservative 10757 // answer false. 10758 if (!PendingMerges.insert(Phi).second) 10759 return false; 10760 RPhi = Phi; 10761 } 10762 10763 // If none of LHS, RHS is a Phi, nothing to do here. 10764 if (!LPhi && !RPhi) 10765 return false; 10766 10767 // If there is a SCEVUnknown Phi we are interested in, make it left. 10768 if (!LPhi) { 10769 std::swap(LHS, RHS); 10770 std::swap(FoundLHS, FoundRHS); 10771 std::swap(LPhi, RPhi); 10772 Pred = ICmpInst::getSwappedPredicate(Pred); 10773 } 10774 10775 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10776 const BasicBlock *LBB = LPhi->getParent(); 10777 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10778 10779 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10780 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10781 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10782 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10783 }; 10784 10785 if (RPhi && RPhi->getParent() == LBB) { 10786 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10787 // If we compare two Phis from the same block, and for each entry block 10788 // the predicate is true for incoming values from this block, then the 10789 // predicate is also true for the Phis. 10790 for (const BasicBlock *IncBB : predecessors(LBB)) { 10791 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10792 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10793 if (!ProvedEasily(L, R)) 10794 return false; 10795 } 10796 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10797 // Case two: RHS is also a Phi from the same basic block, and it is an 10798 // AddRec. It means that there is a loop which has both AddRec and Unknown 10799 // PHIs, for it we can compare incoming values of AddRec from above the loop 10800 // and latch with their respective incoming values of LPhi. 10801 // TODO: Generalize to handle loops with many inputs in a header. 10802 if (LPhi->getNumIncomingValues() != 2) return false; 10803 10804 auto *RLoop = RAR->getLoop(); 10805 auto *Predecessor = RLoop->getLoopPredecessor(); 10806 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10807 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10808 if (!ProvedEasily(L1, RAR->getStart())) 10809 return false; 10810 auto *Latch = RLoop->getLoopLatch(); 10811 assert(Latch && "Loop with AddRec with no latch?"); 10812 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10813 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10814 return false; 10815 } else { 10816 // In all other cases go over inputs of LHS and compare each of them to RHS, 10817 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10818 // At this point RHS is either a non-Phi, or it is a Phi from some block 10819 // different from LBB. 10820 for (const BasicBlock *IncBB : predecessors(LBB)) { 10821 // Check that RHS is available in this block. 10822 if (!dominates(RHS, IncBB)) 10823 return false; 10824 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10825 // Make sure L does not refer to a value from a potentially previous 10826 // iteration of a loop. 10827 if (!properlyDominates(L, IncBB)) 10828 return false; 10829 if (!ProvedEasily(L, RHS)) 10830 return false; 10831 } 10832 } 10833 return true; 10834 } 10835 10836 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10837 const SCEV *LHS, const SCEV *RHS, 10838 const SCEV *FoundLHS, 10839 const SCEV *FoundRHS, 10840 const Instruction *Context) { 10841 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10842 return true; 10843 10844 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10845 return true; 10846 10847 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 10848 Context)) 10849 return true; 10850 10851 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10852 FoundLHS, FoundRHS); 10853 } 10854 10855 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10856 template <typename MinMaxExprType> 10857 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10858 const SCEV *Candidate) { 10859 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10860 if (!MinMaxExpr) 10861 return false; 10862 10863 return is_contained(MinMaxExpr->operands(), Candidate); 10864 } 10865 10866 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10867 ICmpInst::Predicate Pred, 10868 const SCEV *LHS, const SCEV *RHS) { 10869 // If both sides are affine addrecs for the same loop, with equal 10870 // steps, and we know the recurrences don't wrap, then we only 10871 // need to check the predicate on the starting values. 10872 10873 if (!ICmpInst::isRelational(Pred)) 10874 return false; 10875 10876 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10877 if (!LAR) 10878 return false; 10879 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10880 if (!RAR) 10881 return false; 10882 if (LAR->getLoop() != RAR->getLoop()) 10883 return false; 10884 if (!LAR->isAffine() || !RAR->isAffine()) 10885 return false; 10886 10887 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10888 return false; 10889 10890 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10891 SCEV::FlagNSW : SCEV::FlagNUW; 10892 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10893 return false; 10894 10895 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10896 } 10897 10898 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10899 /// expression? 10900 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10901 ICmpInst::Predicate Pred, 10902 const SCEV *LHS, const SCEV *RHS) { 10903 switch (Pred) { 10904 default: 10905 return false; 10906 10907 case ICmpInst::ICMP_SGE: 10908 std::swap(LHS, RHS); 10909 LLVM_FALLTHROUGH; 10910 case ICmpInst::ICMP_SLE: 10911 return 10912 // min(A, ...) <= A 10913 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10914 // A <= max(A, ...) 10915 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10916 10917 case ICmpInst::ICMP_UGE: 10918 std::swap(LHS, RHS); 10919 LLVM_FALLTHROUGH; 10920 case ICmpInst::ICMP_ULE: 10921 return 10922 // min(A, ...) <= A 10923 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10924 // A <= max(A, ...) 10925 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10926 } 10927 10928 llvm_unreachable("covered switch fell through?!"); 10929 } 10930 10931 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10932 const SCEV *LHS, const SCEV *RHS, 10933 const SCEV *FoundLHS, 10934 const SCEV *FoundRHS, 10935 unsigned Depth) { 10936 assert(getTypeSizeInBits(LHS->getType()) == 10937 getTypeSizeInBits(RHS->getType()) && 10938 "LHS and RHS have different sizes?"); 10939 assert(getTypeSizeInBits(FoundLHS->getType()) == 10940 getTypeSizeInBits(FoundRHS->getType()) && 10941 "FoundLHS and FoundRHS have different sizes?"); 10942 // We want to avoid hurting the compile time with analysis of too big trees. 10943 if (Depth > MaxSCEVOperationsImplicationDepth) 10944 return false; 10945 10946 // We only want to work with GT comparison so far. 10947 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 10948 Pred = CmpInst::getSwappedPredicate(Pred); 10949 std::swap(LHS, RHS); 10950 std::swap(FoundLHS, FoundRHS); 10951 } 10952 10953 // For unsigned, try to reduce it to corresponding signed comparison. 10954 if (Pred == ICmpInst::ICMP_UGT) 10955 // We can replace unsigned predicate with its signed counterpart if all 10956 // involved values are non-negative. 10957 // TODO: We could have better support for unsigned. 10958 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 10959 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 10960 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 10961 // use this fact to prove that LHS and RHS are non-negative. 10962 const SCEV *MinusOne = getMinusOne(LHS->getType()); 10963 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 10964 FoundRHS) && 10965 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 10966 FoundRHS)) 10967 Pred = ICmpInst::ICMP_SGT; 10968 } 10969 10970 if (Pred != ICmpInst::ICMP_SGT) 10971 return false; 10972 10973 auto GetOpFromSExt = [&](const SCEV *S) { 10974 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10975 return Ext->getOperand(); 10976 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10977 // the constant in some cases. 10978 return S; 10979 }; 10980 10981 // Acquire values from extensions. 10982 auto *OrigLHS = LHS; 10983 auto *OrigFoundLHS = FoundLHS; 10984 LHS = GetOpFromSExt(LHS); 10985 FoundLHS = GetOpFromSExt(FoundLHS); 10986 10987 // Is the SGT predicate can be proved trivially or using the found context. 10988 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10989 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10990 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10991 FoundRHS, Depth + 1); 10992 }; 10993 10994 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10995 // We want to avoid creation of any new non-constant SCEV. Since we are 10996 // going to compare the operands to RHS, we should be certain that we don't 10997 // need any size extensions for this. So let's decline all cases when the 10998 // sizes of types of LHS and RHS do not match. 10999 // TODO: Maybe try to get RHS from sext to catch more cases? 11000 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11001 return false; 11002 11003 // Should not overflow. 11004 if (!LHSAddExpr->hasNoSignedWrap()) 11005 return false; 11006 11007 auto *LL = LHSAddExpr->getOperand(0); 11008 auto *LR = LHSAddExpr->getOperand(1); 11009 auto *MinusOne = getMinusOne(RHS->getType()); 11010 11011 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11012 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11013 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11014 }; 11015 // Try to prove the following rule: 11016 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11017 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11018 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11019 return true; 11020 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11021 Value *LL, *LR; 11022 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11023 11024 using namespace llvm::PatternMatch; 11025 11026 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11027 // Rules for division. 11028 // We are going to perform some comparisons with Denominator and its 11029 // derivative expressions. In general case, creating a SCEV for it may 11030 // lead to a complex analysis of the entire graph, and in particular it 11031 // can request trip count recalculation for the same loop. This would 11032 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11033 // this, we only want to create SCEVs that are constants in this section. 11034 // So we bail if Denominator is not a constant. 11035 if (!isa<ConstantInt>(LR)) 11036 return false; 11037 11038 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11039 11040 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11041 // then a SCEV for the numerator already exists and matches with FoundLHS. 11042 auto *Numerator = getExistingSCEV(LL); 11043 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11044 return false; 11045 11046 // Make sure that the numerator matches with FoundLHS and the denominator 11047 // is positive. 11048 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11049 return false; 11050 11051 auto *DTy = Denominator->getType(); 11052 auto *FRHSTy = FoundRHS->getType(); 11053 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11054 // One of types is a pointer and another one is not. We cannot extend 11055 // them properly to a wider type, so let us just reject this case. 11056 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11057 // to avoid this check. 11058 return false; 11059 11060 // Given that: 11061 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11062 auto *WTy = getWiderType(DTy, FRHSTy); 11063 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11064 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11065 11066 // Try to prove the following rule: 11067 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11068 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11069 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11070 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11071 if (isKnownNonPositive(RHS) && 11072 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11073 return true; 11074 11075 // Try to prove the following rule: 11076 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11077 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11078 // If we divide it by Denominator > 2, then: 11079 // 1. If FoundLHS is negative, then the result is 0. 11080 // 2. If FoundLHS is non-negative, then the result is non-negative. 11081 // Anyways, the result is non-negative. 11082 auto *MinusOne = getMinusOne(WTy); 11083 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11084 if (isKnownNegative(RHS) && 11085 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11086 return true; 11087 } 11088 } 11089 11090 // If our expression contained SCEVUnknown Phis, and we split it down and now 11091 // need to prove something for them, try to prove the predicate for every 11092 // possible incoming values of those Phis. 11093 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11094 return true; 11095 11096 return false; 11097 } 11098 11099 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11100 const SCEV *LHS, const SCEV *RHS) { 11101 // zext x u<= sext x, sext x s<= zext x 11102 switch (Pred) { 11103 case ICmpInst::ICMP_SGE: 11104 std::swap(LHS, RHS); 11105 LLVM_FALLTHROUGH; 11106 case ICmpInst::ICMP_SLE: { 11107 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11108 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11109 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11110 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11111 return true; 11112 break; 11113 } 11114 case ICmpInst::ICMP_UGE: 11115 std::swap(LHS, RHS); 11116 LLVM_FALLTHROUGH; 11117 case ICmpInst::ICMP_ULE: { 11118 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11119 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11120 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11121 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11122 return true; 11123 break; 11124 } 11125 default: 11126 break; 11127 }; 11128 return false; 11129 } 11130 11131 bool 11132 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 11133 const SCEV *LHS, const SCEV *RHS) { 11134 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 11135 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 11136 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 11137 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 11138 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 11139 } 11140 11141 bool 11142 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 11143 const SCEV *LHS, const SCEV *RHS, 11144 const SCEV *FoundLHS, 11145 const SCEV *FoundRHS) { 11146 switch (Pred) { 11147 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 11148 case ICmpInst::ICMP_EQ: 11149 case ICmpInst::ICMP_NE: 11150 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 11151 return true; 11152 break; 11153 case ICmpInst::ICMP_SLT: 11154 case ICmpInst::ICMP_SLE: 11155 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 11156 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 11157 return true; 11158 break; 11159 case ICmpInst::ICMP_SGT: 11160 case ICmpInst::ICMP_SGE: 11161 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 11162 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 11163 return true; 11164 break; 11165 case ICmpInst::ICMP_ULT: 11166 case ICmpInst::ICMP_ULE: 11167 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 11168 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 11169 return true; 11170 break; 11171 case ICmpInst::ICMP_UGT: 11172 case ICmpInst::ICMP_UGE: 11173 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 11174 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 11175 return true; 11176 break; 11177 } 11178 11179 // Maybe it can be proved via operations? 11180 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11181 return true; 11182 11183 return false; 11184 } 11185 11186 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 11187 const SCEV *LHS, 11188 const SCEV *RHS, 11189 const SCEV *FoundLHS, 11190 const SCEV *FoundRHS) { 11191 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 11192 // The restriction on `FoundRHS` be lifted easily -- it exists only to 11193 // reduce the compile time impact of this optimization. 11194 return false; 11195 11196 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 11197 if (!Addend) 11198 return false; 11199 11200 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 11201 11202 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 11203 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 11204 ConstantRange FoundLHSRange = 11205 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 11206 11207 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 11208 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 11209 11210 // We can also compute the range of values for `LHS` that satisfy the 11211 // consequent, "`LHS` `Pred` `RHS`": 11212 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 11213 // The antecedent implies the consequent if every value of `LHS` that 11214 // satisfies the antecedent also satisfies the consequent. 11215 return LHSRange.icmp(Pred, ConstRHS); 11216 } 11217 11218 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 11219 bool IsSigned) { 11220 assert(isKnownPositive(Stride) && "Positive stride expected!"); 11221 11222 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11223 const SCEV *One = getOne(Stride->getType()); 11224 11225 if (IsSigned) { 11226 APInt MaxRHS = getSignedRangeMax(RHS); 11227 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11228 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11229 11230 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11231 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11232 } 11233 11234 APInt MaxRHS = getUnsignedRangeMax(RHS); 11235 APInt MaxValue = APInt::getMaxValue(BitWidth); 11236 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11237 11238 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11239 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11240 } 11241 11242 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11243 bool IsSigned) { 11244 11245 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11246 const SCEV *One = getOne(Stride->getType()); 11247 11248 if (IsSigned) { 11249 APInt MinRHS = getSignedRangeMin(RHS); 11250 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11251 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11252 11253 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11254 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11255 } 11256 11257 APInt MinRHS = getUnsignedRangeMin(RHS); 11258 APInt MinValue = APInt::getMinValue(BitWidth); 11259 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11260 11261 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11262 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11263 } 11264 11265 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, 11266 const SCEV *Step) { 11267 const SCEV *One = getOne(Step->getType()); 11268 Delta = getAddExpr(Delta, getMinusSCEV(Step, One)); 11269 return getUDivExpr(Delta, Step); 11270 } 11271 11272 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11273 const SCEV *Stride, 11274 const SCEV *End, 11275 unsigned BitWidth, 11276 bool IsSigned) { 11277 11278 assert(!isKnownNonPositive(Stride) && 11279 "Stride is expected strictly positive!"); 11280 // Calculate the maximum backedge count based on the range of values 11281 // permitted by Start, End, and Stride. 11282 const SCEV *MaxBECount; 11283 APInt MinStart = 11284 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11285 11286 APInt StrideForMaxBECount = 11287 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11288 11289 // We already know that the stride is positive, so we paper over conservatism 11290 // in our range computation by forcing StrideForMaxBECount to be at least one. 11291 // In theory this is unnecessary, but we expect MaxBECount to be a 11292 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 11293 // is nothing to constant fold it to). 11294 APInt One(BitWidth, 1, IsSigned); 11295 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 11296 11297 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11298 : APInt::getMaxValue(BitWidth); 11299 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11300 11301 // Although End can be a MAX expression we estimate MaxEnd considering only 11302 // the case End = RHS of the loop termination condition. This is safe because 11303 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11304 // taken count. 11305 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11306 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11307 11308 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 11309 getConstant(StrideForMaxBECount) /* Step */); 11310 11311 return MaxBECount; 11312 } 11313 11314 ScalarEvolution::ExitLimit 11315 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11316 const Loop *L, bool IsSigned, 11317 bool ControlsExit, bool AllowPredicates) { 11318 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11319 11320 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11321 bool PredicatedIV = false; 11322 11323 if (!IV && AllowPredicates) { 11324 // Try to make this an AddRec using runtime tests, in the first X 11325 // iterations of this loop, where X is the SCEV expression found by the 11326 // algorithm below. 11327 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11328 PredicatedIV = true; 11329 } 11330 11331 // Avoid weird loops 11332 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11333 return getCouldNotCompute(); 11334 11335 bool NoWrap = ControlsExit && 11336 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 11337 11338 const SCEV *Stride = IV->getStepRecurrence(*this); 11339 11340 bool PositiveStride = isKnownPositive(Stride); 11341 11342 // Avoid negative or zero stride values. 11343 if (!PositiveStride) { 11344 // We can compute the correct backedge taken count for loops with unknown 11345 // strides if we can prove that the loop is not an infinite loop with side 11346 // effects. Here's the loop structure we are trying to handle - 11347 // 11348 // i = start 11349 // do { 11350 // A[i] = i; 11351 // i += s; 11352 // } while (i < end); 11353 // 11354 // The backedge taken count for such loops is evaluated as - 11355 // (max(end, start + stride) - start - 1) /u stride 11356 // 11357 // The additional preconditions that we need to check to prove correctness 11358 // of the above formula is as follows - 11359 // 11360 // a) IV is either nuw or nsw depending upon signedness (indicated by the 11361 // NoWrap flag). 11362 // b) loop is single exit with no side effects. 11363 // 11364 // 11365 // Precondition a) implies that if the stride is negative, this is a single 11366 // trip loop. The backedge taken count formula reduces to zero in this case. 11367 // 11368 // Precondition b) implies that the unknown stride cannot be zero otherwise 11369 // we have UB. 11370 // 11371 // The positive stride case is the same as isKnownPositive(Stride) returning 11372 // true (original behavior of the function). 11373 // 11374 // We want to make sure that the stride is truly unknown as there are edge 11375 // cases where ScalarEvolution propagates no wrap flags to the 11376 // post-increment/decrement IV even though the increment/decrement operation 11377 // itself is wrapping. The computed backedge taken count may be wrong in 11378 // such cases. This is prevented by checking that the stride is not known to 11379 // be either positive or non-positive. For example, no wrap flags are 11380 // propagated to the post-increment IV of this loop with a trip count of 2 - 11381 // 11382 // unsigned char i; 11383 // for(i=127; i<128; i+=129) 11384 // A[i] = i; 11385 // 11386 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 11387 !loopHasNoSideEffects(L)) 11388 return getCouldNotCompute(); 11389 } else if (!Stride->isOne() && !NoWrap) { 11390 // Avoid proven overflow cases: this will ensure that the backedge taken 11391 // count will not generate any unsigned overflow. Relaxed no-overflow 11392 // conditions exploit NoWrapFlags, allowing to optimize in presence of 11393 // undefined behaviors like the case of C language. 11394 if (canIVOverflowOnLT(RHS, Stride, IsSigned)) 11395 return getCouldNotCompute(); 11396 } 11397 11398 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 11399 : ICmpInst::ICMP_ULT; 11400 const SCEV *Start = IV->getStart(); 11401 const SCEV *End = RHS; 11402 // When the RHS is not invariant, we do not know the end bound of the loop and 11403 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 11404 // calculate the MaxBECount, given the start, stride and max value for the end 11405 // bound of the loop (RHS), and the fact that IV does not overflow (which is 11406 // checked above). 11407 if (!isLoopInvariant(RHS, L)) { 11408 const SCEV *MaxBECount = computeMaxBECountForLT( 11409 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11410 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 11411 false /*MaxOrZero*/, Predicates); 11412 } 11413 // If the backedge is taken at least once, then it will be taken 11414 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 11415 // is the LHS value of the less-than comparison the first time it is evaluated 11416 // and End is the RHS. 11417 const SCEV *BECountIfBackedgeTaken = 11418 computeBECount(getMinusSCEV(End, Start), Stride); 11419 // If the loop entry is guarded by the result of the backedge test of the 11420 // first loop iteration, then we know the backedge will be taken at least 11421 // once and so the backedge taken count is as above. If not then we use the 11422 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 11423 // as if the backedge is taken at least once max(End,Start) is End and so the 11424 // result is as above, and if not max(End,Start) is Start so we get a backedge 11425 // count of zero. 11426 const SCEV *BECount; 11427 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 11428 BECount = BECountIfBackedgeTaken; 11429 else { 11430 // If we know that RHS >= Start in the context of loop, then we know that 11431 // max(RHS, Start) = RHS at this point. 11432 if (isLoopEntryGuardedByCond( 11433 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start)) 11434 End = RHS; 11435 else 11436 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 11437 BECount = computeBECount(getMinusSCEV(End, Start), Stride); 11438 } 11439 11440 const SCEV *MaxBECount; 11441 bool MaxOrZero = false; 11442 if (isa<SCEVConstant>(BECount)) 11443 MaxBECount = BECount; 11444 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 11445 // If we know exactly how many times the backedge will be taken if it's 11446 // taken at least once, then the backedge count will either be that or 11447 // zero. 11448 MaxBECount = BECountIfBackedgeTaken; 11449 MaxOrZero = true; 11450 } else { 11451 MaxBECount = computeMaxBECountForLT( 11452 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11453 } 11454 11455 if (isa<SCEVCouldNotCompute>(MaxBECount) && 11456 !isa<SCEVCouldNotCompute>(BECount)) 11457 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 11458 11459 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 11460 } 11461 11462 ScalarEvolution::ExitLimit 11463 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 11464 const Loop *L, bool IsSigned, 11465 bool ControlsExit, bool AllowPredicates) { 11466 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11467 // We handle only IV > Invariant 11468 if (!isLoopInvariant(RHS, L)) 11469 return getCouldNotCompute(); 11470 11471 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11472 if (!IV && AllowPredicates) 11473 // Try to make this an AddRec using runtime tests, in the first X 11474 // iterations of this loop, where X is the SCEV expression found by the 11475 // algorithm below. 11476 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11477 11478 // Avoid weird loops 11479 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11480 return getCouldNotCompute(); 11481 11482 bool NoWrap = ControlsExit && 11483 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 11484 11485 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 11486 11487 // Avoid negative or zero stride values 11488 if (!isKnownPositive(Stride)) 11489 return getCouldNotCompute(); 11490 11491 // Avoid proven overflow cases: this will ensure that the backedge taken count 11492 // will not generate any unsigned overflow. Relaxed no-overflow conditions 11493 // exploit NoWrapFlags, allowing to optimize in presence of undefined 11494 // behaviors like the case of C language. 11495 if (!Stride->isOne() && !NoWrap) 11496 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 11497 return getCouldNotCompute(); 11498 11499 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 11500 : ICmpInst::ICMP_UGT; 11501 11502 const SCEV *Start = IV->getStart(); 11503 const SCEV *End = RHS; 11504 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 11505 // If we know that Start >= RHS in the context of loop, then we know that 11506 // min(RHS, Start) = RHS at this point. 11507 if (isLoopEntryGuardedByCond( 11508 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 11509 End = RHS; 11510 else 11511 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 11512 } 11513 11514 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride); 11515 11516 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 11517 : getUnsignedRangeMax(Start); 11518 11519 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 11520 : getUnsignedRangeMin(Stride); 11521 11522 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 11523 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 11524 : APInt::getMinValue(BitWidth) + (MinStride - 1); 11525 11526 // Although End can be a MIN expression we estimate MinEnd considering only 11527 // the case End = RHS. This is safe because in the other case (Start - End) 11528 // is zero, leading to a zero maximum backedge taken count. 11529 APInt MinEnd = 11530 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 11531 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 11532 11533 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 11534 ? BECount 11535 : computeBECount(getConstant(MaxStart - MinEnd), 11536 getConstant(MinStride)); 11537 11538 if (isa<SCEVCouldNotCompute>(MaxBECount)) 11539 MaxBECount = BECount; 11540 11541 return ExitLimit(BECount, MaxBECount, false, Predicates); 11542 } 11543 11544 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 11545 ScalarEvolution &SE) const { 11546 if (Range.isFullSet()) // Infinite loop. 11547 return SE.getCouldNotCompute(); 11548 11549 // If the start is a non-zero constant, shift the range to simplify things. 11550 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 11551 if (!SC->getValue()->isZero()) { 11552 SmallVector<const SCEV *, 4> Operands(operands()); 11553 Operands[0] = SE.getZero(SC->getType()); 11554 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 11555 getNoWrapFlags(FlagNW)); 11556 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 11557 return ShiftedAddRec->getNumIterationsInRange( 11558 Range.subtract(SC->getAPInt()), SE); 11559 // This is strange and shouldn't happen. 11560 return SE.getCouldNotCompute(); 11561 } 11562 11563 // The only time we can solve this is when we have all constant indices. 11564 // Otherwise, we cannot determine the overflow conditions. 11565 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 11566 return SE.getCouldNotCompute(); 11567 11568 // Okay at this point we know that all elements of the chrec are constants and 11569 // that the start element is zero. 11570 11571 // First check to see if the range contains zero. If not, the first 11572 // iteration exits. 11573 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 11574 if (!Range.contains(APInt(BitWidth, 0))) 11575 return SE.getZero(getType()); 11576 11577 if (isAffine()) { 11578 // If this is an affine expression then we have this situation: 11579 // Solve {0,+,A} in Range === Ax in Range 11580 11581 // We know that zero is in the range. If A is positive then we know that 11582 // the upper value of the range must be the first possible exit value. 11583 // If A is negative then the lower of the range is the last possible loop 11584 // value. Also note that we already checked for a full range. 11585 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 11586 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 11587 11588 // The exit value should be (End+A)/A. 11589 APInt ExitVal = (End + A).udiv(A); 11590 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 11591 11592 // Evaluate at the exit value. If we really did fall out of the valid 11593 // range, then we computed our trip count, otherwise wrap around or other 11594 // things must have happened. 11595 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 11596 if (Range.contains(Val->getValue())) 11597 return SE.getCouldNotCompute(); // Something strange happened 11598 11599 // Ensure that the previous value is in the range. This is a sanity check. 11600 assert(Range.contains( 11601 EvaluateConstantChrecAtConstant(this, 11602 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 11603 "Linear scev computation is off in a bad way!"); 11604 return SE.getConstant(ExitValue); 11605 } 11606 11607 if (isQuadratic()) { 11608 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 11609 return SE.getConstant(S.getValue()); 11610 } 11611 11612 return SE.getCouldNotCompute(); 11613 } 11614 11615 const SCEVAddRecExpr * 11616 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 11617 assert(getNumOperands() > 1 && "AddRec with zero step?"); 11618 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 11619 // but in this case we cannot guarantee that the value returned will be an 11620 // AddRec because SCEV does not have a fixed point where it stops 11621 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 11622 // may happen if we reach arithmetic depth limit while simplifying. So we 11623 // construct the returned value explicitly. 11624 SmallVector<const SCEV *, 3> Ops; 11625 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 11626 // (this + Step) is {A+B,+,B+C,+...,+,N}. 11627 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 11628 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 11629 // We know that the last operand is not a constant zero (otherwise it would 11630 // have been popped out earlier). This guarantees us that if the result has 11631 // the same last operand, then it will also not be popped out, meaning that 11632 // the returned value will be an AddRec. 11633 const SCEV *Last = getOperand(getNumOperands() - 1); 11634 assert(!Last->isZero() && "Recurrency with zero step?"); 11635 Ops.push_back(Last); 11636 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 11637 SCEV::FlagAnyWrap)); 11638 } 11639 11640 // Return true when S contains at least an undef value. 11641 static inline bool containsUndefs(const SCEV *S) { 11642 return SCEVExprContains(S, [](const SCEV *S) { 11643 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 11644 return isa<UndefValue>(SU->getValue()); 11645 return false; 11646 }); 11647 } 11648 11649 namespace { 11650 11651 // Collect all steps of SCEV expressions. 11652 struct SCEVCollectStrides { 11653 ScalarEvolution &SE; 11654 SmallVectorImpl<const SCEV *> &Strides; 11655 11656 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 11657 : SE(SE), Strides(S) {} 11658 11659 bool follow(const SCEV *S) { 11660 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 11661 Strides.push_back(AR->getStepRecurrence(SE)); 11662 return true; 11663 } 11664 11665 bool isDone() const { return false; } 11666 }; 11667 11668 // Collect all SCEVUnknown and SCEVMulExpr expressions. 11669 struct SCEVCollectTerms { 11670 SmallVectorImpl<const SCEV *> &Terms; 11671 11672 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 11673 11674 bool follow(const SCEV *S) { 11675 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 11676 isa<SCEVSignExtendExpr>(S)) { 11677 if (!containsUndefs(S)) 11678 Terms.push_back(S); 11679 11680 // Stop recursion: once we collected a term, do not walk its operands. 11681 return false; 11682 } 11683 11684 // Keep looking. 11685 return true; 11686 } 11687 11688 bool isDone() const { return false; } 11689 }; 11690 11691 // Check if a SCEV contains an AddRecExpr. 11692 struct SCEVHasAddRec { 11693 bool &ContainsAddRec; 11694 11695 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 11696 ContainsAddRec = false; 11697 } 11698 11699 bool follow(const SCEV *S) { 11700 if (isa<SCEVAddRecExpr>(S)) { 11701 ContainsAddRec = true; 11702 11703 // Stop recursion: once we collected a term, do not walk its operands. 11704 return false; 11705 } 11706 11707 // Keep looking. 11708 return true; 11709 } 11710 11711 bool isDone() const { return false; } 11712 }; 11713 11714 // Find factors that are multiplied with an expression that (possibly as a 11715 // subexpression) contains an AddRecExpr. In the expression: 11716 // 11717 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11718 // 11719 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11720 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11721 // parameters as they form a product with an induction variable. 11722 // 11723 // This collector expects all array size parameters to be in the same MulExpr. 11724 // It might be necessary to later add support for collecting parameters that are 11725 // spread over different nested MulExpr. 11726 struct SCEVCollectAddRecMultiplies { 11727 SmallVectorImpl<const SCEV *> &Terms; 11728 ScalarEvolution &SE; 11729 11730 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11731 : Terms(T), SE(SE) {} 11732 11733 bool follow(const SCEV *S) { 11734 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11735 bool HasAddRec = false; 11736 SmallVector<const SCEV *, 0> Operands; 11737 for (auto Op : Mul->operands()) { 11738 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11739 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11740 Operands.push_back(Op); 11741 } else if (Unknown) { 11742 HasAddRec = true; 11743 } else { 11744 bool ContainsAddRec = false; 11745 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11746 visitAll(Op, ContiansAddRec); 11747 HasAddRec |= ContainsAddRec; 11748 } 11749 } 11750 if (Operands.size() == 0) 11751 return true; 11752 11753 if (!HasAddRec) 11754 return false; 11755 11756 Terms.push_back(SE.getMulExpr(Operands)); 11757 // Stop recursion: once we collected a term, do not walk its operands. 11758 return false; 11759 } 11760 11761 // Keep looking. 11762 return true; 11763 } 11764 11765 bool isDone() const { return false; } 11766 }; 11767 11768 } // end anonymous namespace 11769 11770 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11771 /// two places: 11772 /// 1) The strides of AddRec expressions. 11773 /// 2) Unknowns that are multiplied with AddRec expressions. 11774 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11775 SmallVectorImpl<const SCEV *> &Terms) { 11776 SmallVector<const SCEV *, 4> Strides; 11777 SCEVCollectStrides StrideCollector(*this, Strides); 11778 visitAll(Expr, StrideCollector); 11779 11780 LLVM_DEBUG({ 11781 dbgs() << "Strides:\n"; 11782 for (const SCEV *S : Strides) 11783 dbgs() << *S << "\n"; 11784 }); 11785 11786 for (const SCEV *S : Strides) { 11787 SCEVCollectTerms TermCollector(Terms); 11788 visitAll(S, TermCollector); 11789 } 11790 11791 LLVM_DEBUG({ 11792 dbgs() << "Terms:\n"; 11793 for (const SCEV *T : Terms) 11794 dbgs() << *T << "\n"; 11795 }); 11796 11797 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11798 visitAll(Expr, MulCollector); 11799 } 11800 11801 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11802 SmallVectorImpl<const SCEV *> &Terms, 11803 SmallVectorImpl<const SCEV *> &Sizes) { 11804 int Last = Terms.size() - 1; 11805 const SCEV *Step = Terms[Last]; 11806 11807 // End of recursion. 11808 if (Last == 0) { 11809 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11810 SmallVector<const SCEV *, 2> Qs; 11811 for (const SCEV *Op : M->operands()) 11812 if (!isa<SCEVConstant>(Op)) 11813 Qs.push_back(Op); 11814 11815 Step = SE.getMulExpr(Qs); 11816 } 11817 11818 Sizes.push_back(Step); 11819 return true; 11820 } 11821 11822 for (const SCEV *&Term : Terms) { 11823 // Normalize the terms before the next call to findArrayDimensionsRec. 11824 const SCEV *Q, *R; 11825 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11826 11827 // Bail out when GCD does not evenly divide one of the terms. 11828 if (!R->isZero()) 11829 return false; 11830 11831 Term = Q; 11832 } 11833 11834 // Remove all SCEVConstants. 11835 erase_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }); 11836 11837 if (Terms.size() > 0) 11838 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11839 return false; 11840 11841 Sizes.push_back(Step); 11842 return true; 11843 } 11844 11845 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11846 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11847 for (const SCEV *T : Terms) 11848 if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); })) 11849 return true; 11850 11851 return false; 11852 } 11853 11854 // Return the number of product terms in S. 11855 static inline int numberOfTerms(const SCEV *S) { 11856 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11857 return Expr->getNumOperands(); 11858 return 1; 11859 } 11860 11861 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11862 if (isa<SCEVConstant>(T)) 11863 return nullptr; 11864 11865 if (isa<SCEVUnknown>(T)) 11866 return T; 11867 11868 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11869 SmallVector<const SCEV *, 2> Factors; 11870 for (const SCEV *Op : M->operands()) 11871 if (!isa<SCEVConstant>(Op)) 11872 Factors.push_back(Op); 11873 11874 return SE.getMulExpr(Factors); 11875 } 11876 11877 return T; 11878 } 11879 11880 /// Return the size of an element read or written by Inst. 11881 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11882 Type *Ty; 11883 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11884 Ty = Store->getValueOperand()->getType(); 11885 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11886 Ty = Load->getType(); 11887 else 11888 return nullptr; 11889 11890 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11891 return getSizeOfExpr(ETy, Ty); 11892 } 11893 11894 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11895 SmallVectorImpl<const SCEV *> &Sizes, 11896 const SCEV *ElementSize) { 11897 if (Terms.size() < 1 || !ElementSize) 11898 return; 11899 11900 // Early return when Terms do not contain parameters: we do not delinearize 11901 // non parametric SCEVs. 11902 if (!containsParameters(Terms)) 11903 return; 11904 11905 LLVM_DEBUG({ 11906 dbgs() << "Terms:\n"; 11907 for (const SCEV *T : Terms) 11908 dbgs() << *T << "\n"; 11909 }); 11910 11911 // Remove duplicates. 11912 array_pod_sort(Terms.begin(), Terms.end()); 11913 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11914 11915 // Put larger terms first. 11916 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11917 return numberOfTerms(LHS) > numberOfTerms(RHS); 11918 }); 11919 11920 // Try to divide all terms by the element size. If term is not divisible by 11921 // element size, proceed with the original term. 11922 for (const SCEV *&Term : Terms) { 11923 const SCEV *Q, *R; 11924 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11925 if (!Q->isZero()) 11926 Term = Q; 11927 } 11928 11929 SmallVector<const SCEV *, 4> NewTerms; 11930 11931 // Remove constant factors. 11932 for (const SCEV *T : Terms) 11933 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11934 NewTerms.push_back(NewT); 11935 11936 LLVM_DEBUG({ 11937 dbgs() << "Terms after sorting:\n"; 11938 for (const SCEV *T : NewTerms) 11939 dbgs() << *T << "\n"; 11940 }); 11941 11942 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11943 Sizes.clear(); 11944 return; 11945 } 11946 11947 // The last element to be pushed into Sizes is the size of an element. 11948 Sizes.push_back(ElementSize); 11949 11950 LLVM_DEBUG({ 11951 dbgs() << "Sizes:\n"; 11952 for (const SCEV *S : Sizes) 11953 dbgs() << *S << "\n"; 11954 }); 11955 } 11956 11957 void ScalarEvolution::computeAccessFunctions( 11958 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11959 SmallVectorImpl<const SCEV *> &Sizes) { 11960 // Early exit in case this SCEV is not an affine multivariate function. 11961 if (Sizes.empty()) 11962 return; 11963 11964 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11965 if (!AR->isAffine()) 11966 return; 11967 11968 const SCEV *Res = Expr; 11969 int Last = Sizes.size() - 1; 11970 for (int i = Last; i >= 0; i--) { 11971 const SCEV *Q, *R; 11972 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11973 11974 LLVM_DEBUG({ 11975 dbgs() << "Res: " << *Res << "\n"; 11976 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11977 dbgs() << "Res divided by Sizes[i]:\n"; 11978 dbgs() << "Quotient: " << *Q << "\n"; 11979 dbgs() << "Remainder: " << *R << "\n"; 11980 }); 11981 11982 Res = Q; 11983 11984 // Do not record the last subscript corresponding to the size of elements in 11985 // the array. 11986 if (i == Last) { 11987 11988 // Bail out if the remainder is too complex. 11989 if (isa<SCEVAddRecExpr>(R)) { 11990 Subscripts.clear(); 11991 Sizes.clear(); 11992 return; 11993 } 11994 11995 continue; 11996 } 11997 11998 // Record the access function for the current subscript. 11999 Subscripts.push_back(R); 12000 } 12001 12002 // Also push in last position the remainder of the last division: it will be 12003 // the access function of the innermost dimension. 12004 Subscripts.push_back(Res); 12005 12006 std::reverse(Subscripts.begin(), Subscripts.end()); 12007 12008 LLVM_DEBUG({ 12009 dbgs() << "Subscripts:\n"; 12010 for (const SCEV *S : Subscripts) 12011 dbgs() << *S << "\n"; 12012 }); 12013 } 12014 12015 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 12016 /// sizes of an array access. Returns the remainder of the delinearization that 12017 /// is the offset start of the array. The SCEV->delinearize algorithm computes 12018 /// the multiples of SCEV coefficients: that is a pattern matching of sub 12019 /// expressions in the stride and base of a SCEV corresponding to the 12020 /// computation of a GCD (greatest common divisor) of base and stride. When 12021 /// SCEV->delinearize fails, it returns the SCEV unchanged. 12022 /// 12023 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 12024 /// 12025 /// void foo(long n, long m, long o, double A[n][m][o]) { 12026 /// 12027 /// for (long i = 0; i < n; i++) 12028 /// for (long j = 0; j < m; j++) 12029 /// for (long k = 0; k < o; k++) 12030 /// A[i][j][k] = 1.0; 12031 /// } 12032 /// 12033 /// the delinearization input is the following AddRec SCEV: 12034 /// 12035 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 12036 /// 12037 /// From this SCEV, we are able to say that the base offset of the access is %A 12038 /// because it appears as an offset that does not divide any of the strides in 12039 /// the loops: 12040 /// 12041 /// CHECK: Base offset: %A 12042 /// 12043 /// and then SCEV->delinearize determines the size of some of the dimensions of 12044 /// the array as these are the multiples by which the strides are happening: 12045 /// 12046 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 12047 /// 12048 /// Note that the outermost dimension remains of UnknownSize because there are 12049 /// no strides that would help identifying the size of the last dimension: when 12050 /// the array has been statically allocated, one could compute the size of that 12051 /// dimension by dividing the overall size of the array by the size of the known 12052 /// dimensions: %m * %o * 8. 12053 /// 12054 /// Finally delinearize provides the access functions for the array reference 12055 /// that does correspond to A[i][j][k] of the above C testcase: 12056 /// 12057 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 12058 /// 12059 /// The testcases are checking the output of a function pass: 12060 /// DelinearizationPass that walks through all loads and stores of a function 12061 /// asking for the SCEV of the memory access with respect to all enclosing 12062 /// loops, calling SCEV->delinearize on that and printing the results. 12063 void ScalarEvolution::delinearize(const SCEV *Expr, 12064 SmallVectorImpl<const SCEV *> &Subscripts, 12065 SmallVectorImpl<const SCEV *> &Sizes, 12066 const SCEV *ElementSize) { 12067 // First step: collect parametric terms. 12068 SmallVector<const SCEV *, 4> Terms; 12069 collectParametricTerms(Expr, Terms); 12070 12071 if (Terms.empty()) 12072 return; 12073 12074 // Second step: find subscript sizes. 12075 findArrayDimensions(Terms, Sizes, ElementSize); 12076 12077 if (Sizes.empty()) 12078 return; 12079 12080 // Third step: compute the access functions for each subscript. 12081 computeAccessFunctions(Expr, Subscripts, Sizes); 12082 12083 if (Subscripts.empty()) 12084 return; 12085 12086 LLVM_DEBUG({ 12087 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 12088 dbgs() << "ArrayDecl[UnknownSize]"; 12089 for (const SCEV *S : Sizes) 12090 dbgs() << "[" << *S << "]"; 12091 12092 dbgs() << "\nArrayRef"; 12093 for (const SCEV *S : Subscripts) 12094 dbgs() << "[" << *S << "]"; 12095 dbgs() << "\n"; 12096 }); 12097 } 12098 12099 bool ScalarEvolution::getIndexExpressionsFromGEP( 12100 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 12101 SmallVectorImpl<int> &Sizes) { 12102 assert(Subscripts.empty() && Sizes.empty() && 12103 "Expected output lists to be empty on entry to this function."); 12104 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 12105 Type *Ty = GEP->getPointerOperandType(); 12106 bool DroppedFirstDim = false; 12107 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 12108 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 12109 if (i == 1) { 12110 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 12111 Ty = PtrTy->getElementType(); 12112 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 12113 Ty = ArrayTy->getElementType(); 12114 } else { 12115 Subscripts.clear(); 12116 Sizes.clear(); 12117 return false; 12118 } 12119 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 12120 if (Const->getValue()->isZero()) { 12121 DroppedFirstDim = true; 12122 continue; 12123 } 12124 Subscripts.push_back(Expr); 12125 continue; 12126 } 12127 12128 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 12129 if (!ArrayTy) { 12130 Subscripts.clear(); 12131 Sizes.clear(); 12132 return false; 12133 } 12134 12135 Subscripts.push_back(Expr); 12136 if (!(DroppedFirstDim && i == 2)) 12137 Sizes.push_back(ArrayTy->getNumElements()); 12138 12139 Ty = ArrayTy->getElementType(); 12140 } 12141 return !Subscripts.empty(); 12142 } 12143 12144 //===----------------------------------------------------------------------===// 12145 // SCEVCallbackVH Class Implementation 12146 //===----------------------------------------------------------------------===// 12147 12148 void ScalarEvolution::SCEVCallbackVH::deleted() { 12149 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12150 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12151 SE->ConstantEvolutionLoopExitValue.erase(PN); 12152 SE->eraseValueFromMap(getValPtr()); 12153 // this now dangles! 12154 } 12155 12156 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12157 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12158 12159 // Forget all the expressions associated with users of the old value, 12160 // so that future queries will recompute the expressions using the new 12161 // value. 12162 Value *Old = getValPtr(); 12163 SmallVector<User *, 16> Worklist(Old->users()); 12164 SmallPtrSet<User *, 8> Visited; 12165 while (!Worklist.empty()) { 12166 User *U = Worklist.pop_back_val(); 12167 // Deleting the Old value will cause this to dangle. Postpone 12168 // that until everything else is done. 12169 if (U == Old) 12170 continue; 12171 if (!Visited.insert(U).second) 12172 continue; 12173 if (PHINode *PN = dyn_cast<PHINode>(U)) 12174 SE->ConstantEvolutionLoopExitValue.erase(PN); 12175 SE->eraseValueFromMap(U); 12176 llvm::append_range(Worklist, U->users()); 12177 } 12178 // Delete the Old value. 12179 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12180 SE->ConstantEvolutionLoopExitValue.erase(PN); 12181 SE->eraseValueFromMap(Old); 12182 // this now dangles! 12183 } 12184 12185 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12186 : CallbackVH(V), SE(se) {} 12187 12188 //===----------------------------------------------------------------------===// 12189 // ScalarEvolution Class Implementation 12190 //===----------------------------------------------------------------------===// 12191 12192 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12193 AssumptionCache &AC, DominatorTree &DT, 12194 LoopInfo &LI) 12195 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12196 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12197 LoopDispositions(64), BlockDispositions(64) { 12198 // To use guards for proving predicates, we need to scan every instruction in 12199 // relevant basic blocks, and not just terminators. Doing this is a waste of 12200 // time if the IR does not actually contain any calls to 12201 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12202 // 12203 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12204 // to _add_ guards to the module when there weren't any before, and wants 12205 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12206 // efficient in lieu of being smart in that rather obscure case. 12207 12208 auto *GuardDecl = F.getParent()->getFunction( 12209 Intrinsic::getName(Intrinsic::experimental_guard)); 12210 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12211 } 12212 12213 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12214 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12215 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12216 ValueExprMap(std::move(Arg.ValueExprMap)), 12217 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12218 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12219 PendingMerges(std::move(Arg.PendingMerges)), 12220 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12221 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12222 PredicatedBackedgeTakenCounts( 12223 std::move(Arg.PredicatedBackedgeTakenCounts)), 12224 ConstantEvolutionLoopExitValue( 12225 std::move(Arg.ConstantEvolutionLoopExitValue)), 12226 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12227 LoopDispositions(std::move(Arg.LoopDispositions)), 12228 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12229 BlockDispositions(std::move(Arg.BlockDispositions)), 12230 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12231 SignedRanges(std::move(Arg.SignedRanges)), 12232 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12233 UniquePreds(std::move(Arg.UniquePreds)), 12234 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12235 LoopUsers(std::move(Arg.LoopUsers)), 12236 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12237 FirstUnknown(Arg.FirstUnknown) { 12238 Arg.FirstUnknown = nullptr; 12239 } 12240 12241 ScalarEvolution::~ScalarEvolution() { 12242 // Iterate through all the SCEVUnknown instances and call their 12243 // destructors, so that they release their references to their values. 12244 for (SCEVUnknown *U = FirstUnknown; U;) { 12245 SCEVUnknown *Tmp = U; 12246 U = U->Next; 12247 Tmp->~SCEVUnknown(); 12248 } 12249 FirstUnknown = nullptr; 12250 12251 ExprValueMap.clear(); 12252 ValueExprMap.clear(); 12253 HasRecMap.clear(); 12254 BackedgeTakenCounts.clear(); 12255 PredicatedBackedgeTakenCounts.clear(); 12256 12257 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12258 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12259 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12260 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12261 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12262 } 12263 12264 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12265 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12266 } 12267 12268 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12269 const Loop *L) { 12270 // Print all inner loops first 12271 for (Loop *I : *L) 12272 PrintLoopInfo(OS, SE, I); 12273 12274 OS << "Loop "; 12275 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12276 OS << ": "; 12277 12278 SmallVector<BasicBlock *, 8> ExitingBlocks; 12279 L->getExitingBlocks(ExitingBlocks); 12280 if (ExitingBlocks.size() != 1) 12281 OS << "<multiple exits> "; 12282 12283 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12284 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12285 else 12286 OS << "Unpredictable backedge-taken count.\n"; 12287 12288 if (ExitingBlocks.size() > 1) 12289 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12290 OS << " exit count for " << ExitingBlock->getName() << ": " 12291 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12292 } 12293 12294 OS << "Loop "; 12295 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12296 OS << ": "; 12297 12298 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12299 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12300 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12301 OS << ", actual taken count either this or zero."; 12302 } else { 12303 OS << "Unpredictable max backedge-taken count. "; 12304 } 12305 12306 OS << "\n" 12307 "Loop "; 12308 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12309 OS << ": "; 12310 12311 SCEVUnionPredicate Pred; 12312 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12313 if (!isa<SCEVCouldNotCompute>(PBT)) { 12314 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12315 OS << " Predicates:\n"; 12316 Pred.print(OS, 4); 12317 } else { 12318 OS << "Unpredictable predicated backedge-taken count. "; 12319 } 12320 OS << "\n"; 12321 12322 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12323 OS << "Loop "; 12324 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12325 OS << ": "; 12326 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12327 } 12328 } 12329 12330 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12331 switch (LD) { 12332 case ScalarEvolution::LoopVariant: 12333 return "Variant"; 12334 case ScalarEvolution::LoopInvariant: 12335 return "Invariant"; 12336 case ScalarEvolution::LoopComputable: 12337 return "Computable"; 12338 } 12339 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12340 } 12341 12342 void ScalarEvolution::print(raw_ostream &OS) const { 12343 // ScalarEvolution's implementation of the print method is to print 12344 // out SCEV values of all instructions that are interesting. Doing 12345 // this potentially causes it to create new SCEV objects though, 12346 // which technically conflicts with the const qualifier. This isn't 12347 // observable from outside the class though, so casting away the 12348 // const isn't dangerous. 12349 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12350 12351 if (ClassifyExpressions) { 12352 OS << "Classifying expressions for: "; 12353 F.printAsOperand(OS, /*PrintType=*/false); 12354 OS << "\n"; 12355 for (Instruction &I : instructions(F)) 12356 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12357 OS << I << '\n'; 12358 OS << " --> "; 12359 const SCEV *SV = SE.getSCEV(&I); 12360 SV->print(OS); 12361 if (!isa<SCEVCouldNotCompute>(SV)) { 12362 OS << " U: "; 12363 SE.getUnsignedRange(SV).print(OS); 12364 OS << " S: "; 12365 SE.getSignedRange(SV).print(OS); 12366 } 12367 12368 const Loop *L = LI.getLoopFor(I.getParent()); 12369 12370 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12371 if (AtUse != SV) { 12372 OS << " --> "; 12373 AtUse->print(OS); 12374 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12375 OS << " U: "; 12376 SE.getUnsignedRange(AtUse).print(OS); 12377 OS << " S: "; 12378 SE.getSignedRange(AtUse).print(OS); 12379 } 12380 } 12381 12382 if (L) { 12383 OS << "\t\t" "Exits: "; 12384 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12385 if (!SE.isLoopInvariant(ExitValue, L)) { 12386 OS << "<<Unknown>>"; 12387 } else { 12388 OS << *ExitValue; 12389 } 12390 12391 bool First = true; 12392 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12393 if (First) { 12394 OS << "\t\t" "LoopDispositions: { "; 12395 First = false; 12396 } else { 12397 OS << ", "; 12398 } 12399 12400 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12401 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12402 } 12403 12404 for (auto *InnerL : depth_first(L)) { 12405 if (InnerL == L) 12406 continue; 12407 if (First) { 12408 OS << "\t\t" "LoopDispositions: { "; 12409 First = false; 12410 } else { 12411 OS << ", "; 12412 } 12413 12414 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12415 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12416 } 12417 12418 OS << " }"; 12419 } 12420 12421 OS << "\n"; 12422 } 12423 } 12424 12425 OS << "Determining loop execution counts for: "; 12426 F.printAsOperand(OS, /*PrintType=*/false); 12427 OS << "\n"; 12428 for (Loop *I : LI) 12429 PrintLoopInfo(OS, &SE, I); 12430 } 12431 12432 ScalarEvolution::LoopDisposition 12433 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12434 auto &Values = LoopDispositions[S]; 12435 for (auto &V : Values) { 12436 if (V.getPointer() == L) 12437 return V.getInt(); 12438 } 12439 Values.emplace_back(L, LoopVariant); 12440 LoopDisposition D = computeLoopDisposition(S, L); 12441 auto &Values2 = LoopDispositions[S]; 12442 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12443 if (V.getPointer() == L) { 12444 V.setInt(D); 12445 break; 12446 } 12447 } 12448 return D; 12449 } 12450 12451 ScalarEvolution::LoopDisposition 12452 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12453 switch (S->getSCEVType()) { 12454 case scConstant: 12455 return LoopInvariant; 12456 case scPtrToInt: 12457 case scTruncate: 12458 case scZeroExtend: 12459 case scSignExtend: 12460 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12461 case scAddRecExpr: { 12462 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12463 12464 // If L is the addrec's loop, it's computable. 12465 if (AR->getLoop() == L) 12466 return LoopComputable; 12467 12468 // Add recurrences are never invariant in the function-body (null loop). 12469 if (!L) 12470 return LoopVariant; 12471 12472 // Everything that is not defined at loop entry is variant. 12473 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12474 return LoopVariant; 12475 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12476 " dominate the contained loop's header?"); 12477 12478 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12479 if (AR->getLoop()->contains(L)) 12480 return LoopInvariant; 12481 12482 // This recurrence is variant w.r.t. L if any of its operands 12483 // are variant. 12484 for (auto *Op : AR->operands()) 12485 if (!isLoopInvariant(Op, L)) 12486 return LoopVariant; 12487 12488 // Otherwise it's loop-invariant. 12489 return LoopInvariant; 12490 } 12491 case scAddExpr: 12492 case scMulExpr: 12493 case scUMaxExpr: 12494 case scSMaxExpr: 12495 case scUMinExpr: 12496 case scSMinExpr: { 12497 bool HasVarying = false; 12498 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12499 LoopDisposition D = getLoopDisposition(Op, L); 12500 if (D == LoopVariant) 12501 return LoopVariant; 12502 if (D == LoopComputable) 12503 HasVarying = true; 12504 } 12505 return HasVarying ? LoopComputable : LoopInvariant; 12506 } 12507 case scUDivExpr: { 12508 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12509 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12510 if (LD == LoopVariant) 12511 return LoopVariant; 12512 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12513 if (RD == LoopVariant) 12514 return LoopVariant; 12515 return (LD == LoopInvariant && RD == LoopInvariant) ? 12516 LoopInvariant : LoopComputable; 12517 } 12518 case scUnknown: 12519 // All non-instruction values are loop invariant. All instructions are loop 12520 // invariant if they are not contained in the specified loop. 12521 // Instructions are never considered invariant in the function body 12522 // (null loop) because they are defined within the "loop". 12523 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12524 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12525 return LoopInvariant; 12526 case scCouldNotCompute: 12527 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12528 } 12529 llvm_unreachable("Unknown SCEV kind!"); 12530 } 12531 12532 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 12533 return getLoopDisposition(S, L) == LoopInvariant; 12534 } 12535 12536 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 12537 return getLoopDisposition(S, L) == LoopComputable; 12538 } 12539 12540 ScalarEvolution::BlockDisposition 12541 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12542 auto &Values = BlockDispositions[S]; 12543 for (auto &V : Values) { 12544 if (V.getPointer() == BB) 12545 return V.getInt(); 12546 } 12547 Values.emplace_back(BB, DoesNotDominateBlock); 12548 BlockDisposition D = computeBlockDisposition(S, BB); 12549 auto &Values2 = BlockDispositions[S]; 12550 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12551 if (V.getPointer() == BB) { 12552 V.setInt(D); 12553 break; 12554 } 12555 } 12556 return D; 12557 } 12558 12559 ScalarEvolution::BlockDisposition 12560 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12561 switch (S->getSCEVType()) { 12562 case scConstant: 12563 return ProperlyDominatesBlock; 12564 case scPtrToInt: 12565 case scTruncate: 12566 case scZeroExtend: 12567 case scSignExtend: 12568 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 12569 case scAddRecExpr: { 12570 // This uses a "dominates" query instead of "properly dominates" query 12571 // to test for proper dominance too, because the instruction which 12572 // produces the addrec's value is a PHI, and a PHI effectively properly 12573 // dominates its entire containing block. 12574 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12575 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 12576 return DoesNotDominateBlock; 12577 12578 // Fall through into SCEVNAryExpr handling. 12579 LLVM_FALLTHROUGH; 12580 } 12581 case scAddExpr: 12582 case scMulExpr: 12583 case scUMaxExpr: 12584 case scSMaxExpr: 12585 case scUMinExpr: 12586 case scSMinExpr: { 12587 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12588 bool Proper = true; 12589 for (const SCEV *NAryOp : NAry->operands()) { 12590 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12591 if (D == DoesNotDominateBlock) 12592 return DoesNotDominateBlock; 12593 if (D == DominatesBlock) 12594 Proper = false; 12595 } 12596 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12597 } 12598 case scUDivExpr: { 12599 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12600 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12601 BlockDisposition LD = getBlockDisposition(LHS, BB); 12602 if (LD == DoesNotDominateBlock) 12603 return DoesNotDominateBlock; 12604 BlockDisposition RD = getBlockDisposition(RHS, BB); 12605 if (RD == DoesNotDominateBlock) 12606 return DoesNotDominateBlock; 12607 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12608 ProperlyDominatesBlock : DominatesBlock; 12609 } 12610 case scUnknown: 12611 if (Instruction *I = 12612 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12613 if (I->getParent() == BB) 12614 return DominatesBlock; 12615 if (DT.properlyDominates(I->getParent(), BB)) 12616 return ProperlyDominatesBlock; 12617 return DoesNotDominateBlock; 12618 } 12619 return ProperlyDominatesBlock; 12620 case scCouldNotCompute: 12621 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12622 } 12623 llvm_unreachable("Unknown SCEV kind!"); 12624 } 12625 12626 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12627 return getBlockDisposition(S, BB) >= DominatesBlock; 12628 } 12629 12630 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12631 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12632 } 12633 12634 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12635 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12636 } 12637 12638 void 12639 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12640 ValuesAtScopes.erase(S); 12641 LoopDispositions.erase(S); 12642 BlockDispositions.erase(S); 12643 UnsignedRanges.erase(S); 12644 SignedRanges.erase(S); 12645 ExprValueMap.erase(S); 12646 HasRecMap.erase(S); 12647 MinTrailingZerosCache.erase(S); 12648 12649 for (auto I = PredicatedSCEVRewrites.begin(); 12650 I != PredicatedSCEVRewrites.end();) { 12651 std::pair<const SCEV *, const Loop *> Entry = I->first; 12652 if (Entry.first == S) 12653 PredicatedSCEVRewrites.erase(I++); 12654 else 12655 ++I; 12656 } 12657 12658 auto RemoveSCEVFromBackedgeMap = 12659 [S](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12660 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12661 BackedgeTakenInfo &BEInfo = I->second; 12662 if (BEInfo.hasOperand(S)) 12663 Map.erase(I++); 12664 else 12665 ++I; 12666 } 12667 }; 12668 12669 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12670 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12671 } 12672 12673 void 12674 ScalarEvolution::getUsedLoops(const SCEV *S, 12675 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12676 struct FindUsedLoops { 12677 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12678 : LoopsUsed(LoopsUsed) {} 12679 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12680 bool follow(const SCEV *S) { 12681 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12682 LoopsUsed.insert(AR->getLoop()); 12683 return true; 12684 } 12685 12686 bool isDone() const { return false; } 12687 }; 12688 12689 FindUsedLoops F(LoopsUsed); 12690 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12691 } 12692 12693 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12694 SmallPtrSet<const Loop *, 8> LoopsUsed; 12695 getUsedLoops(S, LoopsUsed); 12696 for (auto *L : LoopsUsed) 12697 LoopUsers[L].push_back(S); 12698 } 12699 12700 void ScalarEvolution::verify() const { 12701 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12702 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12703 12704 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12705 12706 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12707 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12708 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12709 12710 const SCEV *visitConstant(const SCEVConstant *Constant) { 12711 return SE.getConstant(Constant->getAPInt()); 12712 } 12713 12714 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12715 return SE.getUnknown(Expr->getValue()); 12716 } 12717 12718 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12719 return SE.getCouldNotCompute(); 12720 } 12721 }; 12722 12723 SCEVMapper SCM(SE2); 12724 12725 while (!LoopStack.empty()) { 12726 auto *L = LoopStack.pop_back_val(); 12727 llvm::append_range(LoopStack, *L); 12728 12729 auto *CurBECount = SCM.visit( 12730 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12731 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12732 12733 if (CurBECount == SE2.getCouldNotCompute() || 12734 NewBECount == SE2.getCouldNotCompute()) { 12735 // NB! This situation is legal, but is very suspicious -- whatever pass 12736 // change the loop to make a trip count go from could not compute to 12737 // computable or vice-versa *should have* invalidated SCEV. However, we 12738 // choose not to assert here (for now) since we don't want false 12739 // positives. 12740 continue; 12741 } 12742 12743 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12744 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12745 // not propagate undef aggressively). This means we can (and do) fail 12746 // verification in cases where a transform makes the trip count of a loop 12747 // go from "undef" to "undef+1" (say). The transform is fine, since in 12748 // both cases the loop iterates "undef" times, but SCEV thinks we 12749 // increased the trip count of the loop by 1 incorrectly. 12750 continue; 12751 } 12752 12753 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12754 SE.getTypeSizeInBits(NewBECount->getType())) 12755 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12756 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12757 SE.getTypeSizeInBits(NewBECount->getType())) 12758 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12759 12760 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12761 12762 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12763 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12764 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12765 dbgs() << "Old: " << *CurBECount << "\n"; 12766 dbgs() << "New: " << *NewBECount << "\n"; 12767 dbgs() << "Delta: " << *Delta << "\n"; 12768 std::abort(); 12769 } 12770 } 12771 12772 // Collect all valid loops currently in LoopInfo. 12773 SmallPtrSet<Loop *, 32> ValidLoops; 12774 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12775 while (!Worklist.empty()) { 12776 Loop *L = Worklist.pop_back_val(); 12777 if (ValidLoops.contains(L)) 12778 continue; 12779 ValidLoops.insert(L); 12780 Worklist.append(L->begin(), L->end()); 12781 } 12782 // Check for SCEV expressions referencing invalid/deleted loops. 12783 for (auto &KV : ValueExprMap) { 12784 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12785 if (!AR) 12786 continue; 12787 assert(ValidLoops.contains(AR->getLoop()) && 12788 "AddRec references invalid loop"); 12789 } 12790 } 12791 12792 bool ScalarEvolution::invalidate( 12793 Function &F, const PreservedAnalyses &PA, 12794 FunctionAnalysisManager::Invalidator &Inv) { 12795 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12796 // of its dependencies is invalidated. 12797 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12798 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12799 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12800 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12801 Inv.invalidate<LoopAnalysis>(F, PA); 12802 } 12803 12804 AnalysisKey ScalarEvolutionAnalysis::Key; 12805 12806 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12807 FunctionAnalysisManager &AM) { 12808 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12809 AM.getResult<AssumptionAnalysis>(F), 12810 AM.getResult<DominatorTreeAnalysis>(F), 12811 AM.getResult<LoopAnalysis>(F)); 12812 } 12813 12814 PreservedAnalyses 12815 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12816 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12817 return PreservedAnalyses::all(); 12818 } 12819 12820 PreservedAnalyses 12821 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12822 // For compatibility with opt's -analyze feature under legacy pass manager 12823 // which was not ported to NPM. This keeps tests using 12824 // update_analyze_test_checks.py working. 12825 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12826 << F.getName() << "':\n"; 12827 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12828 return PreservedAnalyses::all(); 12829 } 12830 12831 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12832 "Scalar Evolution Analysis", false, true) 12833 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12834 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12835 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12836 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12837 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12838 "Scalar Evolution Analysis", false, true) 12839 12840 char ScalarEvolutionWrapperPass::ID = 0; 12841 12842 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12843 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12844 } 12845 12846 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12847 SE.reset(new ScalarEvolution( 12848 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12849 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12850 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12851 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12852 return false; 12853 } 12854 12855 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12856 12857 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12858 SE->print(OS); 12859 } 12860 12861 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12862 if (!VerifySCEV) 12863 return; 12864 12865 SE->verify(); 12866 } 12867 12868 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12869 AU.setPreservesAll(); 12870 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12871 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12872 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12873 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12874 } 12875 12876 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12877 const SCEV *RHS) { 12878 FoldingSetNodeID ID; 12879 assert(LHS->getType() == RHS->getType() && 12880 "Type mismatch between LHS and RHS"); 12881 // Unique this node based on the arguments 12882 ID.AddInteger(SCEVPredicate::P_Equal); 12883 ID.AddPointer(LHS); 12884 ID.AddPointer(RHS); 12885 void *IP = nullptr; 12886 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12887 return S; 12888 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12889 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12890 UniquePreds.InsertNode(Eq, IP); 12891 return Eq; 12892 } 12893 12894 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12895 const SCEVAddRecExpr *AR, 12896 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12897 FoldingSetNodeID ID; 12898 // Unique this node based on the arguments 12899 ID.AddInteger(SCEVPredicate::P_Wrap); 12900 ID.AddPointer(AR); 12901 ID.AddInteger(AddedFlags); 12902 void *IP = nullptr; 12903 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12904 return S; 12905 auto *OF = new (SCEVAllocator) 12906 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12907 UniquePreds.InsertNode(OF, IP); 12908 return OF; 12909 } 12910 12911 namespace { 12912 12913 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12914 public: 12915 12916 /// Rewrites \p S in the context of a loop L and the SCEV predication 12917 /// infrastructure. 12918 /// 12919 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12920 /// equivalences present in \p Pred. 12921 /// 12922 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12923 /// \p NewPreds such that the result will be an AddRecExpr. 12924 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12925 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12926 SCEVUnionPredicate *Pred) { 12927 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12928 return Rewriter.visit(S); 12929 } 12930 12931 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12932 if (Pred) { 12933 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12934 for (auto *Pred : ExprPreds) 12935 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12936 if (IPred->getLHS() == Expr) 12937 return IPred->getRHS(); 12938 } 12939 return convertToAddRecWithPreds(Expr); 12940 } 12941 12942 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12943 const SCEV *Operand = visit(Expr->getOperand()); 12944 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12945 if (AR && AR->getLoop() == L && AR->isAffine()) { 12946 // This couldn't be folded because the operand didn't have the nuw 12947 // flag. Add the nusw flag as an assumption that we could make. 12948 const SCEV *Step = AR->getStepRecurrence(SE); 12949 Type *Ty = Expr->getType(); 12950 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12951 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12952 SE.getSignExtendExpr(Step, Ty), L, 12953 AR->getNoWrapFlags()); 12954 } 12955 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12956 } 12957 12958 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12959 const SCEV *Operand = visit(Expr->getOperand()); 12960 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12961 if (AR && AR->getLoop() == L && AR->isAffine()) { 12962 // This couldn't be folded because the operand didn't have the nsw 12963 // flag. Add the nssw flag as an assumption that we could make. 12964 const SCEV *Step = AR->getStepRecurrence(SE); 12965 Type *Ty = Expr->getType(); 12966 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12967 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12968 SE.getSignExtendExpr(Step, Ty), L, 12969 AR->getNoWrapFlags()); 12970 } 12971 return SE.getSignExtendExpr(Operand, Expr->getType()); 12972 } 12973 12974 private: 12975 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12976 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12977 SCEVUnionPredicate *Pred) 12978 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12979 12980 bool addOverflowAssumption(const SCEVPredicate *P) { 12981 if (!NewPreds) { 12982 // Check if we've already made this assumption. 12983 return Pred && Pred->implies(P); 12984 } 12985 NewPreds->insert(P); 12986 return true; 12987 } 12988 12989 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12990 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12991 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12992 return addOverflowAssumption(A); 12993 } 12994 12995 // If \p Expr represents a PHINode, we try to see if it can be represented 12996 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12997 // to add this predicate as a runtime overflow check, we return the AddRec. 12998 // If \p Expr does not meet these conditions (is not a PHI node, or we 12999 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13000 // return \p Expr. 13001 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13002 if (!isa<PHINode>(Expr->getValue())) 13003 return Expr; 13004 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13005 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13006 if (!PredicatedRewrite) 13007 return Expr; 13008 for (auto *P : PredicatedRewrite->second){ 13009 // Wrap predicates from outer loops are not supported. 13010 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13011 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 13012 if (L != AR->getLoop()) 13013 return Expr; 13014 } 13015 if (!addOverflowAssumption(P)) 13016 return Expr; 13017 } 13018 return PredicatedRewrite->first; 13019 } 13020 13021 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13022 SCEVUnionPredicate *Pred; 13023 const Loop *L; 13024 }; 13025 13026 } // end anonymous namespace 13027 13028 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13029 SCEVUnionPredicate &Preds) { 13030 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13031 } 13032 13033 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13034 const SCEV *S, const Loop *L, 13035 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13036 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13037 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13038 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13039 13040 if (!AddRec) 13041 return nullptr; 13042 13043 // Since the transformation was successful, we can now transfer the SCEV 13044 // predicates. 13045 for (auto *P : TransformPreds) 13046 Preds.insert(P); 13047 13048 return AddRec; 13049 } 13050 13051 /// SCEV predicates 13052 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13053 SCEVPredicateKind Kind) 13054 : FastID(ID), Kind(Kind) {} 13055 13056 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 13057 const SCEV *LHS, const SCEV *RHS) 13058 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 13059 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13060 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13061 } 13062 13063 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 13064 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 13065 13066 if (!Op) 13067 return false; 13068 13069 return Op->LHS == LHS && Op->RHS == RHS; 13070 } 13071 13072 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 13073 13074 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 13075 13076 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 13077 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13078 } 13079 13080 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13081 const SCEVAddRecExpr *AR, 13082 IncrementWrapFlags Flags) 13083 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13084 13085 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 13086 13087 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 13088 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 13089 13090 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 13091 } 13092 13093 bool SCEVWrapPredicate::isAlwaysTrue() const { 13094 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 13095 IncrementWrapFlags IFlags = Flags; 13096 13097 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 13098 IFlags = clearFlags(IFlags, IncrementNSSW); 13099 13100 return IFlags == IncrementAnyWrap; 13101 } 13102 13103 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 13104 OS.indent(Depth) << *getExpr() << " Added Flags: "; 13105 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 13106 OS << "<nusw>"; 13107 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 13108 OS << "<nssw>"; 13109 OS << "\n"; 13110 } 13111 13112 SCEVWrapPredicate::IncrementWrapFlags 13113 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 13114 ScalarEvolution &SE) { 13115 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 13116 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 13117 13118 // We can safely transfer the NSW flag as NSSW. 13119 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 13120 ImpliedFlags = IncrementNSSW; 13121 13122 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 13123 // If the increment is positive, the SCEV NUW flag will also imply the 13124 // WrapPredicate NUSW flag. 13125 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 13126 if (Step->getValue()->getValue().isNonNegative()) 13127 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 13128 } 13129 13130 return ImpliedFlags; 13131 } 13132 13133 /// Union predicates don't get cached so create a dummy set ID for it. 13134 SCEVUnionPredicate::SCEVUnionPredicate() 13135 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 13136 13137 bool SCEVUnionPredicate::isAlwaysTrue() const { 13138 return all_of(Preds, 13139 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 13140 } 13141 13142 ArrayRef<const SCEVPredicate *> 13143 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 13144 auto I = SCEVToPreds.find(Expr); 13145 if (I == SCEVToPreds.end()) 13146 return ArrayRef<const SCEVPredicate *>(); 13147 return I->second; 13148 } 13149 13150 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 13151 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 13152 return all_of(Set->Preds, 13153 [this](const SCEVPredicate *I) { return this->implies(I); }); 13154 13155 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 13156 if (ScevPredsIt == SCEVToPreds.end()) 13157 return false; 13158 auto &SCEVPreds = ScevPredsIt->second; 13159 13160 return any_of(SCEVPreds, 13161 [N](const SCEVPredicate *I) { return I->implies(N); }); 13162 } 13163 13164 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 13165 13166 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 13167 for (auto Pred : Preds) 13168 Pred->print(OS, Depth); 13169 } 13170 13171 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 13172 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 13173 for (auto Pred : Set->Preds) 13174 add(Pred); 13175 return; 13176 } 13177 13178 if (implies(N)) 13179 return; 13180 13181 const SCEV *Key = N->getExpr(); 13182 assert(Key && "Only SCEVUnionPredicate doesn't have an " 13183 " associated expression!"); 13184 13185 SCEVToPreds[Key].push_back(N); 13186 Preds.push_back(N); 13187 } 13188 13189 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 13190 Loop &L) 13191 : SE(SE), L(L) {} 13192 13193 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 13194 const SCEV *Expr = SE.getSCEV(V); 13195 RewriteEntry &Entry = RewriteMap[Expr]; 13196 13197 // If we already have an entry and the version matches, return it. 13198 if (Entry.second && Generation == Entry.first) 13199 return Entry.second; 13200 13201 // We found an entry but it's stale. Rewrite the stale entry 13202 // according to the current predicate. 13203 if (Entry.second) 13204 Expr = Entry.second; 13205 13206 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 13207 Entry = {Generation, NewSCEV}; 13208 13209 return NewSCEV; 13210 } 13211 13212 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13213 if (!BackedgeCount) { 13214 SCEVUnionPredicate BackedgePred; 13215 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 13216 addPredicate(BackedgePred); 13217 } 13218 return BackedgeCount; 13219 } 13220 13221 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13222 if (Preds.implies(&Pred)) 13223 return; 13224 Preds.add(&Pred); 13225 updateGeneration(); 13226 } 13227 13228 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 13229 return Preds; 13230 } 13231 13232 void PredicatedScalarEvolution::updateGeneration() { 13233 // If the generation number wrapped recompute everything. 13234 if (++Generation == 0) { 13235 for (auto &II : RewriteMap) { 13236 const SCEV *Rewritten = II.second.second; 13237 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 13238 } 13239 } 13240 } 13241 13242 void PredicatedScalarEvolution::setNoOverflow( 13243 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13244 const SCEV *Expr = getSCEV(V); 13245 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13246 13247 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13248 13249 // Clear the statically implied flags. 13250 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13251 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13252 13253 auto II = FlagsMap.insert({V, Flags}); 13254 if (!II.second) 13255 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13256 } 13257 13258 bool PredicatedScalarEvolution::hasNoOverflow( 13259 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13260 const SCEV *Expr = getSCEV(V); 13261 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13262 13263 Flags = SCEVWrapPredicate::clearFlags( 13264 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13265 13266 auto II = FlagsMap.find(V); 13267 13268 if (II != FlagsMap.end()) 13269 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13270 13271 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13272 } 13273 13274 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13275 const SCEV *Expr = this->getSCEV(V); 13276 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13277 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13278 13279 if (!New) 13280 return nullptr; 13281 13282 for (auto *P : NewPreds) 13283 Preds.add(P); 13284 13285 updateGeneration(); 13286 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13287 return New; 13288 } 13289 13290 PredicatedScalarEvolution::PredicatedScalarEvolution( 13291 const PredicatedScalarEvolution &Init) 13292 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13293 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13294 for (auto I : Init.FlagsMap) 13295 FlagsMap.insert(I); 13296 } 13297 13298 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13299 // For each block. 13300 for (auto *BB : L.getBlocks()) 13301 for (auto &I : *BB) { 13302 if (!SE.isSCEVable(I.getType())) 13303 continue; 13304 13305 auto *Expr = SE.getSCEV(&I); 13306 auto II = RewriteMap.find(Expr); 13307 13308 if (II == RewriteMap.end()) 13309 continue; 13310 13311 // Don't print things that are not interesting. 13312 if (II->second.second == Expr) 13313 continue; 13314 13315 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13316 OS.indent(Depth + 2) << *Expr << "\n"; 13317 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13318 } 13319 } 13320 13321 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13322 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13323 // for URem with constant power-of-2 second operands. 13324 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13325 // 4, A / B becomes X / 8). 13326 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13327 const SCEV *&RHS) { 13328 // Try to match 'zext (trunc A to iB) to iY', which is used 13329 // for URem with constant power-of-2 second operands. Make sure the size of 13330 // the operand A matches the size of the whole expressions. 13331 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13332 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13333 LHS = Trunc->getOperand(); 13334 // Bail out if the type of the LHS is larger than the type of the 13335 // expression for now. 13336 if (getTypeSizeInBits(LHS->getType()) > 13337 getTypeSizeInBits(Expr->getType())) 13338 return false; 13339 if (LHS->getType() != Expr->getType()) 13340 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13341 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13342 << getTypeSizeInBits(Trunc->getType())); 13343 return true; 13344 } 13345 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13346 if (Add == nullptr || Add->getNumOperands() != 2) 13347 return false; 13348 13349 const SCEV *A = Add->getOperand(1); 13350 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13351 13352 if (Mul == nullptr) 13353 return false; 13354 13355 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13356 // (SomeExpr + (-(SomeExpr / B) * B)). 13357 if (Expr == getURemExpr(A, B)) { 13358 LHS = A; 13359 RHS = B; 13360 return true; 13361 } 13362 return false; 13363 }; 13364 13365 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13366 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13367 return MatchURemWithDivisor(Mul->getOperand(1)) || 13368 MatchURemWithDivisor(Mul->getOperand(2)); 13369 13370 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13371 if (Mul->getNumOperands() == 2) 13372 return MatchURemWithDivisor(Mul->getOperand(1)) || 13373 MatchURemWithDivisor(Mul->getOperand(0)) || 13374 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 13375 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 13376 return false; 13377 } 13378 13379 const SCEV * 13380 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 13381 SmallVector<BasicBlock*, 16> ExitingBlocks; 13382 L->getExitingBlocks(ExitingBlocks); 13383 13384 // Form an expression for the maximum exit count possible for this loop. We 13385 // merge the max and exact information to approximate a version of 13386 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 13387 SmallVector<const SCEV*, 4> ExitCounts; 13388 for (BasicBlock *ExitingBB : ExitingBlocks) { 13389 const SCEV *ExitCount = getExitCount(L, ExitingBB); 13390 if (isa<SCEVCouldNotCompute>(ExitCount)) 13391 ExitCount = getExitCount(L, ExitingBB, 13392 ScalarEvolution::ConstantMaximum); 13393 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 13394 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 13395 "We should only have known counts for exiting blocks that " 13396 "dominate latch!"); 13397 ExitCounts.push_back(ExitCount); 13398 } 13399 } 13400 if (ExitCounts.empty()) 13401 return getCouldNotCompute(); 13402 return getUMinFromMismatchedTypes(ExitCounts); 13403 } 13404 13405 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 13406 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 13407 /// we cannot guarantee that the replacement is loop invariant in the loop of 13408 /// the AddRec. 13409 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 13410 ValueToSCEVMapTy ⤅ 13411 13412 public: 13413 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 13414 : SCEVRewriteVisitor(SE), Map(M) {} 13415 13416 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 13417 13418 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13419 auto I = Map.find(Expr->getValue()); 13420 if (I == Map.end()) 13421 return Expr; 13422 return I->second; 13423 } 13424 }; 13425 13426 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 13427 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 13428 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 13429 // If we have LHS == 0, check if LHS is computing a property of some unknown 13430 // SCEV %v which we can rewrite %v to express explicitly. 13431 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 13432 if (Predicate == CmpInst::ICMP_EQ && RHSC && 13433 RHSC->getValue()->isNullValue()) { 13434 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 13435 // explicitly express that. 13436 const SCEV *URemLHS = nullptr; 13437 const SCEV *URemRHS = nullptr; 13438 if (matchURem(LHS, URemLHS, URemRHS)) { 13439 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 13440 Value *V = LHSUnknown->getValue(); 13441 auto Multiple = 13442 getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS, 13443 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 13444 RewriteMap[V] = Multiple; 13445 return; 13446 } 13447 } 13448 } 13449 13450 if (!isa<SCEVUnknown>(LHS)) { 13451 std::swap(LHS, RHS); 13452 Predicate = CmpInst::getSwappedPredicate(Predicate); 13453 } 13454 13455 // For now, limit to conditions that provide information about unknown 13456 // expressions. 13457 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 13458 if (!LHSUnknown) 13459 return; 13460 13461 // Check whether LHS has already been rewritten. In that case we want to 13462 // chain further rewrites onto the already rewritten value. 13463 auto I = RewriteMap.find(LHSUnknown->getValue()); 13464 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 13465 13466 // TODO: use information from more predicates. 13467 switch (Predicate) { 13468 case CmpInst::ICMP_ULT: 13469 if (!containsAddRecurrence(RHS)) 13470 RewriteMap[LHSUnknown->getValue()] = getUMinExpr( 13471 RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13472 break; 13473 case CmpInst::ICMP_ULE: 13474 if (!containsAddRecurrence(RHS)) 13475 RewriteMap[LHSUnknown->getValue()] = getUMinExpr(RewrittenLHS, RHS); 13476 break; 13477 case CmpInst::ICMP_UGT: 13478 if (!containsAddRecurrence(RHS)) 13479 RewriteMap[LHSUnknown->getValue()] = 13480 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13481 break; 13482 case CmpInst::ICMP_UGE: 13483 if (!containsAddRecurrence(RHS)) 13484 RewriteMap[LHSUnknown->getValue()] = getUMaxExpr(RewrittenLHS, RHS); 13485 break; 13486 case CmpInst::ICMP_EQ: 13487 if (isa<SCEVConstant>(RHS)) 13488 RewriteMap[LHSUnknown->getValue()] = RHS; 13489 break; 13490 case CmpInst::ICMP_NE: 13491 if (isa<SCEVConstant>(RHS) && 13492 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 13493 RewriteMap[LHSUnknown->getValue()] = 13494 getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 13495 break; 13496 default: 13497 break; 13498 } 13499 }; 13500 // Starting at the loop predecessor, climb up the predecessor chain, as long 13501 // as there are predecessors that can be found that have unique successors 13502 // leading to the original header. 13503 // TODO: share this logic with isLoopEntryGuardedByCond. 13504 ValueToSCEVMapTy RewriteMap; 13505 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 13506 L->getLoopPredecessor(), L->getHeader()); 13507 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 13508 13509 const BranchInst *LoopEntryPredicate = 13510 dyn_cast<BranchInst>(Pair.first->getTerminator()); 13511 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 13512 continue; 13513 13514 bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second; 13515 SmallVector<Value *, 8> Worklist; 13516 SmallPtrSet<Value *, 8> Visited; 13517 Worklist.push_back(LoopEntryPredicate->getCondition()); 13518 while (!Worklist.empty()) { 13519 Value *Cond = Worklist.pop_back_val(); 13520 if (!Visited.insert(Cond).second) 13521 continue; 13522 13523 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 13524 auto Predicate = 13525 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 13526 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 13527 getSCEV(Cmp->getOperand(1)), RewriteMap); 13528 continue; 13529 } 13530 13531 Value *L, *R; 13532 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 13533 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 13534 Worklist.push_back(L); 13535 Worklist.push_back(R); 13536 } 13537 } 13538 } 13539 13540 // Also collect information from assumptions dominating the loop. 13541 for (auto &AssumeVH : AC.assumptions()) { 13542 if (!AssumeVH) 13543 continue; 13544 auto *AssumeI = cast<CallInst>(AssumeVH); 13545 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 13546 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 13547 continue; 13548 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 13549 getSCEV(Cmp->getOperand(1)), RewriteMap); 13550 } 13551 13552 if (RewriteMap.empty()) 13553 return Expr; 13554 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 13555 return Rewriter.visit(Expr); 13556 } 13557