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 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 325 I != E; ++I) { 326 OS << **I; 327 if (std::next(I) != E) 328 OS << OpStr; 329 } 330 OS << ")"; 331 switch (NAry->getSCEVType()) { 332 case scAddExpr: 333 case scMulExpr: 334 if (NAry->hasNoUnsignedWrap()) 335 OS << "<nuw>"; 336 if (NAry->hasNoSignedWrap()) 337 OS << "<nsw>"; 338 break; 339 default: 340 // Nothing to print for other nary expressions. 341 break; 342 } 343 return; 344 } 345 case scUDivExpr: { 346 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 347 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 348 return; 349 } 350 case scUnknown: { 351 const SCEVUnknown *U = cast<SCEVUnknown>(this); 352 Type *AllocTy; 353 if (U->isSizeOf(AllocTy)) { 354 OS << "sizeof(" << *AllocTy << ")"; 355 return; 356 } 357 if (U->isAlignOf(AllocTy)) { 358 OS << "alignof(" << *AllocTy << ")"; 359 return; 360 } 361 362 Type *CTy; 363 Constant *FieldNo; 364 if (U->isOffsetOf(CTy, FieldNo)) { 365 OS << "offsetof(" << *CTy << ", "; 366 FieldNo->printAsOperand(OS, false); 367 OS << ")"; 368 return; 369 } 370 371 // Otherwise just print it normally. 372 U->getValue()->printAsOperand(OS, false); 373 return; 374 } 375 case scCouldNotCompute: 376 OS << "***COULDNOTCOMPUTE***"; 377 return; 378 } 379 llvm_unreachable("Unknown SCEV kind!"); 380 } 381 382 Type *SCEV::getType() const { 383 switch (getSCEVType()) { 384 case scConstant: 385 return cast<SCEVConstant>(this)->getType(); 386 case scPtrToInt: 387 case scTruncate: 388 case scZeroExtend: 389 case scSignExtend: 390 return cast<SCEVCastExpr>(this)->getType(); 391 case scAddRecExpr: 392 case scMulExpr: 393 case scUMaxExpr: 394 case scSMaxExpr: 395 case scUMinExpr: 396 case scSMinExpr: 397 return cast<SCEVNAryExpr>(this)->getType(); 398 case scAddExpr: 399 return cast<SCEVAddExpr>(this)->getType(); 400 case scUDivExpr: 401 return cast<SCEVUDivExpr>(this)->getType(); 402 case scUnknown: 403 return cast<SCEVUnknown>(this)->getType(); 404 case scCouldNotCompute: 405 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 406 } 407 llvm_unreachable("Unknown SCEV kind!"); 408 } 409 410 bool SCEV::isZero() const { 411 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 412 return SC->getValue()->isZero(); 413 return false; 414 } 415 416 bool SCEV::isOne() const { 417 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 418 return SC->getValue()->isOne(); 419 return false; 420 } 421 422 bool SCEV::isAllOnesValue() const { 423 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 424 return SC->getValue()->isMinusOne(); 425 return false; 426 } 427 428 bool SCEV::isNonConstantNegative() const { 429 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 430 if (!Mul) return false; 431 432 // If there is a constant factor, it will be first. 433 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 434 if (!SC) return false; 435 436 // Return true if the value is negative, this matches things like (-42 * V). 437 return SC->getAPInt().isNegative(); 438 } 439 440 SCEVCouldNotCompute::SCEVCouldNotCompute() : 441 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 442 443 bool SCEVCouldNotCompute::classof(const SCEV *S) { 444 return S->getSCEVType() == scCouldNotCompute; 445 } 446 447 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 448 FoldingSetNodeID ID; 449 ID.AddInteger(scConstant); 450 ID.AddPointer(V); 451 void *IP = nullptr; 452 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 453 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 454 UniqueSCEVs.InsertNode(S, IP); 455 return S; 456 } 457 458 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 459 return getConstant(ConstantInt::get(getContext(), Val)); 460 } 461 462 const SCEV * 463 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 464 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 465 return getConstant(ConstantInt::get(ITy, V, isSigned)); 466 } 467 468 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, 469 const SCEV *op, Type *ty) 470 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 471 Operands[0] = op; 472 } 473 474 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, 475 Type *ITy) 476 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) { 477 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && 478 "Must be a non-bit-width-changing pointer-to-integer cast!"); 479 } 480 481 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, 482 SCEVTypes SCEVTy, const SCEV *op, 483 Type *ty) 484 : SCEVCastExpr(ID, SCEVTy, op, ty) {} 485 486 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, 487 Type *ty) 488 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) { 489 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 490 "Cannot truncate non-integer value!"); 491 } 492 493 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 494 const SCEV *op, Type *ty) 495 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) { 496 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 497 "Cannot zero extend non-integer value!"); 498 } 499 500 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 501 const SCEV *op, Type *ty) 502 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) { 503 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 504 "Cannot sign extend non-integer value!"); 505 } 506 507 void SCEVUnknown::deleted() { 508 // Clear this SCEVUnknown from various maps. 509 SE->forgetMemoizedResults(this); 510 511 // Remove this SCEVUnknown from the uniquing map. 512 SE->UniqueSCEVs.RemoveNode(this); 513 514 // Release the value. 515 setValPtr(nullptr); 516 } 517 518 void SCEVUnknown::allUsesReplacedWith(Value *New) { 519 // Remove this SCEVUnknown from the uniquing map. 520 SE->UniqueSCEVs.RemoveNode(this); 521 522 // Update this SCEVUnknown to point to the new value. This is needed 523 // because there may still be outstanding SCEVs which still point to 524 // this SCEVUnknown. 525 setValPtr(New); 526 } 527 528 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 529 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 530 if (VCE->getOpcode() == Instruction::PtrToInt) 531 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 532 if (CE->getOpcode() == Instruction::GetElementPtr && 533 CE->getOperand(0)->isNullValue() && 534 CE->getNumOperands() == 2) 535 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 536 if (CI->isOne()) { 537 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 538 ->getElementType(); 539 return true; 540 } 541 542 return false; 543 } 544 545 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 546 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 547 if (VCE->getOpcode() == Instruction::PtrToInt) 548 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 549 if (CE->getOpcode() == Instruction::GetElementPtr && 550 CE->getOperand(0)->isNullValue()) { 551 Type *Ty = 552 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 553 if (StructType *STy = dyn_cast<StructType>(Ty)) 554 if (!STy->isPacked() && 555 CE->getNumOperands() == 3 && 556 CE->getOperand(1)->isNullValue()) { 557 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 558 if (CI->isOne() && 559 STy->getNumElements() == 2 && 560 STy->getElementType(0)->isIntegerTy(1)) { 561 AllocTy = STy->getElementType(1); 562 return true; 563 } 564 } 565 } 566 567 return false; 568 } 569 570 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 571 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 572 if (VCE->getOpcode() == Instruction::PtrToInt) 573 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 574 if (CE->getOpcode() == Instruction::GetElementPtr && 575 CE->getNumOperands() == 3 && 576 CE->getOperand(0)->isNullValue() && 577 CE->getOperand(1)->isNullValue()) { 578 Type *Ty = 579 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 580 // Ignore vector types here so that ScalarEvolutionExpander doesn't 581 // emit getelementptrs that index into vectors. 582 if (Ty->isStructTy() || Ty->isArrayTy()) { 583 CTy = Ty; 584 FieldNo = CE->getOperand(2); 585 return true; 586 } 587 } 588 589 return false; 590 } 591 592 //===----------------------------------------------------------------------===// 593 // SCEV Utilities 594 //===----------------------------------------------------------------------===// 595 596 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 597 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 598 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 599 /// have been previously deemed to be "equally complex" by this routine. It is 600 /// intended to avoid exponential time complexity in cases like: 601 /// 602 /// %a = f(%x, %y) 603 /// %b = f(%a, %a) 604 /// %c = f(%b, %b) 605 /// 606 /// %d = f(%x, %y) 607 /// %e = f(%d, %d) 608 /// %f = f(%e, %e) 609 /// 610 /// CompareValueComplexity(%f, %c) 611 /// 612 /// Since we do not continue running this routine on expression trees once we 613 /// have seen unequal values, there is no need to track them in the cache. 614 static int 615 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 616 const LoopInfo *const LI, Value *LV, Value *RV, 617 unsigned Depth) { 618 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 619 return 0; 620 621 // Order pointer values after integer values. This helps SCEVExpander form 622 // GEPs. 623 bool LIsPointer = LV->getType()->isPointerTy(), 624 RIsPointer = RV->getType()->isPointerTy(); 625 if (LIsPointer != RIsPointer) 626 return (int)LIsPointer - (int)RIsPointer; 627 628 // Compare getValueID values. 629 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 630 if (LID != RID) 631 return (int)LID - (int)RID; 632 633 // Sort arguments by their position. 634 if (const auto *LA = dyn_cast<Argument>(LV)) { 635 const auto *RA = cast<Argument>(RV); 636 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 637 return (int)LArgNo - (int)RArgNo; 638 } 639 640 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 641 const auto *RGV = cast<GlobalValue>(RV); 642 643 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 644 auto LT = GV->getLinkage(); 645 return !(GlobalValue::isPrivateLinkage(LT) || 646 GlobalValue::isInternalLinkage(LT)); 647 }; 648 649 // Use the names to distinguish the two values, but only if the 650 // names are semantically important. 651 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 652 return LGV->getName().compare(RGV->getName()); 653 } 654 655 // For instructions, compare their loop depth, and their operand count. This 656 // is pretty loose. 657 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 658 const auto *RInst = cast<Instruction>(RV); 659 660 // Compare loop depths. 661 const BasicBlock *LParent = LInst->getParent(), 662 *RParent = RInst->getParent(); 663 if (LParent != RParent) { 664 unsigned LDepth = LI->getLoopDepth(LParent), 665 RDepth = LI->getLoopDepth(RParent); 666 if (LDepth != RDepth) 667 return (int)LDepth - (int)RDepth; 668 } 669 670 // Compare the number of operands. 671 unsigned LNumOps = LInst->getNumOperands(), 672 RNumOps = RInst->getNumOperands(); 673 if (LNumOps != RNumOps) 674 return (int)LNumOps - (int)RNumOps; 675 676 for (unsigned Idx : seq(0u, LNumOps)) { 677 int Result = 678 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 679 RInst->getOperand(Idx), Depth + 1); 680 if (Result != 0) 681 return Result; 682 } 683 } 684 685 EqCacheValue.unionSets(LV, RV); 686 return 0; 687 } 688 689 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 690 // than RHS, respectively. A three-way result allows recursive comparisons to be 691 // more efficient. 692 static int CompareSCEVComplexity( 693 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 694 EquivalenceClasses<const Value *> &EqCacheValue, 695 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 696 DominatorTree &DT, unsigned Depth = 0) { 697 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 698 if (LHS == RHS) 699 return 0; 700 701 // Primarily, sort the SCEVs by their getSCEVType(). 702 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 703 if (LType != RType) 704 return (int)LType - (int)RType; 705 706 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 707 return 0; 708 // Aside from the getSCEVType() ordering, the particular ordering 709 // isn't very important except that it's beneficial to be consistent, 710 // so that (a + b) and (b + a) don't end up as different expressions. 711 switch (LType) { 712 case scUnknown: { 713 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 714 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 715 716 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 717 RU->getValue(), Depth + 1); 718 if (X == 0) 719 EqCacheSCEV.unionSets(LHS, RHS); 720 return X; 721 } 722 723 case scConstant: { 724 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 725 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 726 727 // Compare constant values. 728 const APInt &LA = LC->getAPInt(); 729 const APInt &RA = RC->getAPInt(); 730 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 731 if (LBitWidth != RBitWidth) 732 return (int)LBitWidth - (int)RBitWidth; 733 return LA.ult(RA) ? -1 : 1; 734 } 735 736 case scAddRecExpr: { 737 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 738 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 739 740 // There is always a dominance between two recs that are used by one SCEV, 741 // so we can safely sort recs by loop header dominance. We require such 742 // order in getAddExpr. 743 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 744 if (LLoop != RLoop) { 745 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 746 assert(LHead != RHead && "Two loops share the same header?"); 747 if (DT.dominates(LHead, RHead)) 748 return 1; 749 else 750 assert(DT.dominates(RHead, LHead) && 751 "No dominance between recurrences used by one SCEV?"); 752 return -1; 753 } 754 755 // Addrec complexity grows with operand count. 756 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 757 if (LNumOps != RNumOps) 758 return (int)LNumOps - (int)RNumOps; 759 760 // Lexicographically compare. 761 for (unsigned i = 0; i != LNumOps; ++i) { 762 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 763 LA->getOperand(i), RA->getOperand(i), DT, 764 Depth + 1); 765 if (X != 0) 766 return X; 767 } 768 EqCacheSCEV.unionSets(LHS, RHS); 769 return 0; 770 } 771 772 case scAddExpr: 773 case scMulExpr: 774 case scSMaxExpr: 775 case scUMaxExpr: 776 case scSMinExpr: 777 case scUMinExpr: { 778 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 779 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 780 781 // Lexicographically compare n-ary expressions. 782 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 783 if (LNumOps != RNumOps) 784 return (int)LNumOps - (int)RNumOps; 785 786 for (unsigned i = 0; i != LNumOps; ++i) { 787 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 788 LC->getOperand(i), RC->getOperand(i), DT, 789 Depth + 1); 790 if (X != 0) 791 return X; 792 } 793 EqCacheSCEV.unionSets(LHS, RHS); 794 return 0; 795 } 796 797 case scUDivExpr: { 798 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 799 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 800 801 // Lexicographically compare udiv expressions. 802 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 803 RC->getLHS(), DT, Depth + 1); 804 if (X != 0) 805 return X; 806 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 807 RC->getRHS(), DT, Depth + 1); 808 if (X == 0) 809 EqCacheSCEV.unionSets(LHS, RHS); 810 return X; 811 } 812 813 case scPtrToInt: 814 case scTruncate: 815 case scZeroExtend: 816 case scSignExtend: { 817 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 818 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 819 820 // Compare cast expressions by operand. 821 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 822 LC->getOperand(), RC->getOperand(), DT, 823 Depth + 1); 824 if (X == 0) 825 EqCacheSCEV.unionSets(LHS, RHS); 826 return X; 827 } 828 829 case scCouldNotCompute: 830 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 831 } 832 llvm_unreachable("Unknown SCEV kind!"); 833 } 834 835 /// Given a list of SCEV objects, order them by their complexity, and group 836 /// objects of the same complexity together by value. When this routine is 837 /// finished, we know that any duplicates in the vector are consecutive and that 838 /// complexity is monotonically increasing. 839 /// 840 /// Note that we go take special precautions to ensure that we get deterministic 841 /// results from this routine. In other words, we don't want the results of 842 /// this to depend on where the addresses of various SCEV objects happened to 843 /// land in memory. 844 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 845 LoopInfo *LI, DominatorTree &DT) { 846 if (Ops.size() < 2) return; // Noop 847 848 EquivalenceClasses<const SCEV *> EqCacheSCEV; 849 EquivalenceClasses<const Value *> EqCacheValue; 850 if (Ops.size() == 2) { 851 // This is the common case, which also happens to be trivially simple. 852 // Special case it. 853 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 854 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 855 std::swap(LHS, RHS); 856 return; 857 } 858 859 // Do the rough sort by complexity. 860 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 861 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < 862 0; 863 }); 864 865 // Now that we are sorted by complexity, group elements of the same 866 // complexity. Note that this is, at worst, N^2, but the vector is likely to 867 // be extremely short in practice. Note that we take this approach because we 868 // do not want to depend on the addresses of the objects we are grouping. 869 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 870 const SCEV *S = Ops[i]; 871 unsigned Complexity = S->getSCEVType(); 872 873 // If there are any objects of the same complexity and same value as this 874 // one, group them. 875 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 876 if (Ops[j] == S) { // Found a duplicate. 877 // Move it to immediately after i'th element. 878 std::swap(Ops[i+1], Ops[j]); 879 ++i; // no need to rescan it. 880 if (i == e-2) return; // Done! 881 } 882 } 883 } 884 } 885 886 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 887 /// least HugeExprThreshold nodes). 888 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 889 return any_of(Ops, [](const SCEV *S) { 890 return S->getExpressionSize() >= HugeExprThreshold; 891 }); 892 } 893 894 //===----------------------------------------------------------------------===// 895 // Simple SCEV method implementations 896 //===----------------------------------------------------------------------===// 897 898 /// Compute BC(It, K). The result has width W. Assume, K > 0. 899 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 900 ScalarEvolution &SE, 901 Type *ResultTy) { 902 // Handle the simplest case efficiently. 903 if (K == 1) 904 return SE.getTruncateOrZeroExtend(It, ResultTy); 905 906 // We are using the following formula for BC(It, K): 907 // 908 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 909 // 910 // Suppose, W is the bitwidth of the return value. We must be prepared for 911 // overflow. Hence, we must assure that the result of our computation is 912 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 913 // safe in modular arithmetic. 914 // 915 // However, this code doesn't use exactly that formula; the formula it uses 916 // is something like the following, where T is the number of factors of 2 in 917 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 918 // exponentiation: 919 // 920 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 921 // 922 // This formula is trivially equivalent to the previous formula. However, 923 // this formula can be implemented much more efficiently. The trick is that 924 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 925 // arithmetic. To do exact division in modular arithmetic, all we have 926 // to do is multiply by the inverse. Therefore, this step can be done at 927 // width W. 928 // 929 // The next issue is how to safely do the division by 2^T. The way this 930 // is done is by doing the multiplication step at a width of at least W + T 931 // bits. This way, the bottom W+T bits of the product are accurate. Then, 932 // when we perform the division by 2^T (which is equivalent to a right shift 933 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 934 // truncated out after the division by 2^T. 935 // 936 // In comparison to just directly using the first formula, this technique 937 // is much more efficient; using the first formula requires W * K bits, 938 // but this formula less than W + K bits. Also, the first formula requires 939 // a division step, whereas this formula only requires multiplies and shifts. 940 // 941 // It doesn't matter whether the subtraction step is done in the calculation 942 // width or the input iteration count's width; if the subtraction overflows, 943 // the result must be zero anyway. We prefer here to do it in the width of 944 // the induction variable because it helps a lot for certain cases; CodeGen 945 // isn't smart enough to ignore the overflow, which leads to much less 946 // efficient code if the width of the subtraction is wider than the native 947 // register width. 948 // 949 // (It's possible to not widen at all by pulling out factors of 2 before 950 // the multiplication; for example, K=2 can be calculated as 951 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 952 // extra arithmetic, so it's not an obvious win, and it gets 953 // much more complicated for K > 3.) 954 955 // Protection from insane SCEVs; this bound is conservative, 956 // but it probably doesn't matter. 957 if (K > 1000) 958 return SE.getCouldNotCompute(); 959 960 unsigned W = SE.getTypeSizeInBits(ResultTy); 961 962 // Calculate K! / 2^T and T; we divide out the factors of two before 963 // multiplying for calculating K! / 2^T to avoid overflow. 964 // Other overflow doesn't matter because we only care about the bottom 965 // W bits of the result. 966 APInt OddFactorial(W, 1); 967 unsigned T = 1; 968 for (unsigned i = 3; i <= K; ++i) { 969 APInt Mult(W, i); 970 unsigned TwoFactors = Mult.countTrailingZeros(); 971 T += TwoFactors; 972 Mult.lshrInPlace(TwoFactors); 973 OddFactorial *= Mult; 974 } 975 976 // We need at least W + T bits for the multiplication step 977 unsigned CalculationBits = W + T; 978 979 // Calculate 2^T, at width T+W. 980 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 981 982 // Calculate the multiplicative inverse of K! / 2^T; 983 // this multiplication factor will perform the exact division by 984 // K! / 2^T. 985 APInt Mod = APInt::getSignedMinValue(W+1); 986 APInt MultiplyFactor = OddFactorial.zext(W+1); 987 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 988 MultiplyFactor = MultiplyFactor.trunc(W); 989 990 // Calculate the product, at width T+W 991 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 992 CalculationBits); 993 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 994 for (unsigned i = 1; i != K; ++i) { 995 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 996 Dividend = SE.getMulExpr(Dividend, 997 SE.getTruncateOrZeroExtend(S, CalculationTy)); 998 } 999 1000 // Divide by 2^T 1001 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1002 1003 // Truncate the result, and divide by K! / 2^T. 1004 1005 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1006 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1007 } 1008 1009 /// Return the value of this chain of recurrences at the specified iteration 1010 /// number. We can evaluate this recurrence by multiplying each element in the 1011 /// chain by the binomial coefficient corresponding to it. In other words, we 1012 /// can evaluate {A,+,B,+,C,+,D} as: 1013 /// 1014 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1015 /// 1016 /// where BC(It, k) stands for binomial coefficient. 1017 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1018 ScalarEvolution &SE) const { 1019 const SCEV *Result = getStart(); 1020 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1021 // The computation is correct in the face of overflow provided that the 1022 // multiplication is performed _after_ the evaluation of the binomial 1023 // coefficient. 1024 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1025 if (isa<SCEVCouldNotCompute>(Coeff)) 1026 return Coeff; 1027 1028 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1029 } 1030 return Result; 1031 } 1032 1033 //===----------------------------------------------------------------------===// 1034 // SCEV Expression folder implementations 1035 //===----------------------------------------------------------------------===// 1036 1037 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty, 1038 unsigned Depth) { 1039 assert(Ty->isIntegerTy() && "Target type must be an integer type!"); 1040 assert(Depth <= 1 && "getPtrToIntExpr() should self-recurse at most once."); 1041 1042 // We could be called with an integer-typed operands during SCEV rewrites. 1043 // Since the operand is an integer already, just perform zext/trunc/self cast. 1044 if (!Op->getType()->isPointerTy()) 1045 return getTruncateOrZeroExtend(Op, Ty); 1046 1047 // What would be an ID for such a SCEV cast expression? 1048 FoldingSetNodeID ID; 1049 ID.AddInteger(scPtrToInt); 1050 ID.AddPointer(Op); 1051 1052 void *IP = nullptr; 1053 1054 // Is there already an expression for such a cast? 1055 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1056 return getTruncateOrZeroExtend(S, Ty); 1057 1058 // If not, is this expression something we can't reduce any further? 1059 if (isa<SCEVUnknown>(Op)) { 1060 // Create an explicit cast node. 1061 // We can reuse the existing insert position since if we get here, 1062 // we won't have made any changes which would invalidate it. 1063 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType()); 1064 assert(getDataLayout().getTypeSizeInBits(getEffectiveSCEVType( 1065 Op->getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) && 1066 "We can only model ptrtoint if SCEV's effective (integer) type is " 1067 "sufficiently wide to represent all possible pointer values."); 1068 SCEV *S = new (SCEVAllocator) 1069 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy); 1070 UniqueSCEVs.InsertNode(S, IP); 1071 addToLoopUseLists(S); 1072 return getTruncateOrZeroExtend(S, Ty); 1073 } 1074 1075 assert(Depth == 0 && 1076 "getPtrToIntExpr() should not self-recurse for non-SCEVUnknown's."); 1077 1078 // Otherwise, we've got some expression that is more complex than just a 1079 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an 1080 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown 1081 // only, and the expressions must otherwise be integer-typed. 1082 // So sink the cast down to the SCEVUnknown's. 1083 1084 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression, 1085 /// which computes a pointer-typed value, and rewrites the whole expression 1086 /// tree so that *all* the computations are done on integers, and the only 1087 /// pointer-typed operands in the expression are SCEVUnknown. 1088 class SCEVPtrToIntSinkingRewriter 1089 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> { 1090 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>; 1091 1092 public: 1093 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {} 1094 1095 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) { 1096 SCEVPtrToIntSinkingRewriter Rewriter(SE); 1097 return Rewriter.visit(Scev); 1098 } 1099 1100 const SCEV *visit(const SCEV *S) { 1101 Type *STy = S->getType(); 1102 // If the expression is not pointer-typed, just keep it as-is. 1103 if (!STy->isPointerTy()) 1104 return S; 1105 // Else, recursively sink the cast down into it. 1106 return Base::visit(S); 1107 } 1108 1109 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) { 1110 SmallVector<const SCEV *, 2> Operands; 1111 bool Changed = false; 1112 for (auto *Op : Expr->operands()) { 1113 Operands.push_back(visit(Op)); 1114 Changed |= Op != Operands.back(); 1115 } 1116 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags()); 1117 } 1118 1119 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) { 1120 SmallVector<const SCEV *, 2> Operands; 1121 bool Changed = false; 1122 for (auto *Op : Expr->operands()) { 1123 Operands.push_back(visit(Op)); 1124 Changed |= Op != Operands.back(); 1125 } 1126 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags()); 1127 } 1128 1129 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 1130 Type *ExprPtrTy = Expr->getType(); 1131 assert(ExprPtrTy->isPointerTy() && 1132 "Should only reach pointer-typed SCEVUnknown's."); 1133 Type *ExprIntPtrTy = SE.getDataLayout().getIntPtrType(ExprPtrTy); 1134 return SE.getPtrToIntExpr(Expr, ExprIntPtrTy, /*Depth=*/1); 1135 } 1136 }; 1137 1138 // And actually perform the cast sinking. 1139 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this); 1140 assert(IntOp->getType()->isIntegerTy() && 1141 "We must have succeeded in sinking the cast, " 1142 "and ending up with an integer-typed expression!"); 1143 return getTruncateOrZeroExtend(IntOp, Ty); 1144 } 1145 1146 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1147 unsigned Depth) { 1148 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1149 "This is not a truncating conversion!"); 1150 assert(isSCEVable(Ty) && 1151 "This is not a conversion to a SCEVable type!"); 1152 Ty = getEffectiveSCEVType(Ty); 1153 1154 FoldingSetNodeID ID; 1155 ID.AddInteger(scTruncate); 1156 ID.AddPointer(Op); 1157 ID.AddPointer(Ty); 1158 void *IP = nullptr; 1159 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1160 1161 // Fold if the operand is constant. 1162 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1163 return getConstant( 1164 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1165 1166 // trunc(trunc(x)) --> trunc(x) 1167 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1168 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1169 1170 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1171 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1172 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1173 1174 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1175 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1176 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1177 1178 if (Depth > MaxCastDepth) { 1179 SCEV *S = 1180 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1181 UniqueSCEVs.InsertNode(S, IP); 1182 addToLoopUseLists(S); 1183 return S; 1184 } 1185 1186 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1187 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1188 // if after transforming we have at most one truncate, not counting truncates 1189 // that replace other casts. 1190 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1191 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1192 SmallVector<const SCEV *, 4> Operands; 1193 unsigned numTruncs = 0; 1194 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1195 ++i) { 1196 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1197 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) && 1198 isa<SCEVTruncateExpr>(S)) 1199 numTruncs++; 1200 Operands.push_back(S); 1201 } 1202 if (numTruncs < 2) { 1203 if (isa<SCEVAddExpr>(Op)) 1204 return getAddExpr(Operands); 1205 else if (isa<SCEVMulExpr>(Op)) 1206 return getMulExpr(Operands); 1207 else 1208 llvm_unreachable("Unexpected SCEV type for Op."); 1209 } 1210 // Although we checked in the beginning that ID is not in the cache, it is 1211 // possible that during recursion and different modification ID was inserted 1212 // into the cache. So if we find it, just return it. 1213 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1214 return S; 1215 } 1216 1217 // If the input value is a chrec scev, truncate the chrec's operands. 1218 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1219 SmallVector<const SCEV *, 4> Operands; 1220 for (const SCEV *Op : AddRec->operands()) 1221 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1222 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1223 } 1224 1225 // Return zero if truncating to known zeros. 1226 uint32_t MinTrailingZeros = GetMinTrailingZeros(Op); 1227 if (MinTrailingZeros >= getTypeSizeInBits(Ty)) 1228 return getZero(Ty); 1229 1230 // The cast wasn't folded; create an explicit cast node. We can reuse 1231 // the existing insert position since if we get here, we won't have 1232 // made any changes which would invalidate it. 1233 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1234 Op, Ty); 1235 UniqueSCEVs.InsertNode(S, IP); 1236 addToLoopUseLists(S); 1237 return S; 1238 } 1239 1240 // Get the limit of a recurrence such that incrementing by Step cannot cause 1241 // signed overflow as long as the value of the recurrence within the 1242 // loop does not exceed this limit before incrementing. 1243 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1244 ICmpInst::Predicate *Pred, 1245 ScalarEvolution *SE) { 1246 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1247 if (SE->isKnownPositive(Step)) { 1248 *Pred = ICmpInst::ICMP_SLT; 1249 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1250 SE->getSignedRangeMax(Step)); 1251 } 1252 if (SE->isKnownNegative(Step)) { 1253 *Pred = ICmpInst::ICMP_SGT; 1254 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1255 SE->getSignedRangeMin(Step)); 1256 } 1257 return nullptr; 1258 } 1259 1260 // Get the limit of a recurrence such that incrementing by Step cannot cause 1261 // unsigned overflow as long as the value of the recurrence within the loop does 1262 // not exceed this limit before incrementing. 1263 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1264 ICmpInst::Predicate *Pred, 1265 ScalarEvolution *SE) { 1266 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1267 *Pred = ICmpInst::ICMP_ULT; 1268 1269 return SE->getConstant(APInt::getMinValue(BitWidth) - 1270 SE->getUnsignedRangeMax(Step)); 1271 } 1272 1273 namespace { 1274 1275 struct ExtendOpTraitsBase { 1276 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1277 unsigned); 1278 }; 1279 1280 // Used to make code generic over signed and unsigned overflow. 1281 template <typename ExtendOp> struct ExtendOpTraits { 1282 // Members present: 1283 // 1284 // static const SCEV::NoWrapFlags WrapType; 1285 // 1286 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1287 // 1288 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1289 // ICmpInst::Predicate *Pred, 1290 // ScalarEvolution *SE); 1291 }; 1292 1293 template <> 1294 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1295 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1296 1297 static const GetExtendExprTy GetExtendExpr; 1298 1299 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1300 ICmpInst::Predicate *Pred, 1301 ScalarEvolution *SE) { 1302 return getSignedOverflowLimitForStep(Step, Pred, SE); 1303 } 1304 }; 1305 1306 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1307 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1308 1309 template <> 1310 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1311 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1312 1313 static const GetExtendExprTy GetExtendExpr; 1314 1315 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1316 ICmpInst::Predicate *Pred, 1317 ScalarEvolution *SE) { 1318 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1319 } 1320 }; 1321 1322 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1323 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1324 1325 } // end anonymous namespace 1326 1327 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1328 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1329 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1330 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1331 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1332 // expression "Step + sext/zext(PreIncAR)" is congruent with 1333 // "sext/zext(PostIncAR)" 1334 template <typename ExtendOpTy> 1335 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1336 ScalarEvolution *SE, unsigned Depth) { 1337 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1338 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1339 1340 const Loop *L = AR->getLoop(); 1341 const SCEV *Start = AR->getStart(); 1342 const SCEV *Step = AR->getStepRecurrence(*SE); 1343 1344 // Check for a simple looking step prior to loop entry. 1345 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1346 if (!SA) 1347 return nullptr; 1348 1349 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1350 // subtraction is expensive. For this purpose, perform a quick and dirty 1351 // difference, by checking for Step in the operand list. 1352 SmallVector<const SCEV *, 4> DiffOps; 1353 for (const SCEV *Op : SA->operands()) 1354 if (Op != Step) 1355 DiffOps.push_back(Op); 1356 1357 if (DiffOps.size() == SA->getNumOperands()) 1358 return nullptr; 1359 1360 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1361 // `Step`: 1362 1363 // 1. NSW/NUW flags on the step increment. 1364 auto PreStartFlags = 1365 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1366 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1367 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1368 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1369 1370 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1371 // "S+X does not sign/unsign-overflow". 1372 // 1373 1374 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1375 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1376 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1377 return PreStart; 1378 1379 // 2. Direct overflow check on the step operation's expression. 1380 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1381 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1382 const SCEV *OperandExtendedStart = 1383 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1384 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1385 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1386 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1387 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1388 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1389 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1390 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType); 1391 } 1392 return PreStart; 1393 } 1394 1395 // 3. Loop precondition. 1396 ICmpInst::Predicate Pred; 1397 const SCEV *OverflowLimit = 1398 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1399 1400 if (OverflowLimit && 1401 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1402 return PreStart; 1403 1404 return nullptr; 1405 } 1406 1407 // Get the normalized zero or sign extended expression for this AddRec's Start. 1408 template <typename ExtendOpTy> 1409 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1410 ScalarEvolution *SE, 1411 unsigned Depth) { 1412 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1413 1414 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1415 if (!PreStart) 1416 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1417 1418 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1419 Depth), 1420 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1421 } 1422 1423 // Try to prove away overflow by looking at "nearby" add recurrences. A 1424 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1425 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1426 // 1427 // Formally: 1428 // 1429 // {S,+,X} == {S-T,+,X} + T 1430 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1431 // 1432 // If ({S-T,+,X} + T) does not overflow ... (1) 1433 // 1434 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1435 // 1436 // If {S-T,+,X} does not overflow ... (2) 1437 // 1438 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1439 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1440 // 1441 // If (S-T)+T does not overflow ... (3) 1442 // 1443 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1444 // == {Ext(S),+,Ext(X)} == LHS 1445 // 1446 // Thus, if (1), (2) and (3) are true for some T, then 1447 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1448 // 1449 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1450 // does not overflow" restricted to the 0th iteration. Therefore we only need 1451 // to check for (1) and (2). 1452 // 1453 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1454 // is `Delta` (defined below). 1455 template <typename ExtendOpTy> 1456 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1457 const SCEV *Step, 1458 const Loop *L) { 1459 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1460 1461 // We restrict `Start` to a constant to prevent SCEV from spending too much 1462 // time here. It is correct (but more expensive) to continue with a 1463 // non-constant `Start` and do a general SCEV subtraction to compute 1464 // `PreStart` below. 1465 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1466 if (!StartC) 1467 return false; 1468 1469 APInt StartAI = StartC->getAPInt(); 1470 1471 for (unsigned Delta : {-2, -1, 1, 2}) { 1472 const SCEV *PreStart = getConstant(StartAI - Delta); 1473 1474 FoldingSetNodeID ID; 1475 ID.AddInteger(scAddRecExpr); 1476 ID.AddPointer(PreStart); 1477 ID.AddPointer(Step); 1478 ID.AddPointer(L); 1479 void *IP = nullptr; 1480 const auto *PreAR = 1481 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1482 1483 // Give up if we don't already have the add recurrence we need because 1484 // actually constructing an add recurrence is relatively expensive. 1485 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1486 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1487 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1488 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1489 DeltaS, &Pred, this); 1490 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1491 return true; 1492 } 1493 } 1494 1495 return false; 1496 } 1497 1498 // Finds an integer D for an expression (C + x + y + ...) such that the top 1499 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1500 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1501 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1502 // the (C + x + y + ...) expression is \p WholeAddExpr. 1503 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1504 const SCEVConstant *ConstantTerm, 1505 const SCEVAddExpr *WholeAddExpr) { 1506 const APInt &C = ConstantTerm->getAPInt(); 1507 const unsigned BitWidth = C.getBitWidth(); 1508 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1509 uint32_t TZ = BitWidth; 1510 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1511 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1512 if (TZ) { 1513 // Set D to be as many least significant bits of C as possible while still 1514 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1515 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1516 } 1517 return APInt(BitWidth, 0); 1518 } 1519 1520 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1521 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1522 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1523 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1524 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1525 const APInt &ConstantStart, 1526 const SCEV *Step) { 1527 const unsigned BitWidth = ConstantStart.getBitWidth(); 1528 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1529 if (TZ) 1530 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1531 : ConstantStart; 1532 return APInt(BitWidth, 0); 1533 } 1534 1535 const SCEV * 1536 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1537 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1538 "This is not an extending conversion!"); 1539 assert(isSCEVable(Ty) && 1540 "This is not a conversion to a SCEVable type!"); 1541 Ty = getEffectiveSCEVType(Ty); 1542 1543 // Fold if the operand is constant. 1544 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1545 return getConstant( 1546 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1547 1548 // zext(zext(x)) --> zext(x) 1549 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1550 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1551 1552 // Before doing any expensive analysis, check to see if we've already 1553 // computed a SCEV for this Op and Ty. 1554 FoldingSetNodeID ID; 1555 ID.AddInteger(scZeroExtend); 1556 ID.AddPointer(Op); 1557 ID.AddPointer(Ty); 1558 void *IP = nullptr; 1559 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1560 if (Depth > MaxCastDepth) { 1561 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1562 Op, Ty); 1563 UniqueSCEVs.InsertNode(S, IP); 1564 addToLoopUseLists(S); 1565 return S; 1566 } 1567 1568 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1569 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1570 // It's possible the bits taken off by the truncate were all zero bits. If 1571 // so, we should be able to simplify this further. 1572 const SCEV *X = ST->getOperand(); 1573 ConstantRange CR = getUnsignedRange(X); 1574 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1575 unsigned NewBits = getTypeSizeInBits(Ty); 1576 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1577 CR.zextOrTrunc(NewBits))) 1578 return getTruncateOrZeroExtend(X, Ty, Depth); 1579 } 1580 1581 // If the input value is a chrec scev, and we can prove that the value 1582 // did not overflow the old, smaller, value, we can zero extend all of the 1583 // operands (often constants). This allows analysis of something like 1584 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1585 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1586 if (AR->isAffine()) { 1587 const SCEV *Start = AR->getStart(); 1588 const SCEV *Step = AR->getStepRecurrence(*this); 1589 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1590 const Loop *L = AR->getLoop(); 1591 1592 if (!AR->hasNoUnsignedWrap()) { 1593 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1594 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1595 } 1596 1597 // If we have special knowledge that this addrec won't overflow, 1598 // we don't need to do any further analysis. 1599 if (AR->hasNoUnsignedWrap()) 1600 return getAddRecExpr( 1601 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1602 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1603 1604 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1605 // Note that this serves two purposes: It filters out loops that are 1606 // simply not analyzable, and it covers the case where this code is 1607 // being called from within backedge-taken count analysis, such that 1608 // attempting to ask for the backedge-taken count would likely result 1609 // in infinite recursion. In the later case, the analysis code will 1610 // cope with a conservative value, and it will take care to purge 1611 // that value once it has finished. 1612 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1613 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1614 // Manually compute the final value for AR, checking for overflow. 1615 1616 // Check whether the backedge-taken count can be losslessly casted to 1617 // the addrec's type. The count is always unsigned. 1618 const SCEV *CastedMaxBECount = 1619 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1620 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1621 CastedMaxBECount, MaxBECount->getType(), Depth); 1622 if (MaxBECount == RecastedMaxBECount) { 1623 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1624 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1625 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1626 SCEV::FlagAnyWrap, Depth + 1); 1627 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1628 SCEV::FlagAnyWrap, 1629 Depth + 1), 1630 WideTy, Depth + 1); 1631 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1632 const SCEV *WideMaxBECount = 1633 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1634 const SCEV *OperandExtendedAdd = 1635 getAddExpr(WideStart, 1636 getMulExpr(WideMaxBECount, 1637 getZeroExtendExpr(Step, WideTy, Depth + 1), 1638 SCEV::FlagAnyWrap, Depth + 1), 1639 SCEV::FlagAnyWrap, Depth + 1); 1640 if (ZAdd == OperandExtendedAdd) { 1641 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1642 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1643 // Return the expression with the addrec on the outside. 1644 return getAddRecExpr( 1645 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1646 Depth + 1), 1647 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1648 AR->getNoWrapFlags()); 1649 } 1650 // Similar to above, only this time treat the step value as signed. 1651 // This covers loops that count down. 1652 OperandExtendedAdd = 1653 getAddExpr(WideStart, 1654 getMulExpr(WideMaxBECount, 1655 getSignExtendExpr(Step, WideTy, Depth + 1), 1656 SCEV::FlagAnyWrap, Depth + 1), 1657 SCEV::FlagAnyWrap, Depth + 1); 1658 if (ZAdd == OperandExtendedAdd) { 1659 // Cache knowledge of AR NW, which is propagated to this AddRec. 1660 // Negative step causes unsigned wrap, but it still can't self-wrap. 1661 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1662 // Return the expression with the addrec on the outside. 1663 return getAddRecExpr( 1664 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1665 Depth + 1), 1666 getSignExtendExpr(Step, Ty, Depth + 1), L, 1667 AR->getNoWrapFlags()); 1668 } 1669 } 1670 } 1671 1672 // Normally, in the cases we can prove no-overflow via a 1673 // backedge guarding condition, we can also compute a backedge 1674 // taken count for the loop. The exceptions are assumptions and 1675 // guards present in the loop -- SCEV is not great at exploiting 1676 // these to compute max backedge taken counts, but can still use 1677 // these to prove lack of overflow. Use this fact to avoid 1678 // doing extra work that may not pay off. 1679 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1680 !AC.assumptions().empty()) { 1681 1682 auto NewFlags = proveNoUnsignedWrapViaInduction(AR); 1683 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1684 if (AR->hasNoUnsignedWrap()) { 1685 // Same as nuw case above - duplicated here to avoid a compile time 1686 // issue. It's not clear that the order of checks does matter, but 1687 // it's one of two issue possible causes for a change which was 1688 // reverted. Be conservative for the moment. 1689 return getAddRecExpr( 1690 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1691 Depth + 1), 1692 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1693 AR->getNoWrapFlags()); 1694 } 1695 1696 // For a negative step, we can extend the operands iff doing so only 1697 // traverses values in the range zext([0,UINT_MAX]). 1698 if (isKnownNegative(Step)) { 1699 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1700 getSignedRangeMin(Step)); 1701 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1702 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1703 // Cache knowledge of AR NW, which is propagated to this 1704 // AddRec. Negative step causes unsigned wrap, but it 1705 // still can't self-wrap. 1706 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1707 // Return the expression with the addrec on the outside. 1708 return getAddRecExpr( 1709 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1710 Depth + 1), 1711 getSignExtendExpr(Step, Ty, Depth + 1), L, 1712 AR->getNoWrapFlags()); 1713 } 1714 } 1715 } 1716 1717 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1718 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1719 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1720 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1721 const APInt &C = SC->getAPInt(); 1722 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1723 if (D != 0) { 1724 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1725 const SCEV *SResidual = 1726 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1727 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1728 return getAddExpr(SZExtD, SZExtR, 1729 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1730 Depth + 1); 1731 } 1732 } 1733 1734 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1735 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1736 return getAddRecExpr( 1737 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1738 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1739 } 1740 } 1741 1742 // zext(A % B) --> zext(A) % zext(B) 1743 { 1744 const SCEV *LHS; 1745 const SCEV *RHS; 1746 if (matchURem(Op, LHS, RHS)) 1747 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1748 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1749 } 1750 1751 // zext(A / B) --> zext(A) / zext(B). 1752 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1753 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1754 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1755 1756 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1757 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1758 if (SA->hasNoUnsignedWrap()) { 1759 // If the addition does not unsign overflow then we can, by definition, 1760 // commute the zero extension with the addition operation. 1761 SmallVector<const SCEV *, 4> Ops; 1762 for (const auto *Op : SA->operands()) 1763 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1764 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1765 } 1766 1767 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1768 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1769 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1770 // 1771 // Often address arithmetics contain expressions like 1772 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1773 // This transformation is useful while proving that such expressions are 1774 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1775 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1776 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1777 if (D != 0) { 1778 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1779 const SCEV *SResidual = 1780 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1781 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1782 return getAddExpr(SZExtD, SZExtR, 1783 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1784 Depth + 1); 1785 } 1786 } 1787 } 1788 1789 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1790 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1791 if (SM->hasNoUnsignedWrap()) { 1792 // If the multiply does not unsign overflow then we can, by definition, 1793 // commute the zero extension with the multiply operation. 1794 SmallVector<const SCEV *, 4> Ops; 1795 for (const auto *Op : SM->operands()) 1796 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1797 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1798 } 1799 1800 // zext(2^K * (trunc X to iN)) to iM -> 1801 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1802 // 1803 // Proof: 1804 // 1805 // zext(2^K * (trunc X to iN)) to iM 1806 // = zext((trunc X to iN) << K) to iM 1807 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1808 // (because shl removes the top K bits) 1809 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1810 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1811 // 1812 if (SM->getNumOperands() == 2) 1813 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1814 if (MulLHS->getAPInt().isPowerOf2()) 1815 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1816 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1817 MulLHS->getAPInt().logBase2(); 1818 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1819 return getMulExpr( 1820 getZeroExtendExpr(MulLHS, Ty), 1821 getZeroExtendExpr( 1822 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1823 SCEV::FlagNUW, Depth + 1); 1824 } 1825 } 1826 1827 // The cast wasn't folded; create an explicit cast node. 1828 // Recompute the insert position, as it may have been invalidated. 1829 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1830 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1831 Op, Ty); 1832 UniqueSCEVs.InsertNode(S, IP); 1833 addToLoopUseLists(S); 1834 return S; 1835 } 1836 1837 const SCEV * 1838 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1839 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1840 "This is not an extending conversion!"); 1841 assert(isSCEVable(Ty) && 1842 "This is not a conversion to a SCEVable type!"); 1843 Ty = getEffectiveSCEVType(Ty); 1844 1845 // Fold if the operand is constant. 1846 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1847 return getConstant( 1848 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1849 1850 // sext(sext(x)) --> sext(x) 1851 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1852 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1853 1854 // sext(zext(x)) --> zext(x) 1855 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1856 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1857 1858 // Before doing any expensive analysis, check to see if we've already 1859 // computed a SCEV for this Op and Ty. 1860 FoldingSetNodeID ID; 1861 ID.AddInteger(scSignExtend); 1862 ID.AddPointer(Op); 1863 ID.AddPointer(Ty); 1864 void *IP = nullptr; 1865 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1866 // Limit recursion depth. 1867 if (Depth > MaxCastDepth) { 1868 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1869 Op, Ty); 1870 UniqueSCEVs.InsertNode(S, IP); 1871 addToLoopUseLists(S); 1872 return S; 1873 } 1874 1875 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1876 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1877 // It's possible the bits taken off by the truncate were all sign bits. If 1878 // so, we should be able to simplify this further. 1879 const SCEV *X = ST->getOperand(); 1880 ConstantRange CR = getSignedRange(X); 1881 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1882 unsigned NewBits = getTypeSizeInBits(Ty); 1883 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1884 CR.sextOrTrunc(NewBits))) 1885 return getTruncateOrSignExtend(X, Ty, Depth); 1886 } 1887 1888 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1889 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1890 if (SA->hasNoSignedWrap()) { 1891 // If the addition does not sign overflow then we can, by definition, 1892 // commute the sign extension with the addition operation. 1893 SmallVector<const SCEV *, 4> Ops; 1894 for (const auto *Op : SA->operands()) 1895 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1896 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1897 } 1898 1899 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1900 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1901 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1902 // 1903 // For instance, this will bring two seemingly different expressions: 1904 // 1 + sext(5 + 20 * %x + 24 * %y) and 1905 // sext(6 + 20 * %x + 24 * %y) 1906 // to the same form: 1907 // 2 + sext(4 + 20 * %x + 24 * %y) 1908 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1909 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1910 if (D != 0) { 1911 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1912 const SCEV *SResidual = 1913 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1914 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1915 return getAddExpr(SSExtD, SSExtR, 1916 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1917 Depth + 1); 1918 } 1919 } 1920 } 1921 // If the input value is a chrec scev, and we can prove that the value 1922 // did not overflow the old, smaller, value, we can sign extend all of the 1923 // operands (often constants). This allows analysis of something like 1924 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1925 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1926 if (AR->isAffine()) { 1927 const SCEV *Start = AR->getStart(); 1928 const SCEV *Step = AR->getStepRecurrence(*this); 1929 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1930 const Loop *L = AR->getLoop(); 1931 1932 if (!AR->hasNoSignedWrap()) { 1933 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1934 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1935 } 1936 1937 // If we have special knowledge that this addrec won't overflow, 1938 // we don't need to do any further analysis. 1939 if (AR->hasNoSignedWrap()) 1940 return getAddRecExpr( 1941 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1942 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1943 1944 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1945 // Note that this serves two purposes: It filters out loops that are 1946 // simply not analyzable, and it covers the case where this code is 1947 // being called from within backedge-taken count analysis, such that 1948 // attempting to ask for the backedge-taken count would likely result 1949 // in infinite recursion. In the later case, the analysis code will 1950 // cope with a conservative value, and it will take care to purge 1951 // that value once it has finished. 1952 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1953 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1954 // Manually compute the final value for AR, checking for 1955 // overflow. 1956 1957 // Check whether the backedge-taken count can be losslessly casted to 1958 // the addrec's type. The count is always unsigned. 1959 const SCEV *CastedMaxBECount = 1960 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1961 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1962 CastedMaxBECount, MaxBECount->getType(), Depth); 1963 if (MaxBECount == RecastedMaxBECount) { 1964 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1965 // Check whether Start+Step*MaxBECount has no signed overflow. 1966 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 1967 SCEV::FlagAnyWrap, Depth + 1); 1968 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 1969 SCEV::FlagAnyWrap, 1970 Depth + 1), 1971 WideTy, Depth + 1); 1972 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 1973 const SCEV *WideMaxBECount = 1974 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1975 const SCEV *OperandExtendedAdd = 1976 getAddExpr(WideStart, 1977 getMulExpr(WideMaxBECount, 1978 getSignExtendExpr(Step, WideTy, Depth + 1), 1979 SCEV::FlagAnyWrap, Depth + 1), 1980 SCEV::FlagAnyWrap, Depth + 1); 1981 if (SAdd == OperandExtendedAdd) { 1982 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1983 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 1984 // Return the expression with the addrec on the outside. 1985 return getAddRecExpr( 1986 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1987 Depth + 1), 1988 getSignExtendExpr(Step, Ty, Depth + 1), L, 1989 AR->getNoWrapFlags()); 1990 } 1991 // Similar to above, only this time treat the step value as unsigned. 1992 // This covers loops that count up with an unsigned step. 1993 OperandExtendedAdd = 1994 getAddExpr(WideStart, 1995 getMulExpr(WideMaxBECount, 1996 getZeroExtendExpr(Step, WideTy, Depth + 1), 1997 SCEV::FlagAnyWrap, Depth + 1), 1998 SCEV::FlagAnyWrap, Depth + 1); 1999 if (SAdd == OperandExtendedAdd) { 2000 // If AR wraps around then 2001 // 2002 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2003 // => SAdd != OperandExtendedAdd 2004 // 2005 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2006 // (SAdd == OperandExtendedAdd => AR is NW) 2007 2008 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 2009 2010 // Return the expression with the addrec on the outside. 2011 return getAddRecExpr( 2012 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2013 Depth + 1), 2014 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2015 AR->getNoWrapFlags()); 2016 } 2017 } 2018 } 2019 2020 auto NewFlags = proveNoSignedWrapViaInduction(AR); 2021 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 2022 if (AR->hasNoSignedWrap()) { 2023 // Same as nsw case above - duplicated here to avoid a compile time 2024 // issue. It's not clear that the order of checks does matter, but 2025 // it's one of two issue possible causes for a change which was 2026 // reverted. Be conservative for the moment. 2027 return getAddRecExpr( 2028 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2029 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2030 } 2031 2032 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2033 // if D + (C - D + Step * n) could be proven to not signed wrap 2034 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2035 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2036 const APInt &C = SC->getAPInt(); 2037 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2038 if (D != 0) { 2039 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2040 const SCEV *SResidual = 2041 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2042 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2043 return getAddExpr(SSExtD, SSExtR, 2044 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2045 Depth + 1); 2046 } 2047 } 2048 2049 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2050 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2051 return getAddRecExpr( 2052 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2053 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2054 } 2055 } 2056 2057 // If the input value is provably positive and we could not simplify 2058 // away the sext build a zext instead. 2059 if (isKnownNonNegative(Op)) 2060 return getZeroExtendExpr(Op, Ty, Depth + 1); 2061 2062 // The cast wasn't folded; create an explicit cast node. 2063 // Recompute the insert position, as it may have been invalidated. 2064 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2065 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2066 Op, Ty); 2067 UniqueSCEVs.InsertNode(S, IP); 2068 addToLoopUseLists(S); 2069 return S; 2070 } 2071 2072 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2073 /// unspecified bits out to the given type. 2074 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2075 Type *Ty) { 2076 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2077 "This is not an extending conversion!"); 2078 assert(isSCEVable(Ty) && 2079 "This is not a conversion to a SCEVable type!"); 2080 Ty = getEffectiveSCEVType(Ty); 2081 2082 // Sign-extend negative constants. 2083 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2084 if (SC->getAPInt().isNegative()) 2085 return getSignExtendExpr(Op, Ty); 2086 2087 // Peel off a truncate cast. 2088 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2089 const SCEV *NewOp = T->getOperand(); 2090 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2091 return getAnyExtendExpr(NewOp, Ty); 2092 return getTruncateOrNoop(NewOp, Ty); 2093 } 2094 2095 // Next try a zext cast. If the cast is folded, use it. 2096 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2097 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2098 return ZExt; 2099 2100 // Next try a sext cast. If the cast is folded, use it. 2101 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2102 if (!isa<SCEVSignExtendExpr>(SExt)) 2103 return SExt; 2104 2105 // Force the cast to be folded into the operands of an addrec. 2106 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2107 SmallVector<const SCEV *, 4> Ops; 2108 for (const SCEV *Op : AR->operands()) 2109 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2110 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2111 } 2112 2113 // If the expression is obviously signed, use the sext cast value. 2114 if (isa<SCEVSMaxExpr>(Op)) 2115 return SExt; 2116 2117 // Absent any other information, use the zext cast value. 2118 return ZExt; 2119 } 2120 2121 /// Process the given Ops list, which is a list of operands to be added under 2122 /// the given scale, update the given map. This is a helper function for 2123 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2124 /// that would form an add expression like this: 2125 /// 2126 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2127 /// 2128 /// where A and B are constants, update the map with these values: 2129 /// 2130 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2131 /// 2132 /// and add 13 + A*B*29 to AccumulatedConstant. 2133 /// This will allow getAddRecExpr to produce this: 2134 /// 2135 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2136 /// 2137 /// This form often exposes folding opportunities that are hidden in 2138 /// the original operand list. 2139 /// 2140 /// Return true iff it appears that any interesting folding opportunities 2141 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2142 /// the common case where no interesting opportunities are present, and 2143 /// is also used as a check to avoid infinite recursion. 2144 static bool 2145 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2146 SmallVectorImpl<const SCEV *> &NewOps, 2147 APInt &AccumulatedConstant, 2148 const SCEV *const *Ops, size_t NumOperands, 2149 const APInt &Scale, 2150 ScalarEvolution &SE) { 2151 bool Interesting = false; 2152 2153 // Iterate over the add operands. They are sorted, with constants first. 2154 unsigned i = 0; 2155 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2156 ++i; 2157 // Pull a buried constant out to the outside. 2158 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2159 Interesting = true; 2160 AccumulatedConstant += Scale * C->getAPInt(); 2161 } 2162 2163 // Next comes everything else. We're especially interested in multiplies 2164 // here, but they're in the middle, so just visit the rest with one loop. 2165 for (; i != NumOperands; ++i) { 2166 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2167 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2168 APInt NewScale = 2169 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2170 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2171 // A multiplication of a constant with another add; recurse. 2172 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2173 Interesting |= 2174 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2175 Add->op_begin(), Add->getNumOperands(), 2176 NewScale, SE); 2177 } else { 2178 // A multiplication of a constant with some other value. Update 2179 // the map. 2180 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2181 const SCEV *Key = SE.getMulExpr(MulOps); 2182 auto Pair = M.insert({Key, NewScale}); 2183 if (Pair.second) { 2184 NewOps.push_back(Pair.first->first); 2185 } else { 2186 Pair.first->second += NewScale; 2187 // The map already had an entry for this value, which may indicate 2188 // a folding opportunity. 2189 Interesting = true; 2190 } 2191 } 2192 } else { 2193 // An ordinary operand. Update the map. 2194 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2195 M.insert({Ops[i], Scale}); 2196 if (Pair.second) { 2197 NewOps.push_back(Pair.first->first); 2198 } else { 2199 Pair.first->second += Scale; 2200 // The map already had an entry for this value, which may indicate 2201 // a folding opportunity. 2202 Interesting = true; 2203 } 2204 } 2205 } 2206 2207 return Interesting; 2208 } 2209 2210 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2211 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2212 // can't-overflow flags for the operation if possible. 2213 static SCEV::NoWrapFlags 2214 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2215 const ArrayRef<const SCEV *> Ops, 2216 SCEV::NoWrapFlags Flags) { 2217 using namespace std::placeholders; 2218 2219 using OBO = OverflowingBinaryOperator; 2220 2221 bool CanAnalyze = 2222 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2223 (void)CanAnalyze; 2224 assert(CanAnalyze && "don't call from other places!"); 2225 2226 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2227 SCEV::NoWrapFlags SignOrUnsignWrap = 2228 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2229 2230 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2231 auto IsKnownNonNegative = [&](const SCEV *S) { 2232 return SE->isKnownNonNegative(S); 2233 }; 2234 2235 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2236 Flags = 2237 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2238 2239 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2240 2241 if (SignOrUnsignWrap != SignOrUnsignMask && 2242 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2243 isa<SCEVConstant>(Ops[0])) { 2244 2245 auto Opcode = [&] { 2246 switch (Type) { 2247 case scAddExpr: 2248 return Instruction::Add; 2249 case scMulExpr: 2250 return Instruction::Mul; 2251 default: 2252 llvm_unreachable("Unexpected SCEV op."); 2253 } 2254 }(); 2255 2256 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2257 2258 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2259 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2260 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2261 Opcode, C, OBO::NoSignedWrap); 2262 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2263 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2264 } 2265 2266 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2267 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2268 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2269 Opcode, C, OBO::NoUnsignedWrap); 2270 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2271 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2272 } 2273 } 2274 2275 return Flags; 2276 } 2277 2278 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2279 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2280 } 2281 2282 /// Get a canonical add expression, or something simpler if possible. 2283 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2284 SCEV::NoWrapFlags OrigFlags, 2285 unsigned Depth) { 2286 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2287 "only nuw or nsw allowed"); 2288 assert(!Ops.empty() && "Cannot get empty add!"); 2289 if (Ops.size() == 1) return Ops[0]; 2290 #ifndef NDEBUG 2291 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2292 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2293 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2294 "SCEVAddExpr operand types don't match!"); 2295 #endif 2296 2297 // Sort by complexity, this groups all similar expression types together. 2298 GroupByComplexity(Ops, &LI, DT); 2299 2300 // If there are any constants, fold them together. 2301 unsigned Idx = 0; 2302 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2303 ++Idx; 2304 assert(Idx < Ops.size()); 2305 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2306 // We found two constants, fold them together! 2307 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2308 if (Ops.size() == 2) return Ops[0]; 2309 Ops.erase(Ops.begin()+1); // Erase the folded element 2310 LHSC = cast<SCEVConstant>(Ops[0]); 2311 } 2312 2313 // If we are left with a constant zero being added, strip it off. 2314 if (LHSC->getValue()->isZero()) { 2315 Ops.erase(Ops.begin()); 2316 --Idx; 2317 } 2318 2319 if (Ops.size() == 1) return Ops[0]; 2320 } 2321 2322 // Delay expensive flag strengthening until necessary. 2323 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2324 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2325 }; 2326 2327 // Limit recursion calls depth. 2328 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2329 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2330 2331 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) { 2332 // Don't strengthen flags if we have no new information. 2333 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2334 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2335 Add->setNoWrapFlags(ComputeFlags(Ops)); 2336 return S; 2337 } 2338 2339 // Okay, check to see if the same value occurs in the operand list more than 2340 // once. If so, merge them together into an multiply expression. Since we 2341 // sorted the list, these values are required to be adjacent. 2342 Type *Ty = Ops[0]->getType(); 2343 bool FoundMatch = false; 2344 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2345 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2346 // Scan ahead to count how many equal operands there are. 2347 unsigned Count = 2; 2348 while (i+Count != e && Ops[i+Count] == Ops[i]) 2349 ++Count; 2350 // Merge the values into a multiply. 2351 const SCEV *Scale = getConstant(Ty, Count); 2352 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2353 if (Ops.size() == Count) 2354 return Mul; 2355 Ops[i] = Mul; 2356 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2357 --i; e -= Count - 1; 2358 FoundMatch = true; 2359 } 2360 if (FoundMatch) 2361 return getAddExpr(Ops, OrigFlags, Depth + 1); 2362 2363 // Check for truncates. If all the operands are truncated from the same 2364 // type, see if factoring out the truncate would permit the result to be 2365 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2366 // if the contents of the resulting outer trunc fold to something simple. 2367 auto FindTruncSrcType = [&]() -> Type * { 2368 // We're ultimately looking to fold an addrec of truncs and muls of only 2369 // constants and truncs, so if we find any other types of SCEV 2370 // as operands of the addrec then we bail and return nullptr here. 2371 // Otherwise, we return the type of the operand of a trunc that we find. 2372 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2373 return T->getOperand()->getType(); 2374 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2375 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2376 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2377 return T->getOperand()->getType(); 2378 } 2379 return nullptr; 2380 }; 2381 if (auto *SrcType = FindTruncSrcType()) { 2382 SmallVector<const SCEV *, 8> LargeOps; 2383 bool Ok = true; 2384 // Check all the operands to see if they can be represented in the 2385 // source type of the truncate. 2386 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2387 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2388 if (T->getOperand()->getType() != SrcType) { 2389 Ok = false; 2390 break; 2391 } 2392 LargeOps.push_back(T->getOperand()); 2393 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2394 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2395 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2396 SmallVector<const SCEV *, 8> LargeMulOps; 2397 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2398 if (const SCEVTruncateExpr *T = 2399 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2400 if (T->getOperand()->getType() != SrcType) { 2401 Ok = false; 2402 break; 2403 } 2404 LargeMulOps.push_back(T->getOperand()); 2405 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2406 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2407 } else { 2408 Ok = false; 2409 break; 2410 } 2411 } 2412 if (Ok) 2413 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2414 } else { 2415 Ok = false; 2416 break; 2417 } 2418 } 2419 if (Ok) { 2420 // Evaluate the expression in the larger type. 2421 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2422 // If it folds to something simple, use it. Otherwise, don't. 2423 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2424 return getTruncateExpr(Fold, Ty); 2425 } 2426 } 2427 2428 // Skip past any other cast SCEVs. 2429 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2430 ++Idx; 2431 2432 // If there are add operands they would be next. 2433 if (Idx < Ops.size()) { 2434 bool DeletedAdd = false; 2435 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2436 if (Ops.size() > AddOpsInlineThreshold || 2437 Add->getNumOperands() > AddOpsInlineThreshold) 2438 break; 2439 // If we have an add, expand the add operands onto the end of the operands 2440 // list. 2441 Ops.erase(Ops.begin()+Idx); 2442 Ops.append(Add->op_begin(), Add->op_end()); 2443 DeletedAdd = true; 2444 } 2445 2446 // If we deleted at least one add, we added operands to the end of the list, 2447 // and they are not necessarily sorted. Recurse to resort and resimplify 2448 // any operands we just acquired. 2449 if (DeletedAdd) 2450 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2451 } 2452 2453 // Skip over the add expression until we get to a multiply. 2454 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2455 ++Idx; 2456 2457 // Check to see if there are any folding opportunities present with 2458 // operands multiplied by constant values. 2459 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2460 uint64_t BitWidth = getTypeSizeInBits(Ty); 2461 DenseMap<const SCEV *, APInt> M; 2462 SmallVector<const SCEV *, 8> NewOps; 2463 APInt AccumulatedConstant(BitWidth, 0); 2464 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2465 Ops.data(), Ops.size(), 2466 APInt(BitWidth, 1), *this)) { 2467 struct APIntCompare { 2468 bool operator()(const APInt &LHS, const APInt &RHS) const { 2469 return LHS.ult(RHS); 2470 } 2471 }; 2472 2473 // Some interesting folding opportunity is present, so its worthwhile to 2474 // re-generate the operands list. Group the operands by constant scale, 2475 // to avoid multiplying by the same constant scale multiple times. 2476 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2477 for (const SCEV *NewOp : NewOps) 2478 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2479 // Re-generate the operands list. 2480 Ops.clear(); 2481 if (AccumulatedConstant != 0) 2482 Ops.push_back(getConstant(AccumulatedConstant)); 2483 for (auto &MulOp : MulOpLists) 2484 if (MulOp.first != 0) 2485 Ops.push_back(getMulExpr( 2486 getConstant(MulOp.first), 2487 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2488 SCEV::FlagAnyWrap, Depth + 1)); 2489 if (Ops.empty()) 2490 return getZero(Ty); 2491 if (Ops.size() == 1) 2492 return Ops[0]; 2493 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2494 } 2495 } 2496 2497 // If we are adding something to a multiply expression, make sure the 2498 // something is not already an operand of the multiply. If so, merge it into 2499 // the multiply. 2500 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2501 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2502 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2503 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2504 if (isa<SCEVConstant>(MulOpSCEV)) 2505 continue; 2506 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2507 if (MulOpSCEV == Ops[AddOp]) { 2508 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2509 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2510 if (Mul->getNumOperands() != 2) { 2511 // If the multiply has more than two operands, we must get the 2512 // Y*Z term. 2513 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2514 Mul->op_begin()+MulOp); 2515 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2516 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2517 } 2518 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2519 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2520 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2521 SCEV::FlagAnyWrap, Depth + 1); 2522 if (Ops.size() == 2) return OuterMul; 2523 if (AddOp < Idx) { 2524 Ops.erase(Ops.begin()+AddOp); 2525 Ops.erase(Ops.begin()+Idx-1); 2526 } else { 2527 Ops.erase(Ops.begin()+Idx); 2528 Ops.erase(Ops.begin()+AddOp-1); 2529 } 2530 Ops.push_back(OuterMul); 2531 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2532 } 2533 2534 // Check this multiply against other multiplies being added together. 2535 for (unsigned OtherMulIdx = Idx+1; 2536 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2537 ++OtherMulIdx) { 2538 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2539 // If MulOp occurs in OtherMul, we can fold the two multiplies 2540 // together. 2541 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2542 OMulOp != e; ++OMulOp) 2543 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2544 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2545 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2546 if (Mul->getNumOperands() != 2) { 2547 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2548 Mul->op_begin()+MulOp); 2549 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2550 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2551 } 2552 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2553 if (OtherMul->getNumOperands() != 2) { 2554 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2555 OtherMul->op_begin()+OMulOp); 2556 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2557 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2558 } 2559 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2560 const SCEV *InnerMulSum = 2561 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2562 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2563 SCEV::FlagAnyWrap, Depth + 1); 2564 if (Ops.size() == 2) return OuterMul; 2565 Ops.erase(Ops.begin()+Idx); 2566 Ops.erase(Ops.begin()+OtherMulIdx-1); 2567 Ops.push_back(OuterMul); 2568 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2569 } 2570 } 2571 } 2572 } 2573 2574 // If there are any add recurrences in the operands list, see if any other 2575 // added values are loop invariant. If so, we can fold them into the 2576 // recurrence. 2577 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2578 ++Idx; 2579 2580 // Scan over all recurrences, trying to fold loop invariants into them. 2581 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2582 // Scan all of the other operands to this add and add them to the vector if 2583 // they are loop invariant w.r.t. the recurrence. 2584 SmallVector<const SCEV *, 8> LIOps; 2585 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2586 const Loop *AddRecLoop = AddRec->getLoop(); 2587 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2588 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2589 LIOps.push_back(Ops[i]); 2590 Ops.erase(Ops.begin()+i); 2591 --i; --e; 2592 } 2593 2594 // If we found some loop invariants, fold them into the recurrence. 2595 if (!LIOps.empty()) { 2596 // Compute nowrap flags for the addition of the loop-invariant ops and 2597 // the addrec. Temporarily push it as an operand for that purpose. 2598 LIOps.push_back(AddRec); 2599 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2600 LIOps.pop_back(); 2601 2602 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2603 LIOps.push_back(AddRec->getStart()); 2604 2605 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2606 AddRec->op_end()); 2607 // This follows from the fact that the no-wrap flags on the outer add 2608 // expression are applicable on the 0th iteration, when the add recurrence 2609 // will be equal to its start value. 2610 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2611 2612 // Build the new addrec. Propagate the NUW and NSW flags if both the 2613 // outer add and the inner addrec are guaranteed to have no overflow. 2614 // Always propagate NW. 2615 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2616 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2617 2618 // If all of the other operands were loop invariant, we are done. 2619 if (Ops.size() == 1) return NewRec; 2620 2621 // Otherwise, add the folded AddRec by the non-invariant parts. 2622 for (unsigned i = 0;; ++i) 2623 if (Ops[i] == AddRec) { 2624 Ops[i] = NewRec; 2625 break; 2626 } 2627 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2628 } 2629 2630 // Okay, if there weren't any loop invariants to be folded, check to see if 2631 // there are multiple AddRec's with the same loop induction variable being 2632 // added together. If so, we can fold them. 2633 for (unsigned OtherIdx = Idx+1; 2634 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2635 ++OtherIdx) { 2636 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2637 // so that the 1st found AddRecExpr is dominated by all others. 2638 assert(DT.dominates( 2639 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2640 AddRec->getLoop()->getHeader()) && 2641 "AddRecExprs are not sorted in reverse dominance order?"); 2642 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2643 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2644 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2645 AddRec->op_end()); 2646 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2647 ++OtherIdx) { 2648 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2649 if (OtherAddRec->getLoop() == AddRecLoop) { 2650 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2651 i != e; ++i) { 2652 if (i >= AddRecOps.size()) { 2653 AddRecOps.append(OtherAddRec->op_begin()+i, 2654 OtherAddRec->op_end()); 2655 break; 2656 } 2657 SmallVector<const SCEV *, 2> TwoOps = { 2658 AddRecOps[i], OtherAddRec->getOperand(i)}; 2659 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2660 } 2661 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2662 } 2663 } 2664 // Step size has changed, so we cannot guarantee no self-wraparound. 2665 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2666 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2667 } 2668 } 2669 2670 // Otherwise couldn't fold anything into this recurrence. Move onto the 2671 // next one. 2672 } 2673 2674 // Okay, it looks like we really DO need an add expr. Check to see if we 2675 // already have one, otherwise create a new one. 2676 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2677 } 2678 2679 const SCEV * 2680 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2681 SCEV::NoWrapFlags Flags) { 2682 FoldingSetNodeID ID; 2683 ID.AddInteger(scAddExpr); 2684 for (const SCEV *Op : Ops) 2685 ID.AddPointer(Op); 2686 void *IP = nullptr; 2687 SCEVAddExpr *S = 2688 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2689 if (!S) { 2690 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2691 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2692 S = new (SCEVAllocator) 2693 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2694 UniqueSCEVs.InsertNode(S, IP); 2695 addToLoopUseLists(S); 2696 } 2697 S->setNoWrapFlags(Flags); 2698 return S; 2699 } 2700 2701 const SCEV * 2702 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2703 const Loop *L, SCEV::NoWrapFlags Flags) { 2704 FoldingSetNodeID ID; 2705 ID.AddInteger(scAddRecExpr); 2706 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2707 ID.AddPointer(Ops[i]); 2708 ID.AddPointer(L); 2709 void *IP = nullptr; 2710 SCEVAddRecExpr *S = 2711 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2712 if (!S) { 2713 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2714 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2715 S = new (SCEVAllocator) 2716 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2717 UniqueSCEVs.InsertNode(S, IP); 2718 addToLoopUseLists(S); 2719 } 2720 setNoWrapFlags(S, Flags); 2721 return S; 2722 } 2723 2724 const SCEV * 2725 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2726 SCEV::NoWrapFlags Flags) { 2727 FoldingSetNodeID ID; 2728 ID.AddInteger(scMulExpr); 2729 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2730 ID.AddPointer(Ops[i]); 2731 void *IP = nullptr; 2732 SCEVMulExpr *S = 2733 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2734 if (!S) { 2735 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2736 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2737 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2738 O, Ops.size()); 2739 UniqueSCEVs.InsertNode(S, IP); 2740 addToLoopUseLists(S); 2741 } 2742 S->setNoWrapFlags(Flags); 2743 return S; 2744 } 2745 2746 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2747 uint64_t k = i*j; 2748 if (j > 1 && k / j != i) Overflow = true; 2749 return k; 2750 } 2751 2752 /// Compute the result of "n choose k", the binomial coefficient. If an 2753 /// intermediate computation overflows, Overflow will be set and the return will 2754 /// be garbage. Overflow is not cleared on absence of overflow. 2755 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2756 // We use the multiplicative formula: 2757 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2758 // At each iteration, we take the n-th term of the numeral and divide by the 2759 // (k-n)th term of the denominator. This division will always produce an 2760 // integral result, and helps reduce the chance of overflow in the 2761 // intermediate computations. However, we can still overflow even when the 2762 // final result would fit. 2763 2764 if (n == 0 || n == k) return 1; 2765 if (k > n) return 0; 2766 2767 if (k > n/2) 2768 k = n-k; 2769 2770 uint64_t r = 1; 2771 for (uint64_t i = 1; i <= k; ++i) { 2772 r = umul_ov(r, n-(i-1), Overflow); 2773 r /= i; 2774 } 2775 return r; 2776 } 2777 2778 /// Determine if any of the operands in this SCEV are a constant or if 2779 /// any of the add or multiply expressions in this SCEV contain a constant. 2780 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2781 struct FindConstantInAddMulChain { 2782 bool FoundConstant = false; 2783 2784 bool follow(const SCEV *S) { 2785 FoundConstant |= isa<SCEVConstant>(S); 2786 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2787 } 2788 2789 bool isDone() const { 2790 return FoundConstant; 2791 } 2792 }; 2793 2794 FindConstantInAddMulChain F; 2795 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2796 ST.visitAll(StartExpr); 2797 return F.FoundConstant; 2798 } 2799 2800 /// Get a canonical multiply expression, or something simpler if possible. 2801 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2802 SCEV::NoWrapFlags OrigFlags, 2803 unsigned Depth) { 2804 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 2805 "only nuw or nsw allowed"); 2806 assert(!Ops.empty() && "Cannot get empty mul!"); 2807 if (Ops.size() == 1) return Ops[0]; 2808 #ifndef NDEBUG 2809 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2810 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2811 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2812 "SCEVMulExpr operand types don't match!"); 2813 #endif 2814 2815 // Sort by complexity, this groups all similar expression types together. 2816 GroupByComplexity(Ops, &LI, DT); 2817 2818 // If there are any constants, fold them together. 2819 unsigned Idx = 0; 2820 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2821 ++Idx; 2822 assert(Idx < Ops.size()); 2823 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2824 // We found two constants, fold them together! 2825 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 2826 if (Ops.size() == 2) return Ops[0]; 2827 Ops.erase(Ops.begin()+1); // Erase the folded element 2828 LHSC = cast<SCEVConstant>(Ops[0]); 2829 } 2830 2831 // If we have a multiply of zero, it will always be zero. 2832 if (LHSC->getValue()->isZero()) 2833 return LHSC; 2834 2835 // If we are left with a constant one being multiplied, strip it off. 2836 if (LHSC->getValue()->isOne()) { 2837 Ops.erase(Ops.begin()); 2838 --Idx; 2839 } 2840 2841 if (Ops.size() == 1) 2842 return Ops[0]; 2843 } 2844 2845 // Delay expensive flag strengthening until necessary. 2846 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2847 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 2848 }; 2849 2850 // Limit recursion calls depth. 2851 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2852 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 2853 2854 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { 2855 // Don't strengthen flags if we have no new information. 2856 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 2857 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 2858 Mul->setNoWrapFlags(ComputeFlags(Ops)); 2859 return S; 2860 } 2861 2862 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2863 if (Ops.size() == 2) { 2864 // C1*(C2+V) -> C1*C2 + C1*V 2865 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2866 // If any of Add's ops are Adds or Muls with a constant, apply this 2867 // transformation as well. 2868 // 2869 // TODO: There are some cases where this transformation is not 2870 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2871 // this transformation should be narrowed down. 2872 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2873 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2874 SCEV::FlagAnyWrap, Depth + 1), 2875 getMulExpr(LHSC, Add->getOperand(1), 2876 SCEV::FlagAnyWrap, Depth + 1), 2877 SCEV::FlagAnyWrap, Depth + 1); 2878 2879 if (Ops[0]->isAllOnesValue()) { 2880 // If we have a mul by -1 of an add, try distributing the -1 among the 2881 // add operands. 2882 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2883 SmallVector<const SCEV *, 4> NewOps; 2884 bool AnyFolded = false; 2885 for (const SCEV *AddOp : Add->operands()) { 2886 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2887 Depth + 1); 2888 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2889 NewOps.push_back(Mul); 2890 } 2891 if (AnyFolded) 2892 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2893 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2894 // Negation preserves a recurrence's no self-wrap property. 2895 SmallVector<const SCEV *, 4> Operands; 2896 for (const SCEV *AddRecOp : AddRec->operands()) 2897 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2898 Depth + 1)); 2899 2900 return getAddRecExpr(Operands, AddRec->getLoop(), 2901 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2902 } 2903 } 2904 } 2905 } 2906 2907 // Skip over the add expression until we get to a multiply. 2908 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2909 ++Idx; 2910 2911 // If there are mul operands inline them all into this expression. 2912 if (Idx < Ops.size()) { 2913 bool DeletedMul = false; 2914 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2915 if (Ops.size() > MulOpsInlineThreshold) 2916 break; 2917 // If we have an mul, expand the mul operands onto the end of the 2918 // operands list. 2919 Ops.erase(Ops.begin()+Idx); 2920 Ops.append(Mul->op_begin(), Mul->op_end()); 2921 DeletedMul = true; 2922 } 2923 2924 // If we deleted at least one mul, we added operands to the end of the 2925 // list, and they are not necessarily sorted. Recurse to resort and 2926 // resimplify any operands we just acquired. 2927 if (DeletedMul) 2928 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2929 } 2930 2931 // If there are any add recurrences in the operands list, see if any other 2932 // added values are loop invariant. If so, we can fold them into the 2933 // recurrence. 2934 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2935 ++Idx; 2936 2937 // Scan over all recurrences, trying to fold loop invariants into them. 2938 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2939 // Scan all of the other operands to this mul and add them to the vector 2940 // if they are loop invariant w.r.t. the recurrence. 2941 SmallVector<const SCEV *, 8> LIOps; 2942 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2943 const Loop *AddRecLoop = AddRec->getLoop(); 2944 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2945 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2946 LIOps.push_back(Ops[i]); 2947 Ops.erase(Ops.begin()+i); 2948 --i; --e; 2949 } 2950 2951 // If we found some loop invariants, fold them into the recurrence. 2952 if (!LIOps.empty()) { 2953 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2954 SmallVector<const SCEV *, 4> NewOps; 2955 NewOps.reserve(AddRec->getNumOperands()); 2956 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2957 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2958 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2959 SCEV::FlagAnyWrap, Depth + 1)); 2960 2961 // Build the new addrec. Propagate the NUW and NSW flags if both the 2962 // outer mul and the inner addrec are guaranteed to have no overflow. 2963 // 2964 // No self-wrap cannot be guaranteed after changing the step size, but 2965 // will be inferred if either NUW or NSW is true. 2966 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 2967 const SCEV *NewRec = getAddRecExpr( 2968 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 2969 2970 // If all of the other operands were loop invariant, we are done. 2971 if (Ops.size() == 1) return NewRec; 2972 2973 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2974 for (unsigned i = 0;; ++i) 2975 if (Ops[i] == AddRec) { 2976 Ops[i] = NewRec; 2977 break; 2978 } 2979 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2980 } 2981 2982 // Okay, if there weren't any loop invariants to be folded, check to see 2983 // if there are multiple AddRec's with the same loop induction variable 2984 // being multiplied together. If so, we can fold them. 2985 2986 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2987 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2988 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2989 // ]]],+,...up to x=2n}. 2990 // Note that the arguments to choose() are always integers with values 2991 // known at compile time, never SCEV objects. 2992 // 2993 // The implementation avoids pointless extra computations when the two 2994 // addrec's are of different length (mathematically, it's equivalent to 2995 // an infinite stream of zeros on the right). 2996 bool OpsModified = false; 2997 for (unsigned OtherIdx = Idx+1; 2998 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2999 ++OtherIdx) { 3000 const SCEVAddRecExpr *OtherAddRec = 3001 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3002 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3003 continue; 3004 3005 // Limit max number of arguments to avoid creation of unreasonably big 3006 // SCEVAddRecs with very complex operands. 3007 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3008 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3009 continue; 3010 3011 bool Overflow = false; 3012 Type *Ty = AddRec->getType(); 3013 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3014 SmallVector<const SCEV*, 7> AddRecOps; 3015 for (int x = 0, xe = AddRec->getNumOperands() + 3016 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3017 SmallVector <const SCEV *, 7> SumOps; 3018 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3019 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3020 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3021 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3022 z < ze && !Overflow; ++z) { 3023 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3024 uint64_t Coeff; 3025 if (LargerThan64Bits) 3026 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3027 else 3028 Coeff = Coeff1*Coeff2; 3029 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3030 const SCEV *Term1 = AddRec->getOperand(y-z); 3031 const SCEV *Term2 = OtherAddRec->getOperand(z); 3032 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3033 SCEV::FlagAnyWrap, Depth + 1)); 3034 } 3035 } 3036 if (SumOps.empty()) 3037 SumOps.push_back(getZero(Ty)); 3038 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3039 } 3040 if (!Overflow) { 3041 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3042 SCEV::FlagAnyWrap); 3043 if (Ops.size() == 2) return NewAddRec; 3044 Ops[Idx] = NewAddRec; 3045 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3046 OpsModified = true; 3047 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3048 if (!AddRec) 3049 break; 3050 } 3051 } 3052 if (OpsModified) 3053 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3054 3055 // Otherwise couldn't fold anything into this recurrence. Move onto the 3056 // next one. 3057 } 3058 3059 // Okay, it looks like we really DO need an mul expr. Check to see if we 3060 // already have one, otherwise create a new one. 3061 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3062 } 3063 3064 /// Represents an unsigned remainder expression based on unsigned division. 3065 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3066 const SCEV *RHS) { 3067 assert(getEffectiveSCEVType(LHS->getType()) == 3068 getEffectiveSCEVType(RHS->getType()) && 3069 "SCEVURemExpr operand types don't match!"); 3070 3071 // Short-circuit easy cases 3072 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3073 // If constant is one, the result is trivial 3074 if (RHSC->getValue()->isOne()) 3075 return getZero(LHS->getType()); // X urem 1 --> 0 3076 3077 // If constant is a power of two, fold into a zext(trunc(LHS)). 3078 if (RHSC->getAPInt().isPowerOf2()) { 3079 Type *FullTy = LHS->getType(); 3080 Type *TruncTy = 3081 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3082 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3083 } 3084 } 3085 3086 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3087 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3088 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3089 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3090 } 3091 3092 /// Get a canonical unsigned division expression, or something simpler if 3093 /// possible. 3094 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3095 const SCEV *RHS) { 3096 assert(getEffectiveSCEVType(LHS->getType()) == 3097 getEffectiveSCEVType(RHS->getType()) && 3098 "SCEVUDivExpr operand types don't match!"); 3099 3100 FoldingSetNodeID ID; 3101 ID.AddInteger(scUDivExpr); 3102 ID.AddPointer(LHS); 3103 ID.AddPointer(RHS); 3104 void *IP = nullptr; 3105 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3106 return S; 3107 3108 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3109 if (RHSC->getValue()->isOne()) 3110 return LHS; // X udiv 1 --> x 3111 // If the denominator is zero, the result of the udiv is undefined. Don't 3112 // try to analyze it, because the resolution chosen here may differ from 3113 // the resolution chosen in other parts of the compiler. 3114 if (!RHSC->getValue()->isZero()) { 3115 // Determine if the division can be folded into the operands of 3116 // its operands. 3117 // TODO: Generalize this to non-constants by using known-bits information. 3118 Type *Ty = LHS->getType(); 3119 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3120 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3121 // For non-power-of-two values, effectively round the value up to the 3122 // nearest power of two. 3123 if (!RHSC->getAPInt().isPowerOf2()) 3124 ++MaxShiftAmt; 3125 IntegerType *ExtTy = 3126 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3127 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3128 if (const SCEVConstant *Step = 3129 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3130 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3131 const APInt &StepInt = Step->getAPInt(); 3132 const APInt &DivInt = RHSC->getAPInt(); 3133 if (!StepInt.urem(DivInt) && 3134 getZeroExtendExpr(AR, ExtTy) == 3135 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3136 getZeroExtendExpr(Step, ExtTy), 3137 AR->getLoop(), SCEV::FlagAnyWrap)) { 3138 SmallVector<const SCEV *, 4> Operands; 3139 for (const SCEV *Op : AR->operands()) 3140 Operands.push_back(getUDivExpr(Op, RHS)); 3141 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3142 } 3143 /// Get a canonical UDivExpr for a recurrence. 3144 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3145 // We can currently only fold X%N if X is constant. 3146 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3147 if (StartC && !DivInt.urem(StepInt) && 3148 getZeroExtendExpr(AR, ExtTy) == 3149 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3150 getZeroExtendExpr(Step, ExtTy), 3151 AR->getLoop(), SCEV::FlagAnyWrap)) { 3152 const APInt &StartInt = StartC->getAPInt(); 3153 const APInt &StartRem = StartInt.urem(StepInt); 3154 if (StartRem != 0) { 3155 const SCEV *NewLHS = 3156 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3157 AR->getLoop(), SCEV::FlagNW); 3158 if (LHS != NewLHS) { 3159 LHS = NewLHS; 3160 3161 // Reset the ID to include the new LHS, and check if it is 3162 // already cached. 3163 ID.clear(); 3164 ID.AddInteger(scUDivExpr); 3165 ID.AddPointer(LHS); 3166 ID.AddPointer(RHS); 3167 IP = nullptr; 3168 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3169 return S; 3170 } 3171 } 3172 } 3173 } 3174 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3175 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3176 SmallVector<const SCEV *, 4> Operands; 3177 for (const SCEV *Op : M->operands()) 3178 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3179 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3180 // Find an operand that's safely divisible. 3181 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3182 const SCEV *Op = M->getOperand(i); 3183 const SCEV *Div = getUDivExpr(Op, RHSC); 3184 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3185 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3186 M->op_end()); 3187 Operands[i] = Div; 3188 return getMulExpr(Operands); 3189 } 3190 } 3191 } 3192 3193 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3194 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3195 if (auto *DivisorConstant = 3196 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3197 bool Overflow = false; 3198 APInt NewRHS = 3199 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3200 if (Overflow) { 3201 return getConstant(RHSC->getType(), 0, false); 3202 } 3203 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3204 } 3205 } 3206 3207 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3208 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3209 SmallVector<const SCEV *, 4> Operands; 3210 for (const SCEV *Op : A->operands()) 3211 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3212 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3213 Operands.clear(); 3214 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3215 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3216 if (isa<SCEVUDivExpr>(Op) || 3217 getMulExpr(Op, RHS) != A->getOperand(i)) 3218 break; 3219 Operands.push_back(Op); 3220 } 3221 if (Operands.size() == A->getNumOperands()) 3222 return getAddExpr(Operands); 3223 } 3224 } 3225 3226 // Fold if both operands are constant. 3227 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3228 Constant *LHSCV = LHSC->getValue(); 3229 Constant *RHSCV = RHSC->getValue(); 3230 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3231 RHSCV))); 3232 } 3233 } 3234 } 3235 3236 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3237 // changes). Make sure we get a new one. 3238 IP = nullptr; 3239 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3240 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3241 LHS, RHS); 3242 UniqueSCEVs.InsertNode(S, IP); 3243 addToLoopUseLists(S); 3244 return S; 3245 } 3246 3247 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3248 APInt A = C1->getAPInt().abs(); 3249 APInt B = C2->getAPInt().abs(); 3250 uint32_t ABW = A.getBitWidth(); 3251 uint32_t BBW = B.getBitWidth(); 3252 3253 if (ABW > BBW) 3254 B = B.zext(ABW); 3255 else if (ABW < BBW) 3256 A = A.zext(BBW); 3257 3258 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3259 } 3260 3261 /// Get a canonical unsigned division expression, or something simpler if 3262 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3263 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3264 /// it's not exact because the udiv may be clearing bits. 3265 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3266 const SCEV *RHS) { 3267 // TODO: we could try to find factors in all sorts of things, but for now we 3268 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3269 // end of this file for inspiration. 3270 3271 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3272 if (!Mul || !Mul->hasNoUnsignedWrap()) 3273 return getUDivExpr(LHS, RHS); 3274 3275 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3276 // If the mulexpr multiplies by a constant, then that constant must be the 3277 // first element of the mulexpr. 3278 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3279 if (LHSCst == RHSCst) { 3280 SmallVector<const SCEV *, 2> Operands; 3281 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3282 return getMulExpr(Operands); 3283 } 3284 3285 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3286 // that there's a factor provided by one of the other terms. We need to 3287 // check. 3288 APInt Factor = gcd(LHSCst, RHSCst); 3289 if (!Factor.isIntN(1)) { 3290 LHSCst = 3291 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3292 RHSCst = 3293 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3294 SmallVector<const SCEV *, 2> Operands; 3295 Operands.push_back(LHSCst); 3296 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3297 LHS = getMulExpr(Operands); 3298 RHS = RHSCst; 3299 Mul = dyn_cast<SCEVMulExpr>(LHS); 3300 if (!Mul) 3301 return getUDivExactExpr(LHS, RHS); 3302 } 3303 } 3304 } 3305 3306 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3307 if (Mul->getOperand(i) == RHS) { 3308 SmallVector<const SCEV *, 2> Operands; 3309 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3310 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3311 return getMulExpr(Operands); 3312 } 3313 } 3314 3315 return getUDivExpr(LHS, RHS); 3316 } 3317 3318 /// Get an add recurrence expression for the specified loop. Simplify the 3319 /// expression as much as possible. 3320 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3321 const Loop *L, 3322 SCEV::NoWrapFlags Flags) { 3323 SmallVector<const SCEV *, 4> Operands; 3324 Operands.push_back(Start); 3325 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3326 if (StepChrec->getLoop() == L) { 3327 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3328 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3329 } 3330 3331 Operands.push_back(Step); 3332 return getAddRecExpr(Operands, L, Flags); 3333 } 3334 3335 /// Get an add recurrence expression for the specified loop. Simplify the 3336 /// expression as much as possible. 3337 const SCEV * 3338 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3339 const Loop *L, SCEV::NoWrapFlags Flags) { 3340 if (Operands.size() == 1) return Operands[0]; 3341 #ifndef NDEBUG 3342 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3343 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3344 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3345 "SCEVAddRecExpr operand types don't match!"); 3346 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3347 assert(isLoopInvariant(Operands[i], L) && 3348 "SCEVAddRecExpr operand is not loop-invariant!"); 3349 #endif 3350 3351 if (Operands.back()->isZero()) { 3352 Operands.pop_back(); 3353 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3354 } 3355 3356 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3357 // use that information to infer NUW and NSW flags. However, computing a 3358 // BE count requires calling getAddRecExpr, so we may not yet have a 3359 // meaningful BE count at this point (and if we don't, we'd be stuck 3360 // with a SCEVCouldNotCompute as the cached BE count). 3361 3362 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3363 3364 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3365 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3366 const Loop *NestedLoop = NestedAR->getLoop(); 3367 if (L->contains(NestedLoop) 3368 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3369 : (!NestedLoop->contains(L) && 3370 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3371 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3372 NestedAR->op_end()); 3373 Operands[0] = NestedAR->getStart(); 3374 // AddRecs require their operands be loop-invariant with respect to their 3375 // loops. Don't perform this transformation if it would break this 3376 // requirement. 3377 bool AllInvariant = all_of( 3378 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3379 3380 if (AllInvariant) { 3381 // Create a recurrence for the outer loop with the same step size. 3382 // 3383 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3384 // inner recurrence has the same property. 3385 SCEV::NoWrapFlags OuterFlags = 3386 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3387 3388 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3389 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3390 return isLoopInvariant(Op, NestedLoop); 3391 }); 3392 3393 if (AllInvariant) { 3394 // Ok, both add recurrences are valid after the transformation. 3395 // 3396 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3397 // the outer recurrence has the same property. 3398 SCEV::NoWrapFlags InnerFlags = 3399 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3400 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3401 } 3402 } 3403 // Reset Operands to its original state. 3404 Operands[0] = NestedAR; 3405 } 3406 } 3407 3408 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3409 // already have one, otherwise create a new one. 3410 return getOrCreateAddRecExpr(Operands, L, Flags); 3411 } 3412 3413 const SCEV * 3414 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3415 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3416 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3417 // getSCEV(Base)->getType() has the same address space as Base->getType() 3418 // because SCEV::getType() preserves the address space. 3419 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3420 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3421 // instruction to its SCEV, because the Instruction may be guarded by control 3422 // flow and the no-overflow bits may not be valid for the expression in any 3423 // context. This can be fixed similarly to how these flags are handled for 3424 // adds. 3425 SCEV::NoWrapFlags OffsetWrap = 3426 GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3427 3428 Type *CurTy = GEP->getType(); 3429 bool FirstIter = true; 3430 SmallVector<const SCEV *, 4> Offsets; 3431 for (const SCEV *IndexExpr : IndexExprs) { 3432 // Compute the (potentially symbolic) offset in bytes for this index. 3433 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3434 // For a struct, add the member offset. 3435 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3436 unsigned FieldNo = Index->getZExtValue(); 3437 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3438 Offsets.push_back(FieldOffset); 3439 3440 // Update CurTy to the type of the field at Index. 3441 CurTy = STy->getTypeAtIndex(Index); 3442 } else { 3443 // Update CurTy to its element type. 3444 if (FirstIter) { 3445 assert(isa<PointerType>(CurTy) && 3446 "The first index of a GEP indexes a pointer"); 3447 CurTy = GEP->getSourceElementType(); 3448 FirstIter = false; 3449 } else { 3450 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3451 } 3452 // For an array, add the element offset, explicitly scaled. 3453 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3454 // Getelementptr indices are signed. 3455 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3456 3457 // Multiply the index by the element size to compute the element offset. 3458 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3459 Offsets.push_back(LocalOffset); 3460 } 3461 } 3462 3463 // Handle degenerate case of GEP without offsets. 3464 if (Offsets.empty()) 3465 return BaseExpr; 3466 3467 // Add the offsets together, assuming nsw if inbounds. 3468 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3469 // Add the base address and the offset. We cannot use the nsw flag, as the 3470 // base address is unsigned. However, if we know that the offset is 3471 // non-negative, we can use nuw. 3472 SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset) 3473 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3474 return getAddExpr(BaseExpr, Offset, BaseWrap); 3475 } 3476 3477 std::tuple<SCEV *, FoldingSetNodeID, void *> 3478 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3479 ArrayRef<const SCEV *> Ops) { 3480 FoldingSetNodeID ID; 3481 void *IP = nullptr; 3482 ID.AddInteger(SCEVType); 3483 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3484 ID.AddPointer(Ops[i]); 3485 return std::tuple<SCEV *, FoldingSetNodeID, void *>( 3486 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3487 } 3488 3489 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3490 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3491 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3492 } 3493 3494 const SCEV *ScalarEvolution::getSignumExpr(const SCEV *Op) { 3495 Type *Ty = Op->getType(); 3496 return getSMinExpr(getSMaxExpr(Op, getMinusOne(Ty)), getOne(Ty)); 3497 } 3498 3499 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3500 SmallVectorImpl<const SCEV *> &Ops) { 3501 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3502 if (Ops.size() == 1) return Ops[0]; 3503 #ifndef NDEBUG 3504 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3505 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3506 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3507 "Operand types don't match!"); 3508 #endif 3509 3510 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3511 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3512 3513 // Sort by complexity, this groups all similar expression types together. 3514 GroupByComplexity(Ops, &LI, DT); 3515 3516 // Check if we have created the same expression before. 3517 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3518 return S; 3519 } 3520 3521 // If there are any constants, fold them together. 3522 unsigned Idx = 0; 3523 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3524 ++Idx; 3525 assert(Idx < Ops.size()); 3526 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3527 if (Kind == scSMaxExpr) 3528 return APIntOps::smax(LHS, RHS); 3529 else if (Kind == scSMinExpr) 3530 return APIntOps::smin(LHS, RHS); 3531 else if (Kind == scUMaxExpr) 3532 return APIntOps::umax(LHS, RHS); 3533 else if (Kind == scUMinExpr) 3534 return APIntOps::umin(LHS, RHS); 3535 llvm_unreachable("Unknown SCEV min/max opcode"); 3536 }; 3537 3538 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3539 // We found two constants, fold them together! 3540 ConstantInt *Fold = ConstantInt::get( 3541 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3542 Ops[0] = getConstant(Fold); 3543 Ops.erase(Ops.begin()+1); // Erase the folded element 3544 if (Ops.size() == 1) return Ops[0]; 3545 LHSC = cast<SCEVConstant>(Ops[0]); 3546 } 3547 3548 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3549 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3550 3551 if (IsMax ? IsMinV : IsMaxV) { 3552 // If we are left with a constant minimum(/maximum)-int, strip it off. 3553 Ops.erase(Ops.begin()); 3554 --Idx; 3555 } else if (IsMax ? IsMaxV : IsMinV) { 3556 // If we have a max(/min) with a constant maximum(/minimum)-int, 3557 // it will always be the extremum. 3558 return LHSC; 3559 } 3560 3561 if (Ops.size() == 1) return Ops[0]; 3562 } 3563 3564 // Find the first operation of the same kind 3565 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3566 ++Idx; 3567 3568 // Check to see if one of the operands is of the same kind. If so, expand its 3569 // operands onto our operand list, and recurse to simplify. 3570 if (Idx < Ops.size()) { 3571 bool DeletedAny = false; 3572 while (Ops[Idx]->getSCEVType() == Kind) { 3573 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3574 Ops.erase(Ops.begin()+Idx); 3575 Ops.append(SMME->op_begin(), SMME->op_end()); 3576 DeletedAny = true; 3577 } 3578 3579 if (DeletedAny) 3580 return getMinMaxExpr(Kind, Ops); 3581 } 3582 3583 // Okay, check to see if the same value occurs in the operand list twice. If 3584 // so, delete one. Since we sorted the list, these values are required to 3585 // be adjacent. 3586 llvm::CmpInst::Predicate GEPred = 3587 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3588 llvm::CmpInst::Predicate LEPred = 3589 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3590 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3591 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3592 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3593 if (Ops[i] == Ops[i + 1] || 3594 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3595 // X op Y op Y --> X op Y 3596 // X op Y --> X, if we know X, Y are ordered appropriately 3597 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3598 --i; 3599 --e; 3600 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3601 Ops[i + 1])) { 3602 // X op Y --> Y, if we know X, Y are ordered appropriately 3603 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3604 --i; 3605 --e; 3606 } 3607 } 3608 3609 if (Ops.size() == 1) return Ops[0]; 3610 3611 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3612 3613 // Okay, it looks like we really DO need an expr. Check to see if we 3614 // already have one, otherwise create a new one. 3615 const SCEV *ExistingSCEV; 3616 FoldingSetNodeID ID; 3617 void *IP; 3618 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3619 if (ExistingSCEV) 3620 return ExistingSCEV; 3621 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3622 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3623 SCEV *S = new (SCEVAllocator) 3624 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3625 3626 UniqueSCEVs.InsertNode(S, IP); 3627 addToLoopUseLists(S); 3628 return S; 3629 } 3630 3631 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3632 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3633 return getSMaxExpr(Ops); 3634 } 3635 3636 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3637 return getMinMaxExpr(scSMaxExpr, Ops); 3638 } 3639 3640 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3641 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3642 return getUMaxExpr(Ops); 3643 } 3644 3645 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3646 return getMinMaxExpr(scUMaxExpr, Ops); 3647 } 3648 3649 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3650 const SCEV *RHS) { 3651 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3652 return getSMinExpr(Ops); 3653 } 3654 3655 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3656 return getMinMaxExpr(scSMinExpr, Ops); 3657 } 3658 3659 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3660 const SCEV *RHS) { 3661 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3662 return getUMinExpr(Ops); 3663 } 3664 3665 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3666 return getMinMaxExpr(scUMinExpr, Ops); 3667 } 3668 3669 const SCEV * 3670 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 3671 ScalableVectorType *ScalableTy) { 3672 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 3673 Constant *One = ConstantInt::get(IntTy, 1); 3674 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 3675 // Note that the expression we created is the final expression, we don't 3676 // want to simplify it any further Also, if we call a normal getSCEV(), 3677 // we'll end up in an endless recursion. So just create an SCEVUnknown. 3678 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 3679 } 3680 3681 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3682 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 3683 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 3684 // We can bypass creating a target-independent constant expression and then 3685 // folding it back into a ConstantInt. This is just a compile-time 3686 // optimization. 3687 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3688 } 3689 3690 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 3691 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 3692 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 3693 // We can bypass creating a target-independent constant expression and then 3694 // folding it back into a ConstantInt. This is just a compile-time 3695 // optimization. 3696 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 3697 } 3698 3699 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3700 StructType *STy, 3701 unsigned FieldNo) { 3702 // We can bypass creating a target-independent constant expression and then 3703 // folding it back into a ConstantInt. This is just a compile-time 3704 // optimization. 3705 return getConstant( 3706 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3707 } 3708 3709 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3710 // Don't attempt to do anything other than create a SCEVUnknown object 3711 // here. createSCEV only calls getUnknown after checking for all other 3712 // interesting possibilities, and any other code that calls getUnknown 3713 // is doing so in order to hide a value from SCEV canonicalization. 3714 3715 FoldingSetNodeID ID; 3716 ID.AddInteger(scUnknown); 3717 ID.AddPointer(V); 3718 void *IP = nullptr; 3719 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3720 assert(cast<SCEVUnknown>(S)->getValue() == V && 3721 "Stale SCEVUnknown in uniquing map!"); 3722 return S; 3723 } 3724 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3725 FirstUnknown); 3726 FirstUnknown = cast<SCEVUnknown>(S); 3727 UniqueSCEVs.InsertNode(S, IP); 3728 return S; 3729 } 3730 3731 //===----------------------------------------------------------------------===// 3732 // Basic SCEV Analysis and PHI Idiom Recognition Code 3733 // 3734 3735 /// Test if values of the given type are analyzable within the SCEV 3736 /// framework. This primarily includes integer types, and it can optionally 3737 /// include pointer types if the ScalarEvolution class has access to 3738 /// target-specific information. 3739 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3740 // Integers and pointers are always SCEVable. 3741 return Ty->isIntOrPtrTy(); 3742 } 3743 3744 /// Return the size in bits of the specified type, for which isSCEVable must 3745 /// return true. 3746 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3747 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3748 if (Ty->isPointerTy()) 3749 return getDataLayout().getIndexTypeSizeInBits(Ty); 3750 return getDataLayout().getTypeSizeInBits(Ty); 3751 } 3752 3753 /// Return a type with the same bitwidth as the given type and which represents 3754 /// how SCEV will treat the given type, for which isSCEVable must return 3755 /// true. For pointer types, this is the pointer index sized integer type. 3756 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3757 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3758 3759 if (Ty->isIntegerTy()) 3760 return Ty; 3761 3762 // The only other support type is pointer. 3763 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3764 return getDataLayout().getIndexType(Ty); 3765 } 3766 3767 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3768 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3769 } 3770 3771 const SCEV *ScalarEvolution::getCouldNotCompute() { 3772 return CouldNotCompute.get(); 3773 } 3774 3775 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3776 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3777 auto *SU = dyn_cast<SCEVUnknown>(S); 3778 return SU && SU->getValue() == nullptr; 3779 }); 3780 3781 return !ContainsNulls; 3782 } 3783 3784 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3785 HasRecMapType::iterator I = HasRecMap.find(S); 3786 if (I != HasRecMap.end()) 3787 return I->second; 3788 3789 bool FoundAddRec = 3790 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3791 HasRecMap.insert({S, FoundAddRec}); 3792 return FoundAddRec; 3793 } 3794 3795 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3796 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3797 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3798 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3799 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3800 if (!Add) 3801 return {S, nullptr}; 3802 3803 if (Add->getNumOperands() != 2) 3804 return {S, nullptr}; 3805 3806 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3807 if (!ConstOp) 3808 return {S, nullptr}; 3809 3810 return {Add->getOperand(1), ConstOp->getValue()}; 3811 } 3812 3813 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3814 /// by the value and offset from any ValueOffsetPair in the set. 3815 SetVector<ScalarEvolution::ValueOffsetPair> * 3816 ScalarEvolution::getSCEVValues(const SCEV *S) { 3817 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3818 if (SI == ExprValueMap.end()) 3819 return nullptr; 3820 #ifndef NDEBUG 3821 if (VerifySCEVMap) { 3822 // Check there is no dangling Value in the set returned. 3823 for (const auto &VE : SI->second) 3824 assert(ValueExprMap.count(VE.first)); 3825 } 3826 #endif 3827 return &SI->second; 3828 } 3829 3830 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3831 /// cannot be used separately. eraseValueFromMap should be used to remove 3832 /// V from ValueExprMap and ExprValueMap at the same time. 3833 void ScalarEvolution::eraseValueFromMap(Value *V) { 3834 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3835 if (I != ValueExprMap.end()) { 3836 const SCEV *S = I->second; 3837 // Remove {V, 0} from the set of ExprValueMap[S] 3838 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3839 SV->remove({V, nullptr}); 3840 3841 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3842 const SCEV *Stripped; 3843 ConstantInt *Offset; 3844 std::tie(Stripped, Offset) = splitAddExpr(S); 3845 if (Offset != nullptr) { 3846 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3847 SV->remove({V, Offset}); 3848 } 3849 ValueExprMap.erase(V); 3850 } 3851 } 3852 3853 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3854 /// TODO: In reality it is better to check the poison recursively 3855 /// but this is better than nothing. 3856 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3857 if (auto *I = dyn_cast<Instruction>(V)) { 3858 if (isa<OverflowingBinaryOperator>(I)) { 3859 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3860 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3861 return true; 3862 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3863 return true; 3864 } 3865 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3866 return true; 3867 } 3868 return false; 3869 } 3870 3871 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3872 /// create a new one. 3873 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3874 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3875 3876 const SCEV *S = getExistingSCEV(V); 3877 if (S == nullptr) { 3878 S = createSCEV(V); 3879 // During PHI resolution, it is possible to create two SCEVs for the same 3880 // V, so it is needed to double check whether V->S is inserted into 3881 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3882 std::pair<ValueExprMapType::iterator, bool> Pair = 3883 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3884 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3885 ExprValueMap[S].insert({V, nullptr}); 3886 3887 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3888 // ExprValueMap. 3889 const SCEV *Stripped = S; 3890 ConstantInt *Offset = nullptr; 3891 std::tie(Stripped, Offset) = splitAddExpr(S); 3892 // If stripped is SCEVUnknown, don't bother to save 3893 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3894 // increase the complexity of the expansion code. 3895 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3896 // because it may generate add/sub instead of GEP in SCEV expansion. 3897 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3898 !isa<GetElementPtrInst>(V)) 3899 ExprValueMap[Stripped].insert({V, Offset}); 3900 } 3901 } 3902 return S; 3903 } 3904 3905 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3906 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3907 3908 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3909 if (I != ValueExprMap.end()) { 3910 const SCEV *S = I->second; 3911 if (checkValidity(S)) 3912 return S; 3913 eraseValueFromMap(V); 3914 forgetMemoizedResults(S); 3915 } 3916 return nullptr; 3917 } 3918 3919 /// Return a SCEV corresponding to -V = -1*V 3920 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3921 SCEV::NoWrapFlags Flags) { 3922 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3923 return getConstant( 3924 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3925 3926 Type *Ty = V->getType(); 3927 Ty = getEffectiveSCEVType(Ty); 3928 return getMulExpr(V, getMinusOne(Ty), Flags); 3929 } 3930 3931 /// If Expr computes ~A, return A else return nullptr 3932 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3933 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3934 if (!Add || Add->getNumOperands() != 2 || 3935 !Add->getOperand(0)->isAllOnesValue()) 3936 return nullptr; 3937 3938 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3939 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3940 !AddRHS->getOperand(0)->isAllOnesValue()) 3941 return nullptr; 3942 3943 return AddRHS->getOperand(1); 3944 } 3945 3946 /// Return a SCEV corresponding to ~V = -1-V 3947 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3948 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3949 return getConstant( 3950 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3951 3952 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 3953 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 3954 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 3955 SmallVector<const SCEV *, 2> MatchedOperands; 3956 for (const SCEV *Operand : MME->operands()) { 3957 const SCEV *Matched = MatchNotExpr(Operand); 3958 if (!Matched) 3959 return (const SCEV *)nullptr; 3960 MatchedOperands.push_back(Matched); 3961 } 3962 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 3963 MatchedOperands); 3964 }; 3965 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 3966 return Replaced; 3967 } 3968 3969 Type *Ty = V->getType(); 3970 Ty = getEffectiveSCEVType(Ty); 3971 return getMinusSCEV(getMinusOne(Ty), V); 3972 } 3973 3974 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3975 SCEV::NoWrapFlags Flags, 3976 unsigned Depth) { 3977 // Fast path: X - X --> 0. 3978 if (LHS == RHS) 3979 return getZero(LHS->getType()); 3980 3981 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3982 // makes it so that we cannot make much use of NUW. 3983 auto AddFlags = SCEV::FlagAnyWrap; 3984 const bool RHSIsNotMinSigned = 3985 !getSignedRangeMin(RHS).isMinSignedValue(); 3986 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3987 // Let M be the minimum representable signed value. Then (-1)*RHS 3988 // signed-wraps if and only if RHS is M. That can happen even for 3989 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3990 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3991 // (-1)*RHS, we need to prove that RHS != M. 3992 // 3993 // If LHS is non-negative and we know that LHS - RHS does not 3994 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3995 // either by proving that RHS > M or that LHS >= 0. 3996 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3997 AddFlags = SCEV::FlagNSW; 3998 } 3999 } 4000 4001 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4002 // RHS is NSW and LHS >= 0. 4003 // 4004 // The difficulty here is that the NSW flag may have been proven 4005 // relative to a loop that is to be found in a recurrence in LHS and 4006 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4007 // larger scope than intended. 4008 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4009 4010 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4011 } 4012 4013 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4014 unsigned Depth) { 4015 Type *SrcTy = V->getType(); 4016 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4017 "Cannot truncate or zero extend with non-integer arguments!"); 4018 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4019 return V; // No conversion 4020 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4021 return getTruncateExpr(V, Ty, Depth); 4022 return getZeroExtendExpr(V, Ty, Depth); 4023 } 4024 4025 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4026 unsigned Depth) { 4027 Type *SrcTy = V->getType(); 4028 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4029 "Cannot truncate or zero extend with non-integer arguments!"); 4030 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4031 return V; // No conversion 4032 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4033 return getTruncateExpr(V, Ty, Depth); 4034 return getSignExtendExpr(V, Ty, Depth); 4035 } 4036 4037 const SCEV * 4038 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4039 Type *SrcTy = V->getType(); 4040 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4041 "Cannot noop or zero extend with non-integer arguments!"); 4042 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4043 "getNoopOrZeroExtend cannot truncate!"); 4044 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4045 return V; // No conversion 4046 return getZeroExtendExpr(V, Ty); 4047 } 4048 4049 const SCEV * 4050 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4051 Type *SrcTy = V->getType(); 4052 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4053 "Cannot noop or sign extend with non-integer arguments!"); 4054 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4055 "getNoopOrSignExtend cannot truncate!"); 4056 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4057 return V; // No conversion 4058 return getSignExtendExpr(V, Ty); 4059 } 4060 4061 const SCEV * 4062 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4063 Type *SrcTy = V->getType(); 4064 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4065 "Cannot noop or any extend with non-integer arguments!"); 4066 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4067 "getNoopOrAnyExtend cannot truncate!"); 4068 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4069 return V; // No conversion 4070 return getAnyExtendExpr(V, Ty); 4071 } 4072 4073 const SCEV * 4074 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4075 Type *SrcTy = V->getType(); 4076 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4077 "Cannot truncate or noop with non-integer arguments!"); 4078 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4079 "getTruncateOrNoop cannot extend!"); 4080 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4081 return V; // No conversion 4082 return getTruncateExpr(V, Ty); 4083 } 4084 4085 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4086 const SCEV *RHS) { 4087 const SCEV *PromotedLHS = LHS; 4088 const SCEV *PromotedRHS = RHS; 4089 4090 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4091 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4092 else 4093 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4094 4095 return getUMaxExpr(PromotedLHS, PromotedRHS); 4096 } 4097 4098 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4099 const SCEV *RHS) { 4100 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4101 return getUMinFromMismatchedTypes(Ops); 4102 } 4103 4104 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4105 SmallVectorImpl<const SCEV *> &Ops) { 4106 assert(!Ops.empty() && "At least one operand must be!"); 4107 // Trivial case. 4108 if (Ops.size() == 1) 4109 return Ops[0]; 4110 4111 // Find the max type first. 4112 Type *MaxType = nullptr; 4113 for (auto *S : Ops) 4114 if (MaxType) 4115 MaxType = getWiderType(MaxType, S->getType()); 4116 else 4117 MaxType = S->getType(); 4118 assert(MaxType && "Failed to find maximum type!"); 4119 4120 // Extend all ops to max type. 4121 SmallVector<const SCEV *, 2> PromotedOps; 4122 for (auto *S : Ops) 4123 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4124 4125 // Generate umin. 4126 return getUMinExpr(PromotedOps); 4127 } 4128 4129 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4130 // A pointer operand may evaluate to a nonpointer expression, such as null. 4131 if (!V->getType()->isPointerTy()) 4132 return V; 4133 4134 while (true) { 4135 if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) { 4136 V = Cast->getOperand(); 4137 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4138 const SCEV *PtrOp = nullptr; 4139 for (const SCEV *NAryOp : NAry->operands()) { 4140 if (NAryOp->getType()->isPointerTy()) { 4141 // Cannot find the base of an expression with multiple pointer ops. 4142 if (PtrOp) 4143 return V; 4144 PtrOp = NAryOp; 4145 } 4146 } 4147 if (!PtrOp) // All operands were non-pointer. 4148 return V; 4149 V = PtrOp; 4150 } else // Not something we can look further into. 4151 return V; 4152 } 4153 } 4154 4155 /// Push users of the given Instruction onto the given Worklist. 4156 static void 4157 PushDefUseChildren(Instruction *I, 4158 SmallVectorImpl<Instruction *> &Worklist) { 4159 // Push the def-use children onto the Worklist stack. 4160 for (User *U : I->users()) 4161 Worklist.push_back(cast<Instruction>(U)); 4162 } 4163 4164 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4165 SmallVector<Instruction *, 16> Worklist; 4166 PushDefUseChildren(PN, Worklist); 4167 4168 SmallPtrSet<Instruction *, 8> Visited; 4169 Visited.insert(PN); 4170 while (!Worklist.empty()) { 4171 Instruction *I = Worklist.pop_back_val(); 4172 if (!Visited.insert(I).second) 4173 continue; 4174 4175 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4176 if (It != ValueExprMap.end()) { 4177 const SCEV *Old = It->second; 4178 4179 // Short-circuit the def-use traversal if the symbolic name 4180 // ceases to appear in expressions. 4181 if (Old != SymName && !hasOperand(Old, SymName)) 4182 continue; 4183 4184 // SCEVUnknown for a PHI either means that it has an unrecognized 4185 // structure, it's a PHI that's in the progress of being computed 4186 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4187 // additional loop trip count information isn't going to change anything. 4188 // In the second case, createNodeForPHI will perform the necessary 4189 // updates on its own when it gets to that point. In the third, we do 4190 // want to forget the SCEVUnknown. 4191 if (!isa<PHINode>(I) || 4192 !isa<SCEVUnknown>(Old) || 4193 (I != PN && Old == SymName)) { 4194 eraseValueFromMap(It->first); 4195 forgetMemoizedResults(Old); 4196 } 4197 } 4198 4199 PushDefUseChildren(I, Worklist); 4200 } 4201 } 4202 4203 namespace { 4204 4205 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4206 /// expression in case its Loop is L. If it is not L then 4207 /// if IgnoreOtherLoops is true then use AddRec itself 4208 /// otherwise rewrite cannot be done. 4209 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4210 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4211 public: 4212 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4213 bool IgnoreOtherLoops = true) { 4214 SCEVInitRewriter Rewriter(L, SE); 4215 const SCEV *Result = Rewriter.visit(S); 4216 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4217 return SE.getCouldNotCompute(); 4218 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4219 ? SE.getCouldNotCompute() 4220 : Result; 4221 } 4222 4223 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4224 if (!SE.isLoopInvariant(Expr, L)) 4225 SeenLoopVariantSCEVUnknown = true; 4226 return Expr; 4227 } 4228 4229 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4230 // Only re-write AddRecExprs for this loop. 4231 if (Expr->getLoop() == L) 4232 return Expr->getStart(); 4233 SeenOtherLoops = true; 4234 return Expr; 4235 } 4236 4237 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4238 4239 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4240 4241 private: 4242 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4243 : SCEVRewriteVisitor(SE), L(L) {} 4244 4245 const Loop *L; 4246 bool SeenLoopVariantSCEVUnknown = false; 4247 bool SeenOtherLoops = false; 4248 }; 4249 4250 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4251 /// increment expression in case its Loop is L. If it is not L then 4252 /// use AddRec itself. 4253 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4254 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4255 public: 4256 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4257 SCEVPostIncRewriter Rewriter(L, SE); 4258 const SCEV *Result = Rewriter.visit(S); 4259 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4260 ? SE.getCouldNotCompute() 4261 : Result; 4262 } 4263 4264 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4265 if (!SE.isLoopInvariant(Expr, L)) 4266 SeenLoopVariantSCEVUnknown = true; 4267 return Expr; 4268 } 4269 4270 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4271 // Only re-write AddRecExprs for this loop. 4272 if (Expr->getLoop() == L) 4273 return Expr->getPostIncExpr(SE); 4274 SeenOtherLoops = true; 4275 return Expr; 4276 } 4277 4278 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4279 4280 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4281 4282 private: 4283 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4284 : SCEVRewriteVisitor(SE), L(L) {} 4285 4286 const Loop *L; 4287 bool SeenLoopVariantSCEVUnknown = false; 4288 bool SeenOtherLoops = false; 4289 }; 4290 4291 /// This class evaluates the compare condition by matching it against the 4292 /// condition of loop latch. If there is a match we assume a true value 4293 /// for the condition while building SCEV nodes. 4294 class SCEVBackedgeConditionFolder 4295 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4296 public: 4297 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4298 ScalarEvolution &SE) { 4299 bool IsPosBECond = false; 4300 Value *BECond = nullptr; 4301 if (BasicBlock *Latch = L->getLoopLatch()) { 4302 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4303 if (BI && BI->isConditional()) { 4304 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4305 "Both outgoing branches should not target same header!"); 4306 BECond = BI->getCondition(); 4307 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4308 } else { 4309 return S; 4310 } 4311 } 4312 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4313 return Rewriter.visit(S); 4314 } 4315 4316 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4317 const SCEV *Result = Expr; 4318 bool InvariantF = SE.isLoopInvariant(Expr, L); 4319 4320 if (!InvariantF) { 4321 Instruction *I = cast<Instruction>(Expr->getValue()); 4322 switch (I->getOpcode()) { 4323 case Instruction::Select: { 4324 SelectInst *SI = cast<SelectInst>(I); 4325 Optional<const SCEV *> Res = 4326 compareWithBackedgeCondition(SI->getCondition()); 4327 if (Res.hasValue()) { 4328 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4329 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4330 } 4331 break; 4332 } 4333 default: { 4334 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4335 if (Res.hasValue()) 4336 Result = Res.getValue(); 4337 break; 4338 } 4339 } 4340 } 4341 return Result; 4342 } 4343 4344 private: 4345 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4346 bool IsPosBECond, ScalarEvolution &SE) 4347 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4348 IsPositiveBECond(IsPosBECond) {} 4349 4350 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4351 4352 const Loop *L; 4353 /// Loop back condition. 4354 Value *BackedgeCond = nullptr; 4355 /// Set to true if loop back is on positive branch condition. 4356 bool IsPositiveBECond; 4357 }; 4358 4359 Optional<const SCEV *> 4360 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4361 4362 // If value matches the backedge condition for loop latch, 4363 // then return a constant evolution node based on loopback 4364 // branch taken. 4365 if (BackedgeCond == IC) 4366 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4367 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4368 return None; 4369 } 4370 4371 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4372 public: 4373 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4374 ScalarEvolution &SE) { 4375 SCEVShiftRewriter Rewriter(L, SE); 4376 const SCEV *Result = Rewriter.visit(S); 4377 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4378 } 4379 4380 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4381 // Only allow AddRecExprs for this loop. 4382 if (!SE.isLoopInvariant(Expr, L)) 4383 Valid = false; 4384 return Expr; 4385 } 4386 4387 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4388 if (Expr->getLoop() == L && Expr->isAffine()) 4389 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4390 Valid = false; 4391 return Expr; 4392 } 4393 4394 bool isValid() { return Valid; } 4395 4396 private: 4397 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4398 : SCEVRewriteVisitor(SE), L(L) {} 4399 4400 const Loop *L; 4401 bool Valid = true; 4402 }; 4403 4404 } // end anonymous namespace 4405 4406 SCEV::NoWrapFlags 4407 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4408 if (!AR->isAffine()) 4409 return SCEV::FlagAnyWrap; 4410 4411 using OBO = OverflowingBinaryOperator; 4412 4413 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4414 4415 if (!AR->hasNoSignedWrap()) { 4416 ConstantRange AddRecRange = getSignedRange(AR); 4417 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4418 4419 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4420 Instruction::Add, IncRange, OBO::NoSignedWrap); 4421 if (NSWRegion.contains(AddRecRange)) 4422 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4423 } 4424 4425 if (!AR->hasNoUnsignedWrap()) { 4426 ConstantRange AddRecRange = getUnsignedRange(AR); 4427 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4428 4429 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4430 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4431 if (NUWRegion.contains(AddRecRange)) 4432 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4433 } 4434 4435 return Result; 4436 } 4437 4438 SCEV::NoWrapFlags 4439 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4440 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4441 4442 if (AR->hasNoSignedWrap()) 4443 return Result; 4444 4445 if (!AR->isAffine()) 4446 return Result; 4447 4448 const SCEV *Step = AR->getStepRecurrence(*this); 4449 const Loop *L = AR->getLoop(); 4450 4451 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4452 // Note that this serves two purposes: It filters out loops that are 4453 // simply not analyzable, and it covers the case where this code is 4454 // being called from within backedge-taken count analysis, such that 4455 // attempting to ask for the backedge-taken count would likely result 4456 // in infinite recursion. In the later case, the analysis code will 4457 // cope with a conservative value, and it will take care to purge 4458 // that value once it has finished. 4459 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4460 4461 // Normally, in the cases we can prove no-overflow via a 4462 // backedge guarding condition, we can also compute a backedge 4463 // taken count for the loop. The exceptions are assumptions and 4464 // guards present in the loop -- SCEV is not great at exploiting 4465 // these to compute max backedge taken counts, but can still use 4466 // these to prove lack of overflow. Use this fact to avoid 4467 // doing extra work that may not pay off. 4468 4469 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4470 AC.assumptions().empty()) 4471 return Result; 4472 4473 // If the backedge is guarded by a comparison with the pre-inc value the 4474 // addrec is safe. Also, if the entry is guarded by a comparison with the 4475 // start value and the backedge is guarded by a comparison with the post-inc 4476 // value, the addrec is safe. 4477 ICmpInst::Predicate Pred; 4478 const SCEV *OverflowLimit = 4479 getSignedOverflowLimitForStep(Step, &Pred, this); 4480 if (OverflowLimit && 4481 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4482 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4483 Result = setFlags(Result, SCEV::FlagNSW); 4484 } 4485 return Result; 4486 } 4487 SCEV::NoWrapFlags 4488 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4489 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4490 4491 if (AR->hasNoUnsignedWrap()) 4492 return Result; 4493 4494 if (!AR->isAffine()) 4495 return Result; 4496 4497 const SCEV *Step = AR->getStepRecurrence(*this); 4498 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4499 const Loop *L = AR->getLoop(); 4500 4501 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4502 // Note that this serves two purposes: It filters out loops that are 4503 // simply not analyzable, and it covers the case where this code is 4504 // being called from within backedge-taken count analysis, such that 4505 // attempting to ask for the backedge-taken count would likely result 4506 // in infinite recursion. In the later case, the analysis code will 4507 // cope with a conservative value, and it will take care to purge 4508 // that value once it has finished. 4509 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4510 4511 // Normally, in the cases we can prove no-overflow via a 4512 // backedge guarding condition, we can also compute a backedge 4513 // taken count for the loop. The exceptions are assumptions and 4514 // guards present in the loop -- SCEV is not great at exploiting 4515 // these to compute max backedge taken counts, but can still use 4516 // these to prove lack of overflow. Use this fact to avoid 4517 // doing extra work that may not pay off. 4518 4519 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4520 AC.assumptions().empty()) 4521 return Result; 4522 4523 // If the backedge is guarded by a comparison with the pre-inc value the 4524 // addrec is safe. Also, if the entry is guarded by a comparison with the 4525 // start value and the backedge is guarded by a comparison with the post-inc 4526 // value, the addrec is safe. 4527 if (isKnownPositive(Step)) { 4528 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 4529 getUnsignedRangeMax(Step)); 4530 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 4531 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 4532 Result = setFlags(Result, SCEV::FlagNUW); 4533 } 4534 } 4535 4536 return Result; 4537 } 4538 4539 namespace { 4540 4541 /// Represents an abstract binary operation. This may exist as a 4542 /// normal instruction or constant expression, or may have been 4543 /// derived from an expression tree. 4544 struct BinaryOp { 4545 unsigned Opcode; 4546 Value *LHS; 4547 Value *RHS; 4548 bool IsNSW = false; 4549 bool IsNUW = false; 4550 bool IsExact = false; 4551 4552 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4553 /// constant expression. 4554 Operator *Op = nullptr; 4555 4556 explicit BinaryOp(Operator *Op) 4557 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4558 Op(Op) { 4559 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4560 IsNSW = OBO->hasNoSignedWrap(); 4561 IsNUW = OBO->hasNoUnsignedWrap(); 4562 } 4563 if (auto *PEO = dyn_cast<PossiblyExactOperator>(Op)) 4564 IsExact = PEO->isExact(); 4565 } 4566 4567 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4568 bool IsNUW = false, bool IsExact = false) 4569 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 4570 IsExact(IsExact) {} 4571 }; 4572 4573 } // end anonymous namespace 4574 4575 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4576 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4577 auto *Op = dyn_cast<Operator>(V); 4578 if (!Op) 4579 return None; 4580 4581 // Implementation detail: all the cleverness here should happen without 4582 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4583 // SCEV expressions when possible, and we should not break that. 4584 4585 switch (Op->getOpcode()) { 4586 case Instruction::Add: 4587 case Instruction::Sub: 4588 case Instruction::Mul: 4589 case Instruction::UDiv: 4590 case Instruction::URem: 4591 case Instruction::And: 4592 case Instruction::Or: 4593 case Instruction::AShr: 4594 case Instruction::Shl: 4595 return BinaryOp(Op); 4596 4597 case Instruction::Xor: 4598 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4599 // If the RHS of the xor is a signmask, then this is just an add. 4600 // Instcombine turns add of signmask into xor as a strength reduction step. 4601 if (RHSC->getValue().isSignMask()) 4602 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4603 return BinaryOp(Op); 4604 4605 case Instruction::LShr: 4606 // Turn logical shift right of a constant into a unsigned divide. 4607 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4608 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4609 4610 // If the shift count is not less than the bitwidth, the result of 4611 // the shift is undefined. Don't try to analyze it, because the 4612 // resolution chosen here may differ from the resolution chosen in 4613 // other parts of the compiler. 4614 if (SA->getValue().ult(BitWidth)) { 4615 Constant *X = 4616 ConstantInt::get(SA->getContext(), 4617 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4618 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4619 } 4620 } 4621 return BinaryOp(Op); 4622 4623 case Instruction::ExtractValue: { 4624 auto *EVI = cast<ExtractValueInst>(Op); 4625 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4626 break; 4627 4628 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4629 if (!WO) 4630 break; 4631 4632 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4633 bool Signed = WO->isSigned(); 4634 // TODO: Should add nuw/nsw flags for mul as well. 4635 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4636 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4637 4638 // Now that we know that all uses of the arithmetic-result component of 4639 // CI are guarded by the overflow check, we can go ahead and pretend 4640 // that the arithmetic is non-overflowing. 4641 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4642 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4643 } 4644 4645 default: 4646 break; 4647 } 4648 4649 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4650 // semantics as a Sub, return a binary sub expression. 4651 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4652 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4653 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4654 4655 return None; 4656 } 4657 4658 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4659 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4660 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4661 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4662 /// follows one of the following patterns: 4663 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4664 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4665 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4666 /// we return the type of the truncation operation, and indicate whether the 4667 /// truncated type should be treated as signed/unsigned by setting 4668 /// \p Signed to true/false, respectively. 4669 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4670 bool &Signed, ScalarEvolution &SE) { 4671 // The case where Op == SymbolicPHI (that is, with no type conversions on 4672 // the way) is handled by the regular add recurrence creating logic and 4673 // would have already been triggered in createAddRecForPHI. Reaching it here 4674 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4675 // because one of the other operands of the SCEVAddExpr updating this PHI is 4676 // not invariant). 4677 // 4678 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4679 // this case predicates that allow us to prove that Op == SymbolicPHI will 4680 // be added. 4681 if (Op == SymbolicPHI) 4682 return nullptr; 4683 4684 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4685 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4686 if (SourceBits != NewBits) 4687 return nullptr; 4688 4689 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4690 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4691 if (!SExt && !ZExt) 4692 return nullptr; 4693 const SCEVTruncateExpr *Trunc = 4694 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4695 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4696 if (!Trunc) 4697 return nullptr; 4698 const SCEV *X = Trunc->getOperand(); 4699 if (X != SymbolicPHI) 4700 return nullptr; 4701 Signed = SExt != nullptr; 4702 return Trunc->getType(); 4703 } 4704 4705 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4706 if (!PN->getType()->isIntegerTy()) 4707 return nullptr; 4708 const Loop *L = LI.getLoopFor(PN->getParent()); 4709 if (!L || L->getHeader() != PN->getParent()) 4710 return nullptr; 4711 return L; 4712 } 4713 4714 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4715 // computation that updates the phi follows the following pattern: 4716 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4717 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4718 // If so, try to see if it can be rewritten as an AddRecExpr under some 4719 // Predicates. If successful, return them as a pair. Also cache the results 4720 // of the analysis. 4721 // 4722 // Example usage scenario: 4723 // Say the Rewriter is called for the following SCEV: 4724 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4725 // where: 4726 // %X = phi i64 (%Start, %BEValue) 4727 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4728 // and call this function with %SymbolicPHI = %X. 4729 // 4730 // The analysis will find that the value coming around the backedge has 4731 // the following SCEV: 4732 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4733 // Upon concluding that this matches the desired pattern, the function 4734 // will return the pair {NewAddRec, SmallPredsVec} where: 4735 // NewAddRec = {%Start,+,%Step} 4736 // SmallPredsVec = {P1, P2, P3} as follows: 4737 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4738 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4739 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4740 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4741 // under the predicates {P1,P2,P3}. 4742 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4743 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4744 // 4745 // TODO's: 4746 // 4747 // 1) Extend the Induction descriptor to also support inductions that involve 4748 // casts: When needed (namely, when we are called in the context of the 4749 // vectorizer induction analysis), a Set of cast instructions will be 4750 // populated by this method, and provided back to isInductionPHI. This is 4751 // needed to allow the vectorizer to properly record them to be ignored by 4752 // the cost model and to avoid vectorizing them (otherwise these casts, 4753 // which are redundant under the runtime overflow checks, will be 4754 // vectorized, which can be costly). 4755 // 4756 // 2) Support additional induction/PHISCEV patterns: We also want to support 4757 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4758 // after the induction update operation (the induction increment): 4759 // 4760 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4761 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4762 // 4763 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4764 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4765 // 4766 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4767 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4768 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4769 SmallVector<const SCEVPredicate *, 3> Predicates; 4770 4771 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4772 // return an AddRec expression under some predicate. 4773 4774 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4775 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4776 assert(L && "Expecting an integer loop header phi"); 4777 4778 // The loop may have multiple entrances or multiple exits; we can analyze 4779 // this phi as an addrec if it has a unique entry value and a unique 4780 // backedge value. 4781 Value *BEValueV = nullptr, *StartValueV = nullptr; 4782 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4783 Value *V = PN->getIncomingValue(i); 4784 if (L->contains(PN->getIncomingBlock(i))) { 4785 if (!BEValueV) { 4786 BEValueV = V; 4787 } else if (BEValueV != V) { 4788 BEValueV = nullptr; 4789 break; 4790 } 4791 } else if (!StartValueV) { 4792 StartValueV = V; 4793 } else if (StartValueV != V) { 4794 StartValueV = nullptr; 4795 break; 4796 } 4797 } 4798 if (!BEValueV || !StartValueV) 4799 return None; 4800 4801 const SCEV *BEValue = getSCEV(BEValueV); 4802 4803 // If the value coming around the backedge is an add with the symbolic 4804 // value we just inserted, possibly with casts that we can ignore under 4805 // an appropriate runtime guard, then we found a simple induction variable! 4806 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4807 if (!Add) 4808 return None; 4809 4810 // If there is a single occurrence of the symbolic value, possibly 4811 // casted, replace it with a recurrence. 4812 unsigned FoundIndex = Add->getNumOperands(); 4813 Type *TruncTy = nullptr; 4814 bool Signed; 4815 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4816 if ((TruncTy = 4817 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4818 if (FoundIndex == e) { 4819 FoundIndex = i; 4820 break; 4821 } 4822 4823 if (FoundIndex == Add->getNumOperands()) 4824 return None; 4825 4826 // Create an add with everything but the specified operand. 4827 SmallVector<const SCEV *, 8> Ops; 4828 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4829 if (i != FoundIndex) 4830 Ops.push_back(Add->getOperand(i)); 4831 const SCEV *Accum = getAddExpr(Ops); 4832 4833 // The runtime checks will not be valid if the step amount is 4834 // varying inside the loop. 4835 if (!isLoopInvariant(Accum, L)) 4836 return None; 4837 4838 // *** Part2: Create the predicates 4839 4840 // Analysis was successful: we have a phi-with-cast pattern for which we 4841 // can return an AddRec expression under the following predicates: 4842 // 4843 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4844 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4845 // P2: An Equal predicate that guarantees that 4846 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4847 // P3: An Equal predicate that guarantees that 4848 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4849 // 4850 // As we next prove, the above predicates guarantee that: 4851 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4852 // 4853 // 4854 // More formally, we want to prove that: 4855 // Expr(i+1) = Start + (i+1) * Accum 4856 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4857 // 4858 // Given that: 4859 // 1) Expr(0) = Start 4860 // 2) Expr(1) = Start + Accum 4861 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4862 // 3) Induction hypothesis (step i): 4863 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4864 // 4865 // Proof: 4866 // Expr(i+1) = 4867 // = Start + (i+1)*Accum 4868 // = (Start + i*Accum) + Accum 4869 // = Expr(i) + Accum 4870 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4871 // :: from step i 4872 // 4873 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4874 // 4875 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4876 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4877 // + Accum :: from P3 4878 // 4879 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4880 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4881 // 4882 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4883 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4884 // 4885 // By induction, the same applies to all iterations 1<=i<n: 4886 // 4887 4888 // Create a truncated addrec for which we will add a no overflow check (P1). 4889 const SCEV *StartVal = getSCEV(StartValueV); 4890 const SCEV *PHISCEV = 4891 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4892 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4893 4894 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4895 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4896 // will be constant. 4897 // 4898 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4899 // add P1. 4900 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4901 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4902 Signed ? SCEVWrapPredicate::IncrementNSSW 4903 : SCEVWrapPredicate::IncrementNUSW; 4904 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4905 Predicates.push_back(AddRecPred); 4906 } 4907 4908 // Create the Equal Predicates P2,P3: 4909 4910 // It is possible that the predicates P2 and/or P3 are computable at 4911 // compile time due to StartVal and/or Accum being constants. 4912 // If either one is, then we can check that now and escape if either P2 4913 // or P3 is false. 4914 4915 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4916 // for each of StartVal and Accum 4917 auto getExtendedExpr = [&](const SCEV *Expr, 4918 bool CreateSignExtend) -> const SCEV * { 4919 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4920 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4921 const SCEV *ExtendedExpr = 4922 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4923 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4924 return ExtendedExpr; 4925 }; 4926 4927 // Given: 4928 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4929 // = getExtendedExpr(Expr) 4930 // Determine whether the predicate P: Expr == ExtendedExpr 4931 // is known to be false at compile time 4932 auto PredIsKnownFalse = [&](const SCEV *Expr, 4933 const SCEV *ExtendedExpr) -> bool { 4934 return Expr != ExtendedExpr && 4935 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4936 }; 4937 4938 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4939 if (PredIsKnownFalse(StartVal, StartExtended)) { 4940 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4941 return None; 4942 } 4943 4944 // The Step is always Signed (because the overflow checks are either 4945 // NSSW or NUSW) 4946 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4947 if (PredIsKnownFalse(Accum, AccumExtended)) { 4948 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4949 return None; 4950 } 4951 4952 auto AppendPredicate = [&](const SCEV *Expr, 4953 const SCEV *ExtendedExpr) -> void { 4954 if (Expr != ExtendedExpr && 4955 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4956 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4957 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4958 Predicates.push_back(Pred); 4959 } 4960 }; 4961 4962 AppendPredicate(StartVal, StartExtended); 4963 AppendPredicate(Accum, AccumExtended); 4964 4965 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4966 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4967 // into NewAR if it will also add the runtime overflow checks specified in 4968 // Predicates. 4969 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4970 4971 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4972 std::make_pair(NewAR, Predicates); 4973 // Remember the result of the analysis for this SCEV at this locayyytion. 4974 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4975 return PredRewrite; 4976 } 4977 4978 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4979 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4980 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4981 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4982 if (!L) 4983 return None; 4984 4985 // Check to see if we already analyzed this PHI. 4986 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4987 if (I != PredicatedSCEVRewrites.end()) { 4988 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4989 I->second; 4990 // Analysis was done before and failed to create an AddRec: 4991 if (Rewrite.first == SymbolicPHI) 4992 return None; 4993 // Analysis was done before and succeeded to create an AddRec under 4994 // a predicate: 4995 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4996 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4997 return Rewrite; 4998 } 4999 5000 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5001 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5002 5003 // Record in the cache that the analysis failed 5004 if (!Rewrite) { 5005 SmallVector<const SCEVPredicate *, 3> Predicates; 5006 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5007 return None; 5008 } 5009 5010 return Rewrite; 5011 } 5012 5013 // FIXME: This utility is currently required because the Rewriter currently 5014 // does not rewrite this expression: 5015 // {0, +, (sext ix (trunc iy to ix) to iy)} 5016 // into {0, +, %step}, 5017 // even when the following Equal predicate exists: 5018 // "%step == (sext ix (trunc iy to ix) to iy)". 5019 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5020 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5021 if (AR1 == AR2) 5022 return true; 5023 5024 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5025 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 5026 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 5027 return false; 5028 return true; 5029 }; 5030 5031 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5032 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5033 return false; 5034 return true; 5035 } 5036 5037 /// A helper function for createAddRecFromPHI to handle simple cases. 5038 /// 5039 /// This function tries to find an AddRec expression for the simplest (yet most 5040 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5041 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5042 /// technique for finding the AddRec expression. 5043 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5044 Value *BEValueV, 5045 Value *StartValueV) { 5046 const Loop *L = LI.getLoopFor(PN->getParent()); 5047 assert(L && L->getHeader() == PN->getParent()); 5048 assert(BEValueV && StartValueV); 5049 5050 auto BO = MatchBinaryOp(BEValueV, DT); 5051 if (!BO) 5052 return nullptr; 5053 5054 if (BO->Opcode != Instruction::Add) 5055 return nullptr; 5056 5057 const SCEV *Accum = nullptr; 5058 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5059 Accum = getSCEV(BO->RHS); 5060 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5061 Accum = getSCEV(BO->LHS); 5062 5063 if (!Accum) 5064 return nullptr; 5065 5066 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5067 if (BO->IsNUW) 5068 Flags = setFlags(Flags, SCEV::FlagNUW); 5069 if (BO->IsNSW) 5070 Flags = setFlags(Flags, SCEV::FlagNSW); 5071 5072 const SCEV *StartVal = getSCEV(StartValueV); 5073 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5074 5075 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5076 5077 // We can add Flags to the post-inc expression only if we 5078 // know that it is *undefined behavior* for BEValueV to 5079 // overflow. 5080 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5081 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5082 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5083 5084 return PHISCEV; 5085 } 5086 5087 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5088 const Loop *L = LI.getLoopFor(PN->getParent()); 5089 if (!L || L->getHeader() != PN->getParent()) 5090 return nullptr; 5091 5092 // The loop may have multiple entrances or multiple exits; we can analyze 5093 // this phi as an addrec if it has a unique entry value and a unique 5094 // backedge value. 5095 Value *BEValueV = nullptr, *StartValueV = nullptr; 5096 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5097 Value *V = PN->getIncomingValue(i); 5098 if (L->contains(PN->getIncomingBlock(i))) { 5099 if (!BEValueV) { 5100 BEValueV = V; 5101 } else if (BEValueV != V) { 5102 BEValueV = nullptr; 5103 break; 5104 } 5105 } else if (!StartValueV) { 5106 StartValueV = V; 5107 } else if (StartValueV != V) { 5108 StartValueV = nullptr; 5109 break; 5110 } 5111 } 5112 if (!BEValueV || !StartValueV) 5113 return nullptr; 5114 5115 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5116 "PHI node already processed?"); 5117 5118 // First, try to find AddRec expression without creating a fictituos symbolic 5119 // value for PN. 5120 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5121 return S; 5122 5123 // Handle PHI node value symbolically. 5124 const SCEV *SymbolicName = getUnknown(PN); 5125 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5126 5127 // Using this symbolic name for the PHI, analyze the value coming around 5128 // the back-edge. 5129 const SCEV *BEValue = getSCEV(BEValueV); 5130 5131 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5132 // has a special value for the first iteration of the loop. 5133 5134 // If the value coming around the backedge is an add with the symbolic 5135 // value we just inserted, then we found a simple induction variable! 5136 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5137 // If there is a single occurrence of the symbolic value, replace it 5138 // with a recurrence. 5139 unsigned FoundIndex = Add->getNumOperands(); 5140 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5141 if (Add->getOperand(i) == SymbolicName) 5142 if (FoundIndex == e) { 5143 FoundIndex = i; 5144 break; 5145 } 5146 5147 if (FoundIndex != Add->getNumOperands()) { 5148 // Create an add with everything but the specified operand. 5149 SmallVector<const SCEV *, 8> Ops; 5150 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5151 if (i != FoundIndex) 5152 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5153 L, *this)); 5154 const SCEV *Accum = getAddExpr(Ops); 5155 5156 // This is not a valid addrec if the step amount is varying each 5157 // loop iteration, but is not itself an addrec in this loop. 5158 if (isLoopInvariant(Accum, L) || 5159 (isa<SCEVAddRecExpr>(Accum) && 5160 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5161 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5162 5163 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5164 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5165 if (BO->IsNUW) 5166 Flags = setFlags(Flags, SCEV::FlagNUW); 5167 if (BO->IsNSW) 5168 Flags = setFlags(Flags, SCEV::FlagNSW); 5169 } 5170 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5171 // If the increment is an inbounds GEP, then we know the address 5172 // space cannot be wrapped around. We cannot make any guarantee 5173 // about signed or unsigned overflow because pointers are 5174 // unsigned but we may have a negative index from the base 5175 // pointer. We can guarantee that no unsigned wrap occurs if the 5176 // indices form a positive value. 5177 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5178 Flags = setFlags(Flags, SCEV::FlagNW); 5179 5180 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5181 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5182 Flags = setFlags(Flags, SCEV::FlagNUW); 5183 } 5184 5185 // We cannot transfer nuw and nsw flags from subtraction 5186 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5187 // for instance. 5188 } 5189 5190 const SCEV *StartVal = getSCEV(StartValueV); 5191 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5192 5193 // Okay, for the entire analysis of this edge we assumed the PHI 5194 // to be symbolic. We now need to go back and purge all of the 5195 // entries for the scalars that use the symbolic expression. 5196 forgetSymbolicName(PN, SymbolicName); 5197 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5198 5199 // We can add Flags to the post-inc expression only if we 5200 // know that it is *undefined behavior* for BEValueV to 5201 // overflow. 5202 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5203 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5204 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5205 5206 return PHISCEV; 5207 } 5208 } 5209 } else { 5210 // Otherwise, this could be a loop like this: 5211 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5212 // In this case, j = {1,+,1} and BEValue is j. 5213 // Because the other in-value of i (0) fits the evolution of BEValue 5214 // i really is an addrec evolution. 5215 // 5216 // We can generalize this saying that i is the shifted value of BEValue 5217 // by one iteration: 5218 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5219 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5220 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5221 if (Shifted != getCouldNotCompute() && 5222 Start != getCouldNotCompute()) { 5223 const SCEV *StartVal = getSCEV(StartValueV); 5224 if (Start == StartVal) { 5225 // Okay, for the entire analysis of this edge we assumed the PHI 5226 // to be symbolic. We now need to go back and purge all of the 5227 // entries for the scalars that use the symbolic expression. 5228 forgetSymbolicName(PN, SymbolicName); 5229 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5230 return Shifted; 5231 } 5232 } 5233 } 5234 5235 // Remove the temporary PHI node SCEV that has been inserted while intending 5236 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5237 // as it will prevent later (possibly simpler) SCEV expressions to be added 5238 // to the ValueExprMap. 5239 eraseValueFromMap(PN); 5240 5241 return nullptr; 5242 } 5243 5244 // Checks if the SCEV S is available at BB. S is considered available at BB 5245 // if S can be materialized at BB without introducing a fault. 5246 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5247 BasicBlock *BB) { 5248 struct CheckAvailable { 5249 bool TraversalDone = false; 5250 bool Available = true; 5251 5252 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5253 BasicBlock *BB = nullptr; 5254 DominatorTree &DT; 5255 5256 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5257 : L(L), BB(BB), DT(DT) {} 5258 5259 bool setUnavailable() { 5260 TraversalDone = true; 5261 Available = false; 5262 return false; 5263 } 5264 5265 bool follow(const SCEV *S) { 5266 switch (S->getSCEVType()) { 5267 case scConstant: 5268 case scPtrToInt: 5269 case scTruncate: 5270 case scZeroExtend: 5271 case scSignExtend: 5272 case scAddExpr: 5273 case scMulExpr: 5274 case scUMaxExpr: 5275 case scSMaxExpr: 5276 case scUMinExpr: 5277 case scSMinExpr: 5278 // These expressions are available if their operand(s) is/are. 5279 return true; 5280 5281 case scAddRecExpr: { 5282 // We allow add recurrences that are on the loop BB is in, or some 5283 // outer loop. This guarantees availability because the value of the 5284 // add recurrence at BB is simply the "current" value of the induction 5285 // variable. We can relax this in the future; for instance an add 5286 // recurrence on a sibling dominating loop is also available at BB. 5287 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5288 if (L && (ARLoop == L || ARLoop->contains(L))) 5289 return true; 5290 5291 return setUnavailable(); 5292 } 5293 5294 case scUnknown: { 5295 // For SCEVUnknown, we check for simple dominance. 5296 const auto *SU = cast<SCEVUnknown>(S); 5297 Value *V = SU->getValue(); 5298 5299 if (isa<Argument>(V)) 5300 return false; 5301 5302 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5303 return false; 5304 5305 return setUnavailable(); 5306 } 5307 5308 case scUDivExpr: 5309 case scCouldNotCompute: 5310 // We do not try to smart about these at all. 5311 return setUnavailable(); 5312 } 5313 llvm_unreachable("Unknown SCEV kind!"); 5314 } 5315 5316 bool isDone() { return TraversalDone; } 5317 }; 5318 5319 CheckAvailable CA(L, BB, DT); 5320 SCEVTraversal<CheckAvailable> ST(CA); 5321 5322 ST.visitAll(S); 5323 return CA.Available; 5324 } 5325 5326 // Try to match a control flow sequence that branches out at BI and merges back 5327 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5328 // match. 5329 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5330 Value *&C, Value *&LHS, Value *&RHS) { 5331 C = BI->getCondition(); 5332 5333 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5334 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5335 5336 if (!LeftEdge.isSingleEdge()) 5337 return false; 5338 5339 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5340 5341 Use &LeftUse = Merge->getOperandUse(0); 5342 Use &RightUse = Merge->getOperandUse(1); 5343 5344 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5345 LHS = LeftUse; 5346 RHS = RightUse; 5347 return true; 5348 } 5349 5350 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5351 LHS = RightUse; 5352 RHS = LeftUse; 5353 return true; 5354 } 5355 5356 return false; 5357 } 5358 5359 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5360 auto IsReachable = 5361 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5362 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5363 const Loop *L = LI.getLoopFor(PN->getParent()); 5364 5365 // We don't want to break LCSSA, even in a SCEV expression tree. 5366 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5367 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5368 return nullptr; 5369 5370 // Try to match 5371 // 5372 // br %cond, label %left, label %right 5373 // left: 5374 // br label %merge 5375 // right: 5376 // br label %merge 5377 // merge: 5378 // V = phi [ %x, %left ], [ %y, %right ] 5379 // 5380 // as "select %cond, %x, %y" 5381 5382 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5383 assert(IDom && "At least the entry block should dominate PN"); 5384 5385 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5386 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5387 5388 if (BI && BI->isConditional() && 5389 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5390 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5391 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5392 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5393 } 5394 5395 return nullptr; 5396 } 5397 5398 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5399 if (const SCEV *S = createAddRecFromPHI(PN)) 5400 return S; 5401 5402 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5403 return S; 5404 5405 // If the PHI has a single incoming value, follow that value, unless the 5406 // PHI's incoming blocks are in a different loop, in which case doing so 5407 // risks breaking LCSSA form. Instcombine would normally zap these, but 5408 // it doesn't have DominatorTree information, so it may miss cases. 5409 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5410 if (LI.replacementPreservesLCSSAForm(PN, V)) 5411 return getSCEV(V); 5412 5413 // If it's not a loop phi, we can't handle it yet. 5414 return getUnknown(PN); 5415 } 5416 5417 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5418 Value *Cond, 5419 Value *TrueVal, 5420 Value *FalseVal) { 5421 // Handle "constant" branch or select. This can occur for instance when a 5422 // loop pass transforms an inner loop and moves on to process the outer loop. 5423 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5424 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5425 5426 // Try to match some simple smax or umax patterns. 5427 auto *ICI = dyn_cast<ICmpInst>(Cond); 5428 if (!ICI) 5429 return getUnknown(I); 5430 5431 Value *LHS = ICI->getOperand(0); 5432 Value *RHS = ICI->getOperand(1); 5433 5434 switch (ICI->getPredicate()) { 5435 case ICmpInst::ICMP_SLT: 5436 case ICmpInst::ICMP_SLE: 5437 std::swap(LHS, RHS); 5438 LLVM_FALLTHROUGH; 5439 case ICmpInst::ICMP_SGT: 5440 case ICmpInst::ICMP_SGE: 5441 // a >s b ? a+x : b+x -> smax(a, b)+x 5442 // a >s b ? b+x : a+x -> smin(a, b)+x 5443 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5444 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5445 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5446 const SCEV *LA = getSCEV(TrueVal); 5447 const SCEV *RA = getSCEV(FalseVal); 5448 const SCEV *LDiff = getMinusSCEV(LA, LS); 5449 const SCEV *RDiff = getMinusSCEV(RA, RS); 5450 if (LDiff == RDiff) 5451 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5452 LDiff = getMinusSCEV(LA, RS); 5453 RDiff = getMinusSCEV(RA, LS); 5454 if (LDiff == RDiff) 5455 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5456 } 5457 break; 5458 case ICmpInst::ICMP_ULT: 5459 case ICmpInst::ICMP_ULE: 5460 std::swap(LHS, RHS); 5461 LLVM_FALLTHROUGH; 5462 case ICmpInst::ICMP_UGT: 5463 case ICmpInst::ICMP_UGE: 5464 // a >u b ? a+x : b+x -> umax(a, b)+x 5465 // a >u b ? b+x : a+x -> umin(a, b)+x 5466 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5467 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5468 const SCEV *RS = getNoopOrZeroExtend(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(getUMaxExpr(LS, RS), LDiff); 5475 LDiff = getMinusSCEV(LA, RS); 5476 RDiff = getMinusSCEV(RA, LS); 5477 if (LDiff == RDiff) 5478 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5479 } 5480 break; 5481 case ICmpInst::ICMP_NE: 5482 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5483 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5484 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5485 const SCEV *One = getOne(I->getType()); 5486 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5487 const SCEV *LA = getSCEV(TrueVal); 5488 const SCEV *RA = getSCEV(FalseVal); 5489 const SCEV *LDiff = getMinusSCEV(LA, LS); 5490 const SCEV *RDiff = getMinusSCEV(RA, One); 5491 if (LDiff == RDiff) 5492 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5493 } 5494 break; 5495 case ICmpInst::ICMP_EQ: 5496 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5497 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5498 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5499 const SCEV *One = getOne(I->getType()); 5500 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5501 const SCEV *LA = getSCEV(TrueVal); 5502 const SCEV *RA = getSCEV(FalseVal); 5503 const SCEV *LDiff = getMinusSCEV(LA, One); 5504 const SCEV *RDiff = getMinusSCEV(RA, LS); 5505 if (LDiff == RDiff) 5506 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5507 } 5508 break; 5509 default: 5510 break; 5511 } 5512 5513 return getUnknown(I); 5514 } 5515 5516 /// Expand GEP instructions into add and multiply operations. This allows them 5517 /// to be analyzed by regular SCEV code. 5518 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5519 // Don't attempt to analyze GEPs over unsized objects. 5520 if (!GEP->getSourceElementType()->isSized()) 5521 return getUnknown(GEP); 5522 5523 SmallVector<const SCEV *, 4> IndexExprs; 5524 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5525 IndexExprs.push_back(getSCEV(*Index)); 5526 return getGEPExpr(GEP, IndexExprs); 5527 } 5528 5529 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5530 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5531 return C->getAPInt().countTrailingZeros(); 5532 5533 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5534 return GetMinTrailingZeros(I->getOperand()); 5535 5536 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5537 return std::min(GetMinTrailingZeros(T->getOperand()), 5538 (uint32_t)getTypeSizeInBits(T->getType())); 5539 5540 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5541 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5542 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5543 ? getTypeSizeInBits(E->getType()) 5544 : OpRes; 5545 } 5546 5547 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5548 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5549 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5550 ? getTypeSizeInBits(E->getType()) 5551 : OpRes; 5552 } 5553 5554 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5555 // The result is the min of all operands results. 5556 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5557 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5558 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5559 return MinOpRes; 5560 } 5561 5562 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5563 // The result is the sum of all operands results. 5564 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5565 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5566 for (unsigned i = 1, e = M->getNumOperands(); 5567 SumOpRes != BitWidth && i != e; ++i) 5568 SumOpRes = 5569 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5570 return SumOpRes; 5571 } 5572 5573 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5574 // The result is the min of all operands results. 5575 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5576 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5577 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5578 return MinOpRes; 5579 } 5580 5581 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5582 // The result is the min of all operands results. 5583 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5584 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5585 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5586 return MinOpRes; 5587 } 5588 5589 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5590 // The result is the min of all operands results. 5591 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5592 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5593 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5594 return MinOpRes; 5595 } 5596 5597 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5598 // For a SCEVUnknown, ask ValueTracking. 5599 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5600 return Known.countMinTrailingZeros(); 5601 } 5602 5603 // SCEVUDivExpr 5604 return 0; 5605 } 5606 5607 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5608 auto I = MinTrailingZerosCache.find(S); 5609 if (I != MinTrailingZerosCache.end()) 5610 return I->second; 5611 5612 uint32_t Result = GetMinTrailingZerosImpl(S); 5613 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5614 assert(InsertPair.second && "Should insert a new key"); 5615 return InsertPair.first->second; 5616 } 5617 5618 /// Helper method to assign a range to V from metadata present in the IR. 5619 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5620 if (Instruction *I = dyn_cast<Instruction>(V)) 5621 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5622 return getConstantRangeFromMetadata(*MD); 5623 5624 return None; 5625 } 5626 5627 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 5628 SCEV::NoWrapFlags Flags) { 5629 if (AddRec->getNoWrapFlags(Flags) != Flags) { 5630 AddRec->setNoWrapFlags(Flags); 5631 UnsignedRanges.erase(AddRec); 5632 SignedRanges.erase(AddRec); 5633 } 5634 } 5635 5636 /// Determine the range for a particular SCEV. If SignHint is 5637 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5638 /// with a "cleaner" unsigned (resp. signed) representation. 5639 const ConstantRange & 5640 ScalarEvolution::getRangeRef(const SCEV *S, 5641 ScalarEvolution::RangeSignHint SignHint) { 5642 DenseMap<const SCEV *, ConstantRange> &Cache = 5643 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5644 : SignedRanges; 5645 ConstantRange::PreferredRangeType RangeType = 5646 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5647 ? ConstantRange::Unsigned : ConstantRange::Signed; 5648 5649 // See if we've computed this range already. 5650 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5651 if (I != Cache.end()) 5652 return I->second; 5653 5654 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5655 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5656 5657 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5658 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5659 using OBO = OverflowingBinaryOperator; 5660 5661 // If the value has known zeros, the maximum value will have those known zeros 5662 // as well. 5663 uint32_t TZ = GetMinTrailingZeros(S); 5664 if (TZ != 0) { 5665 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5666 ConservativeResult = 5667 ConstantRange(APInt::getMinValue(BitWidth), 5668 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5669 else 5670 ConservativeResult = ConstantRange( 5671 APInt::getSignedMinValue(BitWidth), 5672 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5673 } 5674 5675 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5676 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5677 unsigned WrapType = OBO::AnyWrap; 5678 if (Add->hasNoSignedWrap()) 5679 WrapType |= OBO::NoSignedWrap; 5680 if (Add->hasNoUnsignedWrap()) 5681 WrapType |= OBO::NoUnsignedWrap; 5682 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5683 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 5684 WrapType, RangeType); 5685 return setRange(Add, SignHint, 5686 ConservativeResult.intersectWith(X, RangeType)); 5687 } 5688 5689 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5690 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5691 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5692 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5693 return setRange(Mul, SignHint, 5694 ConservativeResult.intersectWith(X, RangeType)); 5695 } 5696 5697 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5698 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5699 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5700 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5701 return setRange(SMax, SignHint, 5702 ConservativeResult.intersectWith(X, RangeType)); 5703 } 5704 5705 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5706 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5707 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5708 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5709 return setRange(UMax, SignHint, 5710 ConservativeResult.intersectWith(X, RangeType)); 5711 } 5712 5713 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5714 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5715 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5716 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5717 return setRange(SMin, SignHint, 5718 ConservativeResult.intersectWith(X, RangeType)); 5719 } 5720 5721 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5722 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5723 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5724 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5725 return setRange(UMin, SignHint, 5726 ConservativeResult.intersectWith(X, RangeType)); 5727 } 5728 5729 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5730 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5731 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5732 return setRange(UDiv, SignHint, 5733 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5734 } 5735 5736 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5737 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5738 return setRange(ZExt, SignHint, 5739 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5740 RangeType)); 5741 } 5742 5743 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5744 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5745 return setRange(SExt, SignHint, 5746 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5747 RangeType)); 5748 } 5749 5750 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 5751 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 5752 return setRange(PtrToInt, SignHint, X); 5753 } 5754 5755 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5756 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5757 return setRange(Trunc, SignHint, 5758 ConservativeResult.intersectWith(X.truncate(BitWidth), 5759 RangeType)); 5760 } 5761 5762 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5763 // If there's no unsigned wrap, the value will never be less than its 5764 // initial value. 5765 if (AddRec->hasNoUnsignedWrap()) { 5766 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 5767 if (!UnsignedMinValue.isNullValue()) 5768 ConservativeResult = ConservativeResult.intersectWith( 5769 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 5770 } 5771 5772 // If there's no signed wrap, and all the operands except initial value have 5773 // the same sign or zero, the value won't ever be: 5774 // 1: smaller than initial value if operands are non negative, 5775 // 2: bigger than initial value if operands are non positive. 5776 // For both cases, value can not cross signed min/max boundary. 5777 if (AddRec->hasNoSignedWrap()) { 5778 bool AllNonNeg = true; 5779 bool AllNonPos = true; 5780 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 5781 if (!isKnownNonNegative(AddRec->getOperand(i))) 5782 AllNonNeg = false; 5783 if (!isKnownNonPositive(AddRec->getOperand(i))) 5784 AllNonPos = false; 5785 } 5786 if (AllNonNeg) 5787 ConservativeResult = ConservativeResult.intersectWith( 5788 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 5789 APInt::getSignedMinValue(BitWidth)), 5790 RangeType); 5791 else if (AllNonPos) 5792 ConservativeResult = ConservativeResult.intersectWith( 5793 ConstantRange::getNonEmpty( 5794 APInt::getSignedMinValue(BitWidth), 5795 getSignedRangeMax(AddRec->getStart()) + 1), 5796 RangeType); 5797 } 5798 5799 // TODO: non-affine addrec 5800 if (AddRec->isAffine()) { 5801 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5802 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5803 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5804 auto RangeFromAffine = getRangeForAffineAR( 5805 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5806 BitWidth); 5807 ConservativeResult = 5808 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5809 5810 auto RangeFromFactoring = getRangeViaFactoring( 5811 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5812 BitWidth); 5813 ConservativeResult = 5814 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5815 } 5816 5817 // Now try symbolic BE count and more powerful methods. 5818 if (UseExpensiveRangeSharpening) { 5819 const SCEV *SymbolicMaxBECount = 5820 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 5821 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 5822 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5823 AddRec->hasNoSelfWrap()) { 5824 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 5825 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 5826 ConservativeResult = 5827 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 5828 } 5829 } 5830 } 5831 5832 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5833 } 5834 5835 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5836 // Check if the IR explicitly contains !range metadata. 5837 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5838 if (MDRange.hasValue()) 5839 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5840 RangeType); 5841 5842 // Split here to avoid paying the compile-time cost of calling both 5843 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5844 // if needed. 5845 const DataLayout &DL = getDataLayout(); 5846 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5847 // For a SCEVUnknown, ask ValueTracking. 5848 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5849 if (Known.getBitWidth() != BitWidth) 5850 Known = Known.zextOrTrunc(BitWidth); 5851 // If Known does not result in full-set, intersect with it. 5852 if (Known.getMinValue() != Known.getMaxValue() + 1) 5853 ConservativeResult = ConservativeResult.intersectWith( 5854 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 5855 RangeType); 5856 } else { 5857 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5858 "generalize as needed!"); 5859 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5860 // If the pointer size is larger than the index size type, this can cause 5861 // NS to be larger than BitWidth. So compensate for this. 5862 if (U->getType()->isPointerTy()) { 5863 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 5864 int ptrIdxDiff = ptrSize - BitWidth; 5865 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 5866 NS -= ptrIdxDiff; 5867 } 5868 5869 if (NS > 1) 5870 ConservativeResult = ConservativeResult.intersectWith( 5871 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5872 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5873 RangeType); 5874 } 5875 5876 // A range of Phi is a subset of union of all ranges of its input. 5877 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5878 // Make sure that we do not run over cycled Phis. 5879 if (PendingPhiRanges.insert(Phi).second) { 5880 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5881 for (auto &Op : Phi->operands()) { 5882 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5883 RangeFromOps = RangeFromOps.unionWith(OpRange); 5884 // No point to continue if we already have a full set. 5885 if (RangeFromOps.isFullSet()) 5886 break; 5887 } 5888 ConservativeResult = 5889 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5890 bool Erased = PendingPhiRanges.erase(Phi); 5891 assert(Erased && "Failed to erase Phi properly?"); 5892 (void) Erased; 5893 } 5894 } 5895 5896 return setRange(U, SignHint, std::move(ConservativeResult)); 5897 } 5898 5899 return setRange(S, SignHint, std::move(ConservativeResult)); 5900 } 5901 5902 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5903 // values that the expression can take. Initially, the expression has a value 5904 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5905 // argument defines if we treat Step as signed or unsigned. 5906 static ConstantRange getRangeForAffineARHelper(APInt Step, 5907 const ConstantRange &StartRange, 5908 const APInt &MaxBECount, 5909 unsigned BitWidth, bool Signed) { 5910 // If either Step or MaxBECount is 0, then the expression won't change, and we 5911 // just need to return the initial range. 5912 if (Step == 0 || MaxBECount == 0) 5913 return StartRange; 5914 5915 // If we don't know anything about the initial value (i.e. StartRange is 5916 // FullRange), then we don't know anything about the final range either. 5917 // Return FullRange. 5918 if (StartRange.isFullSet()) 5919 return ConstantRange::getFull(BitWidth); 5920 5921 // If Step is signed and negative, then we use its absolute value, but we also 5922 // note that we're moving in the opposite direction. 5923 bool Descending = Signed && Step.isNegative(); 5924 5925 if (Signed) 5926 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5927 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5928 // This equations hold true due to the well-defined wrap-around behavior of 5929 // APInt. 5930 Step = Step.abs(); 5931 5932 // Check if Offset is more than full span of BitWidth. If it is, the 5933 // expression is guaranteed to overflow. 5934 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5935 return ConstantRange::getFull(BitWidth); 5936 5937 // Offset is by how much the expression can change. Checks above guarantee no 5938 // overflow here. 5939 APInt Offset = Step * MaxBECount; 5940 5941 // Minimum value of the final range will match the minimal value of StartRange 5942 // if the expression is increasing and will be decreased by Offset otherwise. 5943 // Maximum value of the final range will match the maximal value of StartRange 5944 // if the expression is decreasing and will be increased by Offset otherwise. 5945 APInt StartLower = StartRange.getLower(); 5946 APInt StartUpper = StartRange.getUpper() - 1; 5947 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5948 : (StartUpper + std::move(Offset)); 5949 5950 // It's possible that the new minimum/maximum value will fall into the initial 5951 // range (due to wrap around). This means that the expression can take any 5952 // value in this bitwidth, and we have to return full range. 5953 if (StartRange.contains(MovedBoundary)) 5954 return ConstantRange::getFull(BitWidth); 5955 5956 APInt NewLower = 5957 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5958 APInt NewUpper = 5959 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5960 NewUpper += 1; 5961 5962 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5963 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5964 } 5965 5966 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5967 const SCEV *Step, 5968 const SCEV *MaxBECount, 5969 unsigned BitWidth) { 5970 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5971 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5972 "Precondition!"); 5973 5974 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5975 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5976 5977 // First, consider step signed. 5978 ConstantRange StartSRange = getSignedRange(Start); 5979 ConstantRange StepSRange = getSignedRange(Step); 5980 5981 // If Step can be both positive and negative, we need to find ranges for the 5982 // maximum absolute step values in both directions and union them. 5983 ConstantRange SR = 5984 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5985 MaxBECountValue, BitWidth, /* Signed = */ true); 5986 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5987 StartSRange, MaxBECountValue, 5988 BitWidth, /* Signed = */ true)); 5989 5990 // Next, consider step unsigned. 5991 ConstantRange UR = getRangeForAffineARHelper( 5992 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5993 MaxBECountValue, BitWidth, /* Signed = */ false); 5994 5995 // Finally, intersect signed and unsigned ranges. 5996 return SR.intersectWith(UR, ConstantRange::Smallest); 5997 } 5998 5999 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6000 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6001 ScalarEvolution::RangeSignHint SignHint) { 6002 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6003 assert(AddRec->hasNoSelfWrap() && 6004 "This only works for non-self-wrapping AddRecs!"); 6005 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6006 const SCEV *Step = AddRec->getStepRecurrence(*this); 6007 // Only deal with constant step to save compile time. 6008 if (!isa<SCEVConstant>(Step)) 6009 return ConstantRange::getFull(BitWidth); 6010 // Let's make sure that we can prove that we do not self-wrap during 6011 // MaxBECount iterations. We need this because MaxBECount is a maximum 6012 // iteration count estimate, and we might infer nw from some exit for which we 6013 // do not know max exit count (or any other side reasoning). 6014 // TODO: Turn into assert at some point. 6015 if (getTypeSizeInBits(MaxBECount->getType()) > 6016 getTypeSizeInBits(AddRec->getType())) 6017 return ConstantRange::getFull(BitWidth); 6018 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6019 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6020 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6021 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6022 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6023 MaxItersWithoutWrap)) 6024 return ConstantRange::getFull(BitWidth); 6025 6026 ICmpInst::Predicate LEPred = 6027 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6028 ICmpInst::Predicate GEPred = 6029 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6030 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6031 6032 // We know that there is no self-wrap. Let's take Start and End values and 6033 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6034 // the iteration. They either lie inside the range [Min(Start, End), 6035 // Max(Start, End)] or outside it: 6036 // 6037 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6038 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6039 // 6040 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6041 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6042 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6043 // Start <= End and step is positive, or Start >= End and step is negative. 6044 const SCEV *Start = AddRec->getStart(); 6045 ConstantRange StartRange = getRangeRef(Start, SignHint); 6046 ConstantRange EndRange = getRangeRef(End, SignHint); 6047 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6048 // If they already cover full iteration space, we will know nothing useful 6049 // even if we prove what we want to prove. 6050 if (RangeBetween.isFullSet()) 6051 return RangeBetween; 6052 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6053 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6054 : RangeBetween.isWrappedSet(); 6055 if (IsWrappedSet) 6056 return ConstantRange::getFull(BitWidth); 6057 6058 if (isKnownPositive(Step) && 6059 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6060 return RangeBetween; 6061 else if (isKnownNegative(Step) && 6062 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6063 return RangeBetween; 6064 return ConstantRange::getFull(BitWidth); 6065 } 6066 6067 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6068 const SCEV *Step, 6069 const SCEV *MaxBECount, 6070 unsigned BitWidth) { 6071 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6072 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6073 6074 struct SelectPattern { 6075 Value *Condition = nullptr; 6076 APInt TrueValue; 6077 APInt FalseValue; 6078 6079 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6080 const SCEV *S) { 6081 Optional<unsigned> CastOp; 6082 APInt Offset(BitWidth, 0); 6083 6084 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6085 "Should be!"); 6086 6087 // Peel off a constant offset: 6088 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6089 // In the future we could consider being smarter here and handle 6090 // {Start+Step,+,Step} too. 6091 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6092 return; 6093 6094 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6095 S = SA->getOperand(1); 6096 } 6097 6098 // Peel off a cast operation 6099 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6100 CastOp = SCast->getSCEVType(); 6101 S = SCast->getOperand(); 6102 } 6103 6104 using namespace llvm::PatternMatch; 6105 6106 auto *SU = dyn_cast<SCEVUnknown>(S); 6107 const APInt *TrueVal, *FalseVal; 6108 if (!SU || 6109 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6110 m_APInt(FalseVal)))) { 6111 Condition = nullptr; 6112 return; 6113 } 6114 6115 TrueValue = *TrueVal; 6116 FalseValue = *FalseVal; 6117 6118 // Re-apply the cast we peeled off earlier 6119 if (CastOp.hasValue()) 6120 switch (*CastOp) { 6121 default: 6122 llvm_unreachable("Unknown SCEV cast type!"); 6123 6124 case scTruncate: 6125 TrueValue = TrueValue.trunc(BitWidth); 6126 FalseValue = FalseValue.trunc(BitWidth); 6127 break; 6128 case scZeroExtend: 6129 TrueValue = TrueValue.zext(BitWidth); 6130 FalseValue = FalseValue.zext(BitWidth); 6131 break; 6132 case scSignExtend: 6133 TrueValue = TrueValue.sext(BitWidth); 6134 FalseValue = FalseValue.sext(BitWidth); 6135 break; 6136 } 6137 6138 // Re-apply the constant offset we peeled off earlier 6139 TrueValue += Offset; 6140 FalseValue += Offset; 6141 } 6142 6143 bool isRecognized() { return Condition != nullptr; } 6144 }; 6145 6146 SelectPattern StartPattern(*this, BitWidth, Start); 6147 if (!StartPattern.isRecognized()) 6148 return ConstantRange::getFull(BitWidth); 6149 6150 SelectPattern StepPattern(*this, BitWidth, Step); 6151 if (!StepPattern.isRecognized()) 6152 return ConstantRange::getFull(BitWidth); 6153 6154 if (StartPattern.Condition != StepPattern.Condition) { 6155 // We don't handle this case today; but we could, by considering four 6156 // possibilities below instead of two. I'm not sure if there are cases where 6157 // that will help over what getRange already does, though. 6158 return ConstantRange::getFull(BitWidth); 6159 } 6160 6161 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6162 // construct arbitrary general SCEV expressions here. This function is called 6163 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6164 // say) can end up caching a suboptimal value. 6165 6166 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6167 // C2352 and C2512 (otherwise it isn't needed). 6168 6169 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6170 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6171 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6172 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6173 6174 ConstantRange TrueRange = 6175 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6176 ConstantRange FalseRange = 6177 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6178 6179 return TrueRange.unionWith(FalseRange); 6180 } 6181 6182 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6183 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6184 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6185 6186 // Return early if there are no flags to propagate to the SCEV. 6187 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6188 if (BinOp->hasNoUnsignedWrap()) 6189 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6190 if (BinOp->hasNoSignedWrap()) 6191 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6192 if (Flags == SCEV::FlagAnyWrap) 6193 return SCEV::FlagAnyWrap; 6194 6195 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6196 } 6197 6198 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6199 // Here we check that I is in the header of the innermost loop containing I, 6200 // since we only deal with instructions in the loop header. The actual loop we 6201 // need to check later will come from an add recurrence, but getting that 6202 // requires computing the SCEV of the operands, which can be expensive. This 6203 // check we can do cheaply to rule out some cases early. 6204 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6205 if (InnermostContainingLoop == nullptr || 6206 InnermostContainingLoop->getHeader() != I->getParent()) 6207 return false; 6208 6209 // Only proceed if we can prove that I does not yield poison. 6210 if (!programUndefinedIfPoison(I)) 6211 return false; 6212 6213 // At this point we know that if I is executed, then it does not wrap 6214 // according to at least one of NSW or NUW. If I is not executed, then we do 6215 // not know if the calculation that I represents would wrap. Multiple 6216 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6217 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6218 // derived from other instructions that map to the same SCEV. We cannot make 6219 // that guarantee for cases where I is not executed. So we need to find the 6220 // loop that I is considered in relation to and prove that I is executed for 6221 // every iteration of that loop. That implies that the value that I 6222 // calculates does not wrap anywhere in the loop, so then we can apply the 6223 // flags to the SCEV. 6224 // 6225 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6226 // from different loops, so that we know which loop to prove that I is 6227 // executed in. 6228 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6229 // I could be an extractvalue from a call to an overflow intrinsic. 6230 // TODO: We can do better here in some cases. 6231 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6232 return false; 6233 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6234 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6235 bool AllOtherOpsLoopInvariant = true; 6236 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6237 ++OtherOpIndex) { 6238 if (OtherOpIndex != OpIndex) { 6239 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6240 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6241 AllOtherOpsLoopInvariant = false; 6242 break; 6243 } 6244 } 6245 } 6246 if (AllOtherOpsLoopInvariant && 6247 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6248 return true; 6249 } 6250 } 6251 return false; 6252 } 6253 6254 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6255 // If we know that \c I can never be poison period, then that's enough. 6256 if (isSCEVExprNeverPoison(I)) 6257 return true; 6258 6259 // For an add recurrence specifically, we assume that infinite loops without 6260 // side effects are undefined behavior, and then reason as follows: 6261 // 6262 // If the add recurrence is poison in any iteration, it is poison on all 6263 // future iterations (since incrementing poison yields poison). If the result 6264 // of the add recurrence is fed into the loop latch condition and the loop 6265 // does not contain any throws or exiting blocks other than the latch, we now 6266 // have the ability to "choose" whether the backedge is taken or not (by 6267 // choosing a sufficiently evil value for the poison feeding into the branch) 6268 // for every iteration including and after the one in which \p I first became 6269 // poison. There are two possibilities (let's call the iteration in which \p 6270 // I first became poison as K): 6271 // 6272 // 1. In the set of iterations including and after K, the loop body executes 6273 // no side effects. In this case executing the backege an infinte number 6274 // of times will yield undefined behavior. 6275 // 6276 // 2. In the set of iterations including and after K, the loop body executes 6277 // at least one side effect. In this case, that specific instance of side 6278 // effect is control dependent on poison, which also yields undefined 6279 // behavior. 6280 6281 auto *ExitingBB = L->getExitingBlock(); 6282 auto *LatchBB = L->getLoopLatch(); 6283 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6284 return false; 6285 6286 SmallPtrSet<const Instruction *, 16> Pushed; 6287 SmallVector<const Instruction *, 8> PoisonStack; 6288 6289 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6290 // things that are known to be poison under that assumption go on the 6291 // PoisonStack. 6292 Pushed.insert(I); 6293 PoisonStack.push_back(I); 6294 6295 bool LatchControlDependentOnPoison = false; 6296 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6297 const Instruction *Poison = PoisonStack.pop_back_val(); 6298 6299 for (auto *PoisonUser : Poison->users()) { 6300 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6301 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6302 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6303 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6304 assert(BI->isConditional() && "Only possibility!"); 6305 if (BI->getParent() == LatchBB) { 6306 LatchControlDependentOnPoison = true; 6307 break; 6308 } 6309 } 6310 } 6311 } 6312 6313 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6314 } 6315 6316 ScalarEvolution::LoopProperties 6317 ScalarEvolution::getLoopProperties(const Loop *L) { 6318 using LoopProperties = ScalarEvolution::LoopProperties; 6319 6320 auto Itr = LoopPropertiesCache.find(L); 6321 if (Itr == LoopPropertiesCache.end()) { 6322 auto HasSideEffects = [](Instruction *I) { 6323 if (auto *SI = dyn_cast<StoreInst>(I)) 6324 return !SI->isSimple(); 6325 6326 return I->mayHaveSideEffects(); 6327 }; 6328 6329 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6330 /*HasNoSideEffects*/ true}; 6331 6332 for (auto *BB : L->getBlocks()) 6333 for (auto &I : *BB) { 6334 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6335 LP.HasNoAbnormalExits = false; 6336 if (HasSideEffects(&I)) 6337 LP.HasNoSideEffects = false; 6338 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6339 break; // We're already as pessimistic as we can get. 6340 } 6341 6342 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6343 assert(InsertPair.second && "We just checked!"); 6344 Itr = InsertPair.first; 6345 } 6346 6347 return Itr->second; 6348 } 6349 6350 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6351 if (!isSCEVable(V->getType())) 6352 return getUnknown(V); 6353 6354 if (Instruction *I = dyn_cast<Instruction>(V)) { 6355 // Don't attempt to analyze instructions in blocks that aren't 6356 // reachable. Such instructions don't matter, and they aren't required 6357 // to obey basic rules for definitions dominating uses which this 6358 // analysis depends on. 6359 if (!DT.isReachableFromEntry(I->getParent())) 6360 return getUnknown(UndefValue::get(V->getType())); 6361 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6362 return getConstant(CI); 6363 else if (isa<ConstantPointerNull>(V)) 6364 // FIXME: we shouldn't special-case null pointer constant. 6365 return getZero(V->getType()); 6366 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6367 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6368 else if (!isa<ConstantExpr>(V)) 6369 return getUnknown(V); 6370 6371 Operator *U = cast<Operator>(V); 6372 if (auto BO = MatchBinaryOp(U, DT)) { 6373 switch (BO->Opcode) { 6374 case Instruction::Add: { 6375 // The simple thing to do would be to just call getSCEV on both operands 6376 // and call getAddExpr with the result. However if we're looking at a 6377 // bunch of things all added together, this can be quite inefficient, 6378 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6379 // Instead, gather up all the operands and make a single getAddExpr call. 6380 // LLVM IR canonical form means we need only traverse the left operands. 6381 SmallVector<const SCEV *, 4> AddOps; 6382 do { 6383 if (BO->Op) { 6384 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6385 AddOps.push_back(OpSCEV); 6386 break; 6387 } 6388 6389 // If a NUW or NSW flag can be applied to the SCEV for this 6390 // addition, then compute the SCEV for this addition by itself 6391 // with a separate call to getAddExpr. We need to do that 6392 // instead of pushing the operands of the addition onto AddOps, 6393 // since the flags are only known to apply to this particular 6394 // addition - they may not apply to other additions that can be 6395 // formed with operands from AddOps. 6396 const SCEV *RHS = getSCEV(BO->RHS); 6397 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6398 if (Flags != SCEV::FlagAnyWrap) { 6399 const SCEV *LHS = getSCEV(BO->LHS); 6400 if (BO->Opcode == Instruction::Sub) 6401 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6402 else 6403 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6404 break; 6405 } 6406 } 6407 6408 if (BO->Opcode == Instruction::Sub) 6409 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6410 else 6411 AddOps.push_back(getSCEV(BO->RHS)); 6412 6413 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6414 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6415 NewBO->Opcode != Instruction::Sub)) { 6416 AddOps.push_back(getSCEV(BO->LHS)); 6417 break; 6418 } 6419 BO = NewBO; 6420 } while (true); 6421 6422 return getAddExpr(AddOps); 6423 } 6424 6425 case Instruction::Mul: { 6426 SmallVector<const SCEV *, 4> MulOps; 6427 do { 6428 if (BO->Op) { 6429 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6430 MulOps.push_back(OpSCEV); 6431 break; 6432 } 6433 6434 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6435 if (Flags != SCEV::FlagAnyWrap) { 6436 MulOps.push_back( 6437 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6438 break; 6439 } 6440 } 6441 6442 MulOps.push_back(getSCEV(BO->RHS)); 6443 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6444 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6445 MulOps.push_back(getSCEV(BO->LHS)); 6446 break; 6447 } 6448 BO = NewBO; 6449 } while (true); 6450 6451 return getMulExpr(MulOps); 6452 } 6453 case Instruction::UDiv: 6454 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6455 case Instruction::URem: 6456 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6457 case Instruction::Sub: { 6458 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6459 if (BO->Op) 6460 Flags = getNoWrapFlagsFromUB(BO->Op); 6461 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6462 } 6463 case Instruction::And: 6464 // For an expression like x&255 that merely masks off the high bits, 6465 // use zext(trunc(x)) as the SCEV expression. 6466 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6467 if (CI->isZero()) 6468 return getSCEV(BO->RHS); 6469 if (CI->isMinusOne()) 6470 return getSCEV(BO->LHS); 6471 const APInt &A = CI->getValue(); 6472 6473 // Instcombine's ShrinkDemandedConstant may strip bits out of 6474 // constants, obscuring what would otherwise be a low-bits mask. 6475 // Use computeKnownBits to compute what ShrinkDemandedConstant 6476 // knew about to reconstruct a low-bits mask value. 6477 unsigned LZ = A.countLeadingZeros(); 6478 unsigned TZ = A.countTrailingZeros(); 6479 unsigned BitWidth = A.getBitWidth(); 6480 KnownBits Known(BitWidth); 6481 computeKnownBits(BO->LHS, Known, getDataLayout(), 6482 0, &AC, nullptr, &DT); 6483 6484 APInt EffectiveMask = 6485 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6486 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6487 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6488 const SCEV *LHS = getSCEV(BO->LHS); 6489 const SCEV *ShiftedLHS = nullptr; 6490 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6491 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6492 // For an expression like (x * 8) & 8, simplify the multiply. 6493 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6494 unsigned GCD = std::min(MulZeros, TZ); 6495 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6496 SmallVector<const SCEV*, 4> MulOps; 6497 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6498 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6499 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6500 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6501 } 6502 } 6503 if (!ShiftedLHS) 6504 ShiftedLHS = getUDivExpr(LHS, MulCount); 6505 return getMulExpr( 6506 getZeroExtendExpr( 6507 getTruncateExpr(ShiftedLHS, 6508 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6509 BO->LHS->getType()), 6510 MulCount); 6511 } 6512 } 6513 break; 6514 6515 case Instruction::Or: 6516 // If the RHS of the Or is a constant, we may have something like: 6517 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6518 // optimizations will transparently handle this case. 6519 // 6520 // In order for this transformation to be safe, the LHS must be of the 6521 // form X*(2^n) and the Or constant must be less than 2^n. 6522 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6523 const SCEV *LHS = getSCEV(BO->LHS); 6524 const APInt &CIVal = CI->getValue(); 6525 if (GetMinTrailingZeros(LHS) >= 6526 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6527 // Build a plain add SCEV. 6528 return getAddExpr(LHS, getSCEV(CI), 6529 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6530 } 6531 } 6532 break; 6533 6534 case Instruction::Xor: 6535 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6536 // If the RHS of xor is -1, then this is a not operation. 6537 if (CI->isMinusOne()) 6538 return getNotSCEV(getSCEV(BO->LHS)); 6539 6540 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6541 // This is a variant of the check for xor with -1, and it handles 6542 // the case where instcombine has trimmed non-demanded bits out 6543 // of an xor with -1. 6544 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6545 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6546 if (LBO->getOpcode() == Instruction::And && 6547 LCI->getValue() == CI->getValue()) 6548 if (const SCEVZeroExtendExpr *Z = 6549 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6550 Type *UTy = BO->LHS->getType(); 6551 const SCEV *Z0 = Z->getOperand(); 6552 Type *Z0Ty = Z0->getType(); 6553 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6554 6555 // If C is a low-bits mask, the zero extend is serving to 6556 // mask off the high bits. Complement the operand and 6557 // re-apply the zext. 6558 if (CI->getValue().isMask(Z0TySize)) 6559 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6560 6561 // If C is a single bit, it may be in the sign-bit position 6562 // before the zero-extend. In this case, represent the xor 6563 // using an add, which is equivalent, and re-apply the zext. 6564 APInt Trunc = CI->getValue().trunc(Z0TySize); 6565 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6566 Trunc.isSignMask()) 6567 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6568 UTy); 6569 } 6570 } 6571 break; 6572 6573 case Instruction::Shl: 6574 // Turn shift left of a constant amount into a multiply. 6575 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6576 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6577 6578 // If the shift count is not less than the bitwidth, the result of 6579 // the shift is undefined. Don't try to analyze it, because the 6580 // resolution chosen here may differ from the resolution chosen in 6581 // other parts of the compiler. 6582 if (SA->getValue().uge(BitWidth)) 6583 break; 6584 6585 // We can safely preserve the nuw flag in all cases. It's also safe to 6586 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6587 // requires special handling. It can be preserved as long as we're not 6588 // left shifting by bitwidth - 1. 6589 auto Flags = SCEV::FlagAnyWrap; 6590 if (BO->Op) { 6591 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6592 if ((MulFlags & SCEV::FlagNSW) && 6593 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6594 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6595 if (MulFlags & SCEV::FlagNUW) 6596 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6597 } 6598 6599 Constant *X = ConstantInt::get( 6600 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6601 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6602 } 6603 break; 6604 6605 case Instruction::AShr: { 6606 // AShr X, C, where C is a constant. 6607 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6608 if (!CI) 6609 break; 6610 6611 Type *OuterTy = BO->LHS->getType(); 6612 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6613 // If the shift count is not less than the bitwidth, the result of 6614 // the shift is undefined. Don't try to analyze it, because the 6615 // resolution chosen here may differ from the resolution chosen in 6616 // other parts of the compiler. 6617 if (CI->getValue().uge(BitWidth)) 6618 break; 6619 6620 if (CI->isZero()) 6621 return getSCEV(BO->LHS); // shift by zero --> noop 6622 6623 uint64_t AShrAmt = CI->getZExtValue(); 6624 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6625 6626 Operator *L = dyn_cast<Operator>(BO->LHS); 6627 if (L && L->getOpcode() == Instruction::Shl) { 6628 // X = Shl A, n 6629 // Y = AShr X, m 6630 // Both n and m are constant. 6631 6632 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6633 if (L->getOperand(1) == BO->RHS) 6634 // For a two-shift sext-inreg, i.e. n = m, 6635 // use sext(trunc(x)) as the SCEV expression. 6636 return getSignExtendExpr( 6637 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6638 6639 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6640 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6641 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6642 if (ShlAmt > AShrAmt) { 6643 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6644 // expression. We already checked that ShlAmt < BitWidth, so 6645 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6646 // ShlAmt - AShrAmt < Amt. 6647 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6648 ShlAmt - AShrAmt); 6649 return getSignExtendExpr( 6650 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6651 getConstant(Mul)), OuterTy); 6652 } 6653 } 6654 } 6655 if (BO->IsExact) { 6656 // Given exact arithmetic in-bounds right-shift by a constant, 6657 // we can lower it into: (abs(x) EXACT/u (1<<C)) * signum(x) 6658 const SCEV *X = getSCEV(BO->LHS); 6659 const SCEV *AbsX = getAbsExpr(X, /*IsNSW=*/false); 6660 APInt Mult = APInt::getOneBitSet(BitWidth, AShrAmt); 6661 const SCEV *Div = getUDivExactExpr(AbsX, getConstant(Mult)); 6662 return getMulExpr(Div, getSignumExpr(X), SCEV::FlagNSW); 6663 } 6664 break; 6665 } 6666 } 6667 } 6668 6669 switch (U->getOpcode()) { 6670 case Instruction::Trunc: 6671 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6672 6673 case Instruction::ZExt: 6674 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6675 6676 case Instruction::SExt: 6677 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6678 // The NSW flag of a subtract does not always survive the conversion to 6679 // A + (-1)*B. By pushing sign extension onto its operands we are much 6680 // more likely to preserve NSW and allow later AddRec optimisations. 6681 // 6682 // NOTE: This is effectively duplicating this logic from getSignExtend: 6683 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6684 // but by that point the NSW information has potentially been lost. 6685 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6686 Type *Ty = U->getType(); 6687 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6688 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6689 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6690 } 6691 } 6692 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6693 6694 case Instruction::BitCast: 6695 // BitCasts are no-op casts so we just eliminate the cast. 6696 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6697 return getSCEV(U->getOperand(0)); 6698 break; 6699 6700 case Instruction::PtrToInt: { 6701 // Pointer to integer cast is straight-forward, so do model it. 6702 Value *Ptr = U->getOperand(0); 6703 const SCEV *Op = getSCEV(Ptr); 6704 Type *DstIntTy = U->getType(); 6705 // SCEV doesn't have constant pointer expression type, but it supports 6706 // nullptr constant (and only that one), which is modelled in SCEV as a 6707 // zero integer constant. So just skip the ptrtoint cast for constants. 6708 if (isa<SCEVConstant>(Op)) 6709 return getTruncateOrZeroExtend(Op, DstIntTy); 6710 Type *PtrTy = Ptr->getType(); 6711 Type *IntPtrTy = getDataLayout().getIntPtrType(PtrTy); 6712 // But only if effective SCEV (integer) type is wide enough to represent 6713 // all possible pointer values. 6714 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(PtrTy)) != 6715 getDataLayout().getTypeSizeInBits(IntPtrTy)) 6716 return getUnknown(V); 6717 return getPtrToIntExpr(Op, DstIntTy); 6718 } 6719 case Instruction::IntToPtr: 6720 // Just don't deal with inttoptr casts. 6721 return getUnknown(V); 6722 6723 case Instruction::SDiv: 6724 // If both operands are non-negative, this is just an udiv. 6725 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6726 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6727 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6728 break; 6729 6730 case Instruction::SRem: 6731 // If both operands are non-negative, this is just an urem. 6732 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6733 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6734 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6735 break; 6736 6737 case Instruction::GetElementPtr: 6738 return createNodeForGEP(cast<GEPOperator>(U)); 6739 6740 case Instruction::PHI: 6741 return createNodeForPHI(cast<PHINode>(U)); 6742 6743 case Instruction::Select: 6744 // U can also be a select constant expr, which let fall through. Since 6745 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6746 // constant expressions cannot have instructions as operands, we'd have 6747 // returned getUnknown for a select constant expressions anyway. 6748 if (isa<Instruction>(U)) 6749 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6750 U->getOperand(1), U->getOperand(2)); 6751 break; 6752 6753 case Instruction::Call: 6754 case Instruction::Invoke: 6755 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 6756 return getSCEV(RV); 6757 6758 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 6759 switch (II->getIntrinsicID()) { 6760 case Intrinsic::abs: 6761 return getAbsExpr( 6762 getSCEV(II->getArgOperand(0)), 6763 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 6764 case Intrinsic::umax: 6765 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 6766 getSCEV(II->getArgOperand(1))); 6767 case Intrinsic::umin: 6768 return getUMinExpr(getSCEV(II->getArgOperand(0)), 6769 getSCEV(II->getArgOperand(1))); 6770 case Intrinsic::smax: 6771 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 6772 getSCEV(II->getArgOperand(1))); 6773 case Intrinsic::smin: 6774 return getSMinExpr(getSCEV(II->getArgOperand(0)), 6775 getSCEV(II->getArgOperand(1))); 6776 case Intrinsic::usub_sat: { 6777 const SCEV *X = getSCEV(II->getArgOperand(0)); 6778 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6779 const SCEV *ClampedY = getUMinExpr(X, Y); 6780 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 6781 } 6782 case Intrinsic::uadd_sat: { 6783 const SCEV *X = getSCEV(II->getArgOperand(0)); 6784 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6785 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 6786 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 6787 } 6788 case Intrinsic::start_loop_iterations: 6789 // A start_loop_iterations is just equivalent to the first operand for 6790 // SCEV purposes. 6791 return getSCEV(II->getArgOperand(0)); 6792 default: 6793 break; 6794 } 6795 } 6796 break; 6797 } 6798 6799 return getUnknown(V); 6800 } 6801 6802 //===----------------------------------------------------------------------===// 6803 // Iteration Count Computation Code 6804 // 6805 6806 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6807 if (!ExitCount) 6808 return 0; 6809 6810 ConstantInt *ExitConst = ExitCount->getValue(); 6811 6812 // Guard against huge trip counts. 6813 if (ExitConst->getValue().getActiveBits() > 32) 6814 return 0; 6815 6816 // In case of integer overflow, this returns 0, which is correct. 6817 return ((unsigned)ExitConst->getZExtValue()) + 1; 6818 } 6819 6820 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6821 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6822 return getSmallConstantTripCount(L, ExitingBB); 6823 6824 // No trip count information for multiple exits. 6825 return 0; 6826 } 6827 6828 unsigned 6829 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6830 const BasicBlock *ExitingBlock) { 6831 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6832 assert(L->isLoopExiting(ExitingBlock) && 6833 "Exiting block must actually branch out of the loop!"); 6834 const SCEVConstant *ExitCount = 6835 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6836 return getConstantTripCount(ExitCount); 6837 } 6838 6839 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6840 const auto *MaxExitCount = 6841 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6842 return getConstantTripCount(MaxExitCount); 6843 } 6844 6845 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6846 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6847 return getSmallConstantTripMultiple(L, ExitingBB); 6848 6849 // No trip multiple information for multiple exits. 6850 return 0; 6851 } 6852 6853 /// Returns the largest constant divisor of the trip count of this loop as a 6854 /// normal unsigned value, if possible. This means that the actual trip count is 6855 /// always a multiple of the returned value (don't forget the trip count could 6856 /// very well be zero as well!). 6857 /// 6858 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6859 /// multiple of a constant (which is also the case if the trip count is simply 6860 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6861 /// if the trip count is very large (>= 2^32). 6862 /// 6863 /// As explained in the comments for getSmallConstantTripCount, this assumes 6864 /// that control exits the loop via ExitingBlock. 6865 unsigned 6866 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6867 const BasicBlock *ExitingBlock) { 6868 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6869 assert(L->isLoopExiting(ExitingBlock) && 6870 "Exiting block must actually branch out of the loop!"); 6871 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6872 if (ExitCount == getCouldNotCompute()) 6873 return 1; 6874 6875 // Get the trip count from the BE count by adding 1. 6876 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6877 6878 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6879 if (!TC) 6880 // Attempt to factor more general cases. Returns the greatest power of 6881 // two divisor. If overflow happens, the trip count expression is still 6882 // divisible by the greatest power of 2 divisor returned. 6883 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6884 6885 ConstantInt *Result = TC->getValue(); 6886 6887 // Guard against huge trip counts (this requires checking 6888 // for zero to handle the case where the trip count == -1 and the 6889 // addition wraps). 6890 if (!Result || Result->getValue().getActiveBits() > 32 || 6891 Result->getValue().getActiveBits() == 0) 6892 return 1; 6893 6894 return (unsigned)Result->getZExtValue(); 6895 } 6896 6897 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6898 const BasicBlock *ExitingBlock, 6899 ExitCountKind Kind) { 6900 switch (Kind) { 6901 case Exact: 6902 case SymbolicMaximum: 6903 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6904 case ConstantMaximum: 6905 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 6906 }; 6907 llvm_unreachable("Invalid ExitCountKind!"); 6908 } 6909 6910 const SCEV * 6911 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6912 SCEVUnionPredicate &Preds) { 6913 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6914 } 6915 6916 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 6917 ExitCountKind Kind) { 6918 switch (Kind) { 6919 case Exact: 6920 return getBackedgeTakenInfo(L).getExact(L, this); 6921 case ConstantMaximum: 6922 return getBackedgeTakenInfo(L).getConstantMax(this); 6923 case SymbolicMaximum: 6924 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 6925 }; 6926 llvm_unreachable("Invalid ExitCountKind!"); 6927 } 6928 6929 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6930 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 6931 } 6932 6933 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6934 static void 6935 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6936 BasicBlock *Header = L->getHeader(); 6937 6938 // Push all Loop-header PHIs onto the Worklist stack. 6939 for (PHINode &PN : Header->phis()) 6940 Worklist.push_back(&PN); 6941 } 6942 6943 const ScalarEvolution::BackedgeTakenInfo & 6944 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6945 auto &BTI = getBackedgeTakenInfo(L); 6946 if (BTI.hasFullInfo()) 6947 return BTI; 6948 6949 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6950 6951 if (!Pair.second) 6952 return Pair.first->second; 6953 6954 BackedgeTakenInfo Result = 6955 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6956 6957 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6958 } 6959 6960 ScalarEvolution::BackedgeTakenInfo & 6961 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6962 // Initially insert an invalid entry for this loop. If the insertion 6963 // succeeds, proceed to actually compute a backedge-taken count and 6964 // update the value. The temporary CouldNotCompute value tells SCEV 6965 // code elsewhere that it shouldn't attempt to request a new 6966 // backedge-taken count, which could result in infinite recursion. 6967 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6968 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6969 if (!Pair.second) 6970 return Pair.first->second; 6971 6972 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6973 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6974 // must be cleared in this scope. 6975 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6976 6977 // In product build, there are no usage of statistic. 6978 (void)NumTripCountsComputed; 6979 (void)NumTripCountsNotComputed; 6980 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6981 const SCEV *BEExact = Result.getExact(L, this); 6982 if (BEExact != getCouldNotCompute()) { 6983 assert(isLoopInvariant(BEExact, L) && 6984 isLoopInvariant(Result.getConstantMax(this), L) && 6985 "Computed backedge-taken count isn't loop invariant for loop!"); 6986 ++NumTripCountsComputed; 6987 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 6988 isa<PHINode>(L->getHeader()->begin())) { 6989 // Only count loops that have phi nodes as not being computable. 6990 ++NumTripCountsNotComputed; 6991 } 6992 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6993 6994 // Now that we know more about the trip count for this loop, forget any 6995 // existing SCEV values for PHI nodes in this loop since they are only 6996 // conservative estimates made without the benefit of trip count 6997 // information. This is similar to the code in forgetLoop, except that 6998 // it handles SCEVUnknown PHI nodes specially. 6999 if (Result.hasAnyInfo()) { 7000 SmallVector<Instruction *, 16> Worklist; 7001 PushLoopPHIs(L, Worklist); 7002 7003 SmallPtrSet<Instruction *, 8> Discovered; 7004 while (!Worklist.empty()) { 7005 Instruction *I = Worklist.pop_back_val(); 7006 7007 ValueExprMapType::iterator It = 7008 ValueExprMap.find_as(static_cast<Value *>(I)); 7009 if (It != ValueExprMap.end()) { 7010 const SCEV *Old = It->second; 7011 7012 // SCEVUnknown for a PHI either means that it has an unrecognized 7013 // structure, or it's a PHI that's in the progress of being computed 7014 // by createNodeForPHI. In the former case, additional loop trip 7015 // count information isn't going to change anything. In the later 7016 // case, createNodeForPHI will perform the necessary updates on its 7017 // own when it gets to that point. 7018 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 7019 eraseValueFromMap(It->first); 7020 forgetMemoizedResults(Old); 7021 } 7022 if (PHINode *PN = dyn_cast<PHINode>(I)) 7023 ConstantEvolutionLoopExitValue.erase(PN); 7024 } 7025 7026 // Since we don't need to invalidate anything for correctness and we're 7027 // only invalidating to make SCEV's results more precise, we get to stop 7028 // early to avoid invalidating too much. This is especially important in 7029 // cases like: 7030 // 7031 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 7032 // loop0: 7033 // %pn0 = phi 7034 // ... 7035 // loop1: 7036 // %pn1 = phi 7037 // ... 7038 // 7039 // where both loop0 and loop1's backedge taken count uses the SCEV 7040 // expression for %v. If we don't have the early stop below then in cases 7041 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 7042 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 7043 // count for loop1, effectively nullifying SCEV's trip count cache. 7044 for (auto *U : I->users()) 7045 if (auto *I = dyn_cast<Instruction>(U)) { 7046 auto *LoopForUser = LI.getLoopFor(I->getParent()); 7047 if (LoopForUser && L->contains(LoopForUser) && 7048 Discovered.insert(I).second) 7049 Worklist.push_back(I); 7050 } 7051 } 7052 } 7053 7054 // Re-lookup the insert position, since the call to 7055 // computeBackedgeTakenCount above could result in a 7056 // recusive call to getBackedgeTakenInfo (on a different 7057 // loop), which would invalidate the iterator computed 7058 // earlier. 7059 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7060 } 7061 7062 void ScalarEvolution::forgetAllLoops() { 7063 // This method is intended to forget all info about loops. It should 7064 // invalidate caches as if the following happened: 7065 // - The trip counts of all loops have changed arbitrarily 7066 // - Every llvm::Value has been updated in place to produce a different 7067 // result. 7068 BackedgeTakenCounts.clear(); 7069 PredicatedBackedgeTakenCounts.clear(); 7070 LoopPropertiesCache.clear(); 7071 ConstantEvolutionLoopExitValue.clear(); 7072 ValueExprMap.clear(); 7073 ValuesAtScopes.clear(); 7074 LoopDispositions.clear(); 7075 BlockDispositions.clear(); 7076 UnsignedRanges.clear(); 7077 SignedRanges.clear(); 7078 ExprValueMap.clear(); 7079 HasRecMap.clear(); 7080 MinTrailingZerosCache.clear(); 7081 PredicatedSCEVRewrites.clear(); 7082 } 7083 7084 void ScalarEvolution::forgetLoop(const Loop *L) { 7085 // Drop any stored trip count value. 7086 auto RemoveLoopFromBackedgeMap = 7087 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 7088 auto BTCPos = Map.find(L); 7089 if (BTCPos != Map.end()) { 7090 BTCPos->second.clear(); 7091 Map.erase(BTCPos); 7092 } 7093 }; 7094 7095 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7096 SmallVector<Instruction *, 32> Worklist; 7097 SmallPtrSet<Instruction *, 16> Visited; 7098 7099 // Iterate over all the loops and sub-loops to drop SCEV information. 7100 while (!LoopWorklist.empty()) { 7101 auto *CurrL = LoopWorklist.pop_back_val(); 7102 7103 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 7104 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 7105 7106 // Drop information about predicated SCEV rewrites for this loop. 7107 for (auto I = PredicatedSCEVRewrites.begin(); 7108 I != PredicatedSCEVRewrites.end();) { 7109 std::pair<const SCEV *, const Loop *> Entry = I->first; 7110 if (Entry.second == CurrL) 7111 PredicatedSCEVRewrites.erase(I++); 7112 else 7113 ++I; 7114 } 7115 7116 auto LoopUsersItr = LoopUsers.find(CurrL); 7117 if (LoopUsersItr != LoopUsers.end()) { 7118 for (auto *S : LoopUsersItr->second) 7119 forgetMemoizedResults(S); 7120 LoopUsers.erase(LoopUsersItr); 7121 } 7122 7123 // Drop information about expressions based on loop-header PHIs. 7124 PushLoopPHIs(CurrL, Worklist); 7125 7126 while (!Worklist.empty()) { 7127 Instruction *I = Worklist.pop_back_val(); 7128 if (!Visited.insert(I).second) 7129 continue; 7130 7131 ValueExprMapType::iterator It = 7132 ValueExprMap.find_as(static_cast<Value *>(I)); 7133 if (It != ValueExprMap.end()) { 7134 eraseValueFromMap(It->first); 7135 forgetMemoizedResults(It->second); 7136 if (PHINode *PN = dyn_cast<PHINode>(I)) 7137 ConstantEvolutionLoopExitValue.erase(PN); 7138 } 7139 7140 PushDefUseChildren(I, Worklist); 7141 } 7142 7143 LoopPropertiesCache.erase(CurrL); 7144 // Forget all contained loops too, to avoid dangling entries in the 7145 // ValuesAtScopes map. 7146 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7147 } 7148 } 7149 7150 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7151 while (Loop *Parent = L->getParentLoop()) 7152 L = Parent; 7153 forgetLoop(L); 7154 } 7155 7156 void ScalarEvolution::forgetValue(Value *V) { 7157 Instruction *I = dyn_cast<Instruction>(V); 7158 if (!I) return; 7159 7160 // Drop information about expressions based on loop-header PHIs. 7161 SmallVector<Instruction *, 16> Worklist; 7162 Worklist.push_back(I); 7163 7164 SmallPtrSet<Instruction *, 8> Visited; 7165 while (!Worklist.empty()) { 7166 I = Worklist.pop_back_val(); 7167 if (!Visited.insert(I).second) 7168 continue; 7169 7170 ValueExprMapType::iterator It = 7171 ValueExprMap.find_as(static_cast<Value *>(I)); 7172 if (It != ValueExprMap.end()) { 7173 eraseValueFromMap(It->first); 7174 forgetMemoizedResults(It->second); 7175 if (PHINode *PN = dyn_cast<PHINode>(I)) 7176 ConstantEvolutionLoopExitValue.erase(PN); 7177 } 7178 7179 PushDefUseChildren(I, Worklist); 7180 } 7181 } 7182 7183 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7184 LoopDispositions.clear(); 7185 } 7186 7187 /// Get the exact loop backedge taken count considering all loop exits. A 7188 /// computable result can only be returned for loops with all exiting blocks 7189 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7190 /// is never skipped. This is a valid assumption as long as the loop exits via 7191 /// that test. For precise results, it is the caller's responsibility to specify 7192 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7193 const SCEV * 7194 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7195 SCEVUnionPredicate *Preds) const { 7196 // If any exits were not computable, the loop is not computable. 7197 if (!isComplete() || ExitNotTaken.empty()) 7198 return SE->getCouldNotCompute(); 7199 7200 const BasicBlock *Latch = L->getLoopLatch(); 7201 // All exiting blocks we have collected must dominate the only backedge. 7202 if (!Latch) 7203 return SE->getCouldNotCompute(); 7204 7205 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7206 // count is simply a minimum out of all these calculated exit counts. 7207 SmallVector<const SCEV *, 2> Ops; 7208 for (auto &ENT : ExitNotTaken) { 7209 const SCEV *BECount = ENT.ExactNotTaken; 7210 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7211 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7212 "We should only have known counts for exiting blocks that dominate " 7213 "latch!"); 7214 7215 Ops.push_back(BECount); 7216 7217 if (Preds && !ENT.hasAlwaysTruePredicate()) 7218 Preds->add(ENT.Predicate.get()); 7219 7220 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7221 "Predicate should be always true!"); 7222 } 7223 7224 return SE->getUMinFromMismatchedTypes(Ops); 7225 } 7226 7227 /// Get the exact not taken count for this loop exit. 7228 const SCEV * 7229 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7230 ScalarEvolution *SE) const { 7231 for (auto &ENT : ExitNotTaken) 7232 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7233 return ENT.ExactNotTaken; 7234 7235 return SE->getCouldNotCompute(); 7236 } 7237 7238 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7239 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7240 for (auto &ENT : ExitNotTaken) 7241 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7242 return ENT.MaxNotTaken; 7243 7244 return SE->getCouldNotCompute(); 7245 } 7246 7247 /// getConstantMax - Get the constant max backedge taken count for the loop. 7248 const SCEV * 7249 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7250 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7251 return !ENT.hasAlwaysTruePredicate(); 7252 }; 7253 7254 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax()) 7255 return SE->getCouldNotCompute(); 7256 7257 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7258 isa<SCEVConstant>(getConstantMax())) && 7259 "No point in having a non-constant max backedge taken count!"); 7260 return getConstantMax(); 7261 } 7262 7263 const SCEV * 7264 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 7265 ScalarEvolution *SE) { 7266 if (!SymbolicMax) 7267 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 7268 return SymbolicMax; 7269 } 7270 7271 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 7272 ScalarEvolution *SE) const { 7273 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7274 return !ENT.hasAlwaysTruePredicate(); 7275 }; 7276 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7277 } 7278 7279 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 7280 ScalarEvolution *SE) const { 7281 if (getConstantMax() && getConstantMax() != SE->getCouldNotCompute() && 7282 SE->hasOperand(getConstantMax(), S)) 7283 return true; 7284 7285 for (auto &ENT : ExitNotTaken) 7286 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 7287 SE->hasOperand(ENT.ExactNotTaken, S)) 7288 return true; 7289 7290 return false; 7291 } 7292 7293 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7294 : ExactNotTaken(E), MaxNotTaken(E) { 7295 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7296 isa<SCEVConstant>(MaxNotTaken)) && 7297 "No point in having a non-constant max backedge taken count!"); 7298 } 7299 7300 ScalarEvolution::ExitLimit::ExitLimit( 7301 const SCEV *E, const SCEV *M, bool MaxOrZero, 7302 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7303 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7304 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7305 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7306 "Exact is not allowed to be less precise than Max"); 7307 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7308 isa<SCEVConstant>(MaxNotTaken)) && 7309 "No point in having a non-constant max backedge taken count!"); 7310 for (auto *PredSet : PredSetList) 7311 for (auto *P : *PredSet) 7312 addPredicate(P); 7313 } 7314 7315 ScalarEvolution::ExitLimit::ExitLimit( 7316 const SCEV *E, const SCEV *M, bool MaxOrZero, 7317 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7318 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7319 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7320 isa<SCEVConstant>(MaxNotTaken)) && 7321 "No point in having a non-constant max backedge taken count!"); 7322 } 7323 7324 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7325 bool MaxOrZero) 7326 : ExitLimit(E, M, MaxOrZero, None) { 7327 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7328 isa<SCEVConstant>(MaxNotTaken)) && 7329 "No point in having a non-constant max backedge taken count!"); 7330 } 7331 7332 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7333 /// computable exit into a persistent ExitNotTakenInfo array. 7334 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7335 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 7336 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 7337 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 7338 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7339 7340 ExitNotTaken.reserve(ExitCounts.size()); 7341 std::transform( 7342 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7343 [&](const EdgeExitInfo &EEI) { 7344 BasicBlock *ExitBB = EEI.first; 7345 const ExitLimit &EL = EEI.second; 7346 if (EL.Predicates.empty()) 7347 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7348 nullptr); 7349 7350 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7351 for (auto *Pred : EL.Predicates) 7352 Predicate->add(Pred); 7353 7354 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7355 std::move(Predicate)); 7356 }); 7357 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 7358 isa<SCEVConstant>(ConstantMax)) && 7359 "No point in having a non-constant max backedge taken count!"); 7360 } 7361 7362 /// Invalidate this result and free the ExitNotTakenInfo array. 7363 void ScalarEvolution::BackedgeTakenInfo::clear() { 7364 ExitNotTaken.clear(); 7365 } 7366 7367 /// Compute the number of times the backedge of the specified loop will execute. 7368 ScalarEvolution::BackedgeTakenInfo 7369 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7370 bool AllowPredicates) { 7371 SmallVector<BasicBlock *, 8> ExitingBlocks; 7372 L->getExitingBlocks(ExitingBlocks); 7373 7374 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7375 7376 SmallVector<EdgeExitInfo, 4> ExitCounts; 7377 bool CouldComputeBECount = true; 7378 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7379 const SCEV *MustExitMaxBECount = nullptr; 7380 const SCEV *MayExitMaxBECount = nullptr; 7381 bool MustExitMaxOrZero = false; 7382 7383 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7384 // and compute maxBECount. 7385 // Do a union of all the predicates here. 7386 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7387 BasicBlock *ExitBB = ExitingBlocks[i]; 7388 7389 // We canonicalize untaken exits to br (constant), ignore them so that 7390 // proving an exit untaken doesn't negatively impact our ability to reason 7391 // about the loop as whole. 7392 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7393 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7394 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7395 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7396 continue; 7397 } 7398 7399 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7400 7401 assert((AllowPredicates || EL.Predicates.empty()) && 7402 "Predicated exit limit when predicates are not allowed!"); 7403 7404 // 1. For each exit that can be computed, add an entry to ExitCounts. 7405 // CouldComputeBECount is true only if all exits can be computed. 7406 if (EL.ExactNotTaken == getCouldNotCompute()) 7407 // We couldn't compute an exact value for this exit, so 7408 // we won't be able to compute an exact value for the loop. 7409 CouldComputeBECount = false; 7410 else 7411 ExitCounts.emplace_back(ExitBB, EL); 7412 7413 // 2. Derive the loop's MaxBECount from each exit's max number of 7414 // non-exiting iterations. Partition the loop exits into two kinds: 7415 // LoopMustExits and LoopMayExits. 7416 // 7417 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7418 // is a LoopMayExit. If any computable LoopMustExit is found, then 7419 // MaxBECount is the minimum EL.MaxNotTaken of computable 7420 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7421 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7422 // computable EL.MaxNotTaken. 7423 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7424 DT.dominates(ExitBB, Latch)) { 7425 if (!MustExitMaxBECount) { 7426 MustExitMaxBECount = EL.MaxNotTaken; 7427 MustExitMaxOrZero = EL.MaxOrZero; 7428 } else { 7429 MustExitMaxBECount = 7430 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7431 } 7432 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7433 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7434 MayExitMaxBECount = EL.MaxNotTaken; 7435 else { 7436 MayExitMaxBECount = 7437 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7438 } 7439 } 7440 } 7441 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7442 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7443 // The loop backedge will be taken the maximum or zero times if there's 7444 // a single exit that must be taken the maximum or zero times. 7445 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7446 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7447 MaxBECount, MaxOrZero); 7448 } 7449 7450 ScalarEvolution::ExitLimit 7451 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7452 bool AllowPredicates) { 7453 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7454 // If our exiting block does not dominate the latch, then its connection with 7455 // loop's exit limit may be far from trivial. 7456 const BasicBlock *Latch = L->getLoopLatch(); 7457 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7458 return getCouldNotCompute(); 7459 7460 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7461 Instruction *Term = ExitingBlock->getTerminator(); 7462 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7463 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7464 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7465 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7466 "It should have one successor in loop and one exit block!"); 7467 // Proceed to the next level to examine the exit condition expression. 7468 return computeExitLimitFromCond( 7469 L, BI->getCondition(), ExitIfTrue, 7470 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7471 } 7472 7473 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7474 // For switch, make sure that there is a single exit from the loop. 7475 BasicBlock *Exit = nullptr; 7476 for (auto *SBB : successors(ExitingBlock)) 7477 if (!L->contains(SBB)) { 7478 if (Exit) // Multiple exit successors. 7479 return getCouldNotCompute(); 7480 Exit = SBB; 7481 } 7482 assert(Exit && "Exiting block must have at least one exit"); 7483 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7484 /*ControlsExit=*/IsOnlyExit); 7485 } 7486 7487 return getCouldNotCompute(); 7488 } 7489 7490 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7491 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7492 bool ControlsExit, bool AllowPredicates) { 7493 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7494 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7495 ControlsExit, AllowPredicates); 7496 } 7497 7498 Optional<ScalarEvolution::ExitLimit> 7499 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7500 bool ExitIfTrue, bool ControlsExit, 7501 bool AllowPredicates) { 7502 (void)this->L; 7503 (void)this->ExitIfTrue; 7504 (void)this->AllowPredicates; 7505 7506 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7507 this->AllowPredicates == AllowPredicates && 7508 "Variance in assumed invariant key components!"); 7509 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7510 if (Itr == TripCountMap.end()) 7511 return None; 7512 return Itr->second; 7513 } 7514 7515 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7516 bool ExitIfTrue, 7517 bool ControlsExit, 7518 bool AllowPredicates, 7519 const ExitLimit &EL) { 7520 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7521 this->AllowPredicates == AllowPredicates && 7522 "Variance in assumed invariant key components!"); 7523 7524 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7525 assert(InsertResult.second && "Expected successful insertion!"); 7526 (void)InsertResult; 7527 (void)ExitIfTrue; 7528 } 7529 7530 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7531 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7532 bool ControlsExit, bool AllowPredicates) { 7533 7534 if (auto MaybeEL = 7535 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7536 return *MaybeEL; 7537 7538 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7539 ControlsExit, AllowPredicates); 7540 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7541 return EL; 7542 } 7543 7544 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7545 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7546 bool ControlsExit, bool AllowPredicates) { 7547 // Handle BinOp conditions (And, Or). 7548 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 7549 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7550 return *LimitFromBinOp; 7551 7552 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7553 // Proceed to the next level to examine the icmp. 7554 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7555 ExitLimit EL = 7556 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7557 if (EL.hasFullInfo() || !AllowPredicates) 7558 return EL; 7559 7560 // Try again, but use SCEV predicates this time. 7561 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7562 /*AllowPredicates=*/true); 7563 } 7564 7565 // Check for a constant condition. These are normally stripped out by 7566 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7567 // preserve the CFG and is temporarily leaving constant conditions 7568 // in place. 7569 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7570 if (ExitIfTrue == !CI->getZExtValue()) 7571 // The backedge is always taken. 7572 return getCouldNotCompute(); 7573 else 7574 // The backedge is never taken. 7575 return getZero(CI->getType()); 7576 } 7577 7578 // If it's not an integer or pointer comparison then compute it the hard way. 7579 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7580 } 7581 7582 Optional<ScalarEvolution::ExitLimit> 7583 ScalarEvolution::computeExitLimitFromCondFromBinOp( 7584 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7585 bool ControlsExit, bool AllowPredicates) { 7586 // Check if the controlling expression for this loop is an And or Or. 7587 Value *Op0, *Op1; 7588 bool IsAnd = false; 7589 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 7590 IsAnd = true; 7591 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 7592 IsAnd = false; 7593 else 7594 return None; 7595 7596 // EitherMayExit is true in these two cases: 7597 // br (and Op0 Op1), loop, exit 7598 // br (or Op0 Op1), exit, loop 7599 bool EitherMayExit = IsAnd ^ ExitIfTrue; 7600 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 7601 ControlsExit && !EitherMayExit, 7602 AllowPredicates); 7603 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 7604 ControlsExit && !EitherMayExit, 7605 AllowPredicates); 7606 7607 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 7608 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 7609 if (isa<ConstantInt>(Op1)) 7610 return Op1 == NeutralElement ? EL0 : EL1; 7611 if (isa<ConstantInt>(Op0)) 7612 return Op0 == NeutralElement ? EL1 : EL0; 7613 7614 const SCEV *BECount = getCouldNotCompute(); 7615 const SCEV *MaxBECount = getCouldNotCompute(); 7616 if (EitherMayExit) { 7617 // Both conditions must be same for the loop to continue executing. 7618 // Choose the less conservative count. 7619 // If ExitCond is a short-circuit form (select), using 7620 // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general. 7621 // To see the detailed examples, please see 7622 // test/Analysis/ScalarEvolution/exit-count-select.ll 7623 bool PoisonSafe = isa<BinaryOperator>(ExitCond); 7624 if (!PoisonSafe) 7625 // Even if ExitCond is select, we can safely derive BECount using both 7626 // EL0 and EL1 in these cases: 7627 // (1) EL0.ExactNotTaken is non-zero 7628 // (2) EL1.ExactNotTaken is non-poison 7629 // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and 7630 // it cannot be umin(0, ..)) 7631 // The PoisonSafe assignment below is simplified and the assertion after 7632 // BECount calculation fully guarantees the condition (3). 7633 PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) || 7634 isa<SCEVConstant>(EL1.ExactNotTaken); 7635 if (EL0.ExactNotTaken != getCouldNotCompute() && 7636 EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) { 7637 BECount = 7638 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7639 7640 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 7641 // it should have been simplified to zero (see the condition (3) above) 7642 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 7643 BECount->isZero()); 7644 } 7645 if (EL0.MaxNotTaken == getCouldNotCompute()) 7646 MaxBECount = EL1.MaxNotTaken; 7647 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7648 MaxBECount = EL0.MaxNotTaken; 7649 else 7650 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7651 } else { 7652 // Both conditions must be same at the same time for the loop to exit. 7653 // For now, be conservative. 7654 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7655 BECount = EL0.ExactNotTaken; 7656 } 7657 7658 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7659 // to be more aggressive when computing BECount than when computing 7660 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7661 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7662 // to not. 7663 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7664 !isa<SCEVCouldNotCompute>(BECount)) 7665 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7666 7667 return ExitLimit(BECount, MaxBECount, false, 7668 { &EL0.Predicates, &EL1.Predicates }); 7669 } 7670 7671 ScalarEvolution::ExitLimit 7672 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7673 ICmpInst *ExitCond, 7674 bool ExitIfTrue, 7675 bool ControlsExit, 7676 bool AllowPredicates) { 7677 // If the condition was exit on true, convert the condition to exit on false 7678 ICmpInst::Predicate Pred; 7679 if (!ExitIfTrue) 7680 Pred = ExitCond->getPredicate(); 7681 else 7682 Pred = ExitCond->getInversePredicate(); 7683 const ICmpInst::Predicate OriginalPred = Pred; 7684 7685 // Handle common loops like: for (X = "string"; *X; ++X) 7686 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7687 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7688 ExitLimit ItCnt = 7689 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7690 if (ItCnt.hasAnyInfo()) 7691 return ItCnt; 7692 } 7693 7694 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7695 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7696 7697 // Try to evaluate any dependencies out of the loop. 7698 LHS = getSCEVAtScope(LHS, L); 7699 RHS = getSCEVAtScope(RHS, L); 7700 7701 // At this point, we would like to compute how many iterations of the 7702 // loop the predicate will return true for these inputs. 7703 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7704 // If there is a loop-invariant, force it into the RHS. 7705 std::swap(LHS, RHS); 7706 Pred = ICmpInst::getSwappedPredicate(Pred); 7707 } 7708 7709 // Simplify the operands before analyzing them. 7710 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7711 7712 // If we have a comparison of a chrec against a constant, try to use value 7713 // ranges to answer this query. 7714 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7715 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7716 if (AddRec->getLoop() == L) { 7717 // Form the constant range. 7718 ConstantRange CompRange = 7719 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7720 7721 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7722 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7723 } 7724 7725 switch (Pred) { 7726 case ICmpInst::ICMP_NE: { // while (X != Y) 7727 // Convert to: while (X-Y != 0) 7728 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7729 AllowPredicates); 7730 if (EL.hasAnyInfo()) return EL; 7731 break; 7732 } 7733 case ICmpInst::ICMP_EQ: { // while (X == Y) 7734 // Convert to: while (X-Y == 0) 7735 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7736 if (EL.hasAnyInfo()) return EL; 7737 break; 7738 } 7739 case ICmpInst::ICMP_SLT: 7740 case ICmpInst::ICMP_ULT: { // while (X < Y) 7741 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7742 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7743 AllowPredicates); 7744 if (EL.hasAnyInfo()) return EL; 7745 break; 7746 } 7747 case ICmpInst::ICMP_SGT: 7748 case ICmpInst::ICMP_UGT: { // while (X > Y) 7749 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7750 ExitLimit EL = 7751 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7752 AllowPredicates); 7753 if (EL.hasAnyInfo()) return EL; 7754 break; 7755 } 7756 default: 7757 break; 7758 } 7759 7760 auto *ExhaustiveCount = 7761 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7762 7763 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7764 return ExhaustiveCount; 7765 7766 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7767 ExitCond->getOperand(1), L, OriginalPred); 7768 } 7769 7770 ScalarEvolution::ExitLimit 7771 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7772 SwitchInst *Switch, 7773 BasicBlock *ExitingBlock, 7774 bool ControlsExit) { 7775 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7776 7777 // Give up if the exit is the default dest of a switch. 7778 if (Switch->getDefaultDest() == ExitingBlock) 7779 return getCouldNotCompute(); 7780 7781 assert(L->contains(Switch->getDefaultDest()) && 7782 "Default case must not exit the loop!"); 7783 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7784 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7785 7786 // while (X != Y) --> while (X-Y != 0) 7787 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7788 if (EL.hasAnyInfo()) 7789 return EL; 7790 7791 return getCouldNotCompute(); 7792 } 7793 7794 static ConstantInt * 7795 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7796 ScalarEvolution &SE) { 7797 const SCEV *InVal = SE.getConstant(C); 7798 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7799 assert(isa<SCEVConstant>(Val) && 7800 "Evaluation of SCEV at constant didn't fold correctly?"); 7801 return cast<SCEVConstant>(Val)->getValue(); 7802 } 7803 7804 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7805 /// compute the backedge execution count. 7806 ScalarEvolution::ExitLimit 7807 ScalarEvolution::computeLoadConstantCompareExitLimit( 7808 LoadInst *LI, 7809 Constant *RHS, 7810 const Loop *L, 7811 ICmpInst::Predicate predicate) { 7812 if (LI->isVolatile()) return getCouldNotCompute(); 7813 7814 // Check to see if the loaded pointer is a getelementptr of a global. 7815 // TODO: Use SCEV instead of manually grubbing with GEPs. 7816 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7817 if (!GEP) return getCouldNotCompute(); 7818 7819 // Make sure that it is really a constant global we are gepping, with an 7820 // initializer, and make sure the first IDX is really 0. 7821 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7822 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7823 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7824 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7825 return getCouldNotCompute(); 7826 7827 // Okay, we allow one non-constant index into the GEP instruction. 7828 Value *VarIdx = nullptr; 7829 std::vector<Constant*> Indexes; 7830 unsigned VarIdxNum = 0; 7831 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7832 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7833 Indexes.push_back(CI); 7834 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7835 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7836 VarIdx = GEP->getOperand(i); 7837 VarIdxNum = i-2; 7838 Indexes.push_back(nullptr); 7839 } 7840 7841 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7842 if (!VarIdx) 7843 return getCouldNotCompute(); 7844 7845 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7846 // Check to see if X is a loop variant variable value now. 7847 const SCEV *Idx = getSCEV(VarIdx); 7848 Idx = getSCEVAtScope(Idx, L); 7849 7850 // We can only recognize very limited forms of loop index expressions, in 7851 // particular, only affine AddRec's like {C1,+,C2}. 7852 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7853 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7854 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7855 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7856 return getCouldNotCompute(); 7857 7858 unsigned MaxSteps = MaxBruteForceIterations; 7859 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7860 ConstantInt *ItCst = ConstantInt::get( 7861 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7862 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7863 7864 // Form the GEP offset. 7865 Indexes[VarIdxNum] = Val; 7866 7867 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7868 Indexes); 7869 if (!Result) break; // Cannot compute! 7870 7871 // Evaluate the condition for this iteration. 7872 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7873 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7874 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7875 ++NumArrayLenItCounts; 7876 return getConstant(ItCst); // Found terminating iteration! 7877 } 7878 } 7879 return getCouldNotCompute(); 7880 } 7881 7882 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7883 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7884 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7885 if (!RHS) 7886 return getCouldNotCompute(); 7887 7888 const BasicBlock *Latch = L->getLoopLatch(); 7889 if (!Latch) 7890 return getCouldNotCompute(); 7891 7892 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7893 if (!Predecessor) 7894 return getCouldNotCompute(); 7895 7896 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7897 // Return LHS in OutLHS and shift_opt in OutOpCode. 7898 auto MatchPositiveShift = 7899 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7900 7901 using namespace PatternMatch; 7902 7903 ConstantInt *ShiftAmt; 7904 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7905 OutOpCode = Instruction::LShr; 7906 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7907 OutOpCode = Instruction::AShr; 7908 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7909 OutOpCode = Instruction::Shl; 7910 else 7911 return false; 7912 7913 return ShiftAmt->getValue().isStrictlyPositive(); 7914 }; 7915 7916 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7917 // 7918 // loop: 7919 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7920 // %iv.shifted = lshr i32 %iv, <positive constant> 7921 // 7922 // Return true on a successful match. Return the corresponding PHI node (%iv 7923 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7924 auto MatchShiftRecurrence = 7925 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7926 Optional<Instruction::BinaryOps> PostShiftOpCode; 7927 7928 { 7929 Instruction::BinaryOps OpC; 7930 Value *V; 7931 7932 // If we encounter a shift instruction, "peel off" the shift operation, 7933 // and remember that we did so. Later when we inspect %iv's backedge 7934 // value, we will make sure that the backedge value uses the same 7935 // operation. 7936 // 7937 // Note: the peeled shift operation does not have to be the same 7938 // instruction as the one feeding into the PHI's backedge value. We only 7939 // really care about it being the same *kind* of shift instruction -- 7940 // that's all that is required for our later inferences to hold. 7941 if (MatchPositiveShift(LHS, V, OpC)) { 7942 PostShiftOpCode = OpC; 7943 LHS = V; 7944 } 7945 } 7946 7947 PNOut = dyn_cast<PHINode>(LHS); 7948 if (!PNOut || PNOut->getParent() != L->getHeader()) 7949 return false; 7950 7951 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7952 Value *OpLHS; 7953 7954 return 7955 // The backedge value for the PHI node must be a shift by a positive 7956 // amount 7957 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7958 7959 // of the PHI node itself 7960 OpLHS == PNOut && 7961 7962 // and the kind of shift should be match the kind of shift we peeled 7963 // off, if any. 7964 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7965 }; 7966 7967 PHINode *PN; 7968 Instruction::BinaryOps OpCode; 7969 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7970 return getCouldNotCompute(); 7971 7972 const DataLayout &DL = getDataLayout(); 7973 7974 // The key rationale for this optimization is that for some kinds of shift 7975 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7976 // within a finite number of iterations. If the condition guarding the 7977 // backedge (in the sense that the backedge is taken if the condition is true) 7978 // is false for the value the shift recurrence stabilizes to, then we know 7979 // that the backedge is taken only a finite number of times. 7980 7981 ConstantInt *StableValue = nullptr; 7982 switch (OpCode) { 7983 default: 7984 llvm_unreachable("Impossible case!"); 7985 7986 case Instruction::AShr: { 7987 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7988 // bitwidth(K) iterations. 7989 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7990 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7991 Predecessor->getTerminator(), &DT); 7992 auto *Ty = cast<IntegerType>(RHS->getType()); 7993 if (Known.isNonNegative()) 7994 StableValue = ConstantInt::get(Ty, 0); 7995 else if (Known.isNegative()) 7996 StableValue = ConstantInt::get(Ty, -1, true); 7997 else 7998 return getCouldNotCompute(); 7999 8000 break; 8001 } 8002 case Instruction::LShr: 8003 case Instruction::Shl: 8004 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8005 // stabilize to 0 in at most bitwidth(K) iterations. 8006 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8007 break; 8008 } 8009 8010 auto *Result = 8011 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8012 assert(Result->getType()->isIntegerTy(1) && 8013 "Otherwise cannot be an operand to a branch instruction"); 8014 8015 if (Result->isZeroValue()) { 8016 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8017 const SCEV *UpperBound = 8018 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8019 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8020 } 8021 8022 return getCouldNotCompute(); 8023 } 8024 8025 /// Return true if we can constant fold an instruction of the specified type, 8026 /// assuming that all operands were constants. 8027 static bool CanConstantFold(const Instruction *I) { 8028 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8029 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8030 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8031 return true; 8032 8033 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8034 if (const Function *F = CI->getCalledFunction()) 8035 return canConstantFoldCallTo(CI, F); 8036 return false; 8037 } 8038 8039 /// Determine whether this instruction can constant evolve within this loop 8040 /// assuming its operands can all constant evolve. 8041 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8042 // An instruction outside of the loop can't be derived from a loop PHI. 8043 if (!L->contains(I)) return false; 8044 8045 if (isa<PHINode>(I)) { 8046 // We don't currently keep track of the control flow needed to evaluate 8047 // PHIs, so we cannot handle PHIs inside of loops. 8048 return L->getHeader() == I->getParent(); 8049 } 8050 8051 // If we won't be able to constant fold this expression even if the operands 8052 // are constants, bail early. 8053 return CanConstantFold(I); 8054 } 8055 8056 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8057 /// recursing through each instruction operand until reaching a loop header phi. 8058 static PHINode * 8059 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8060 DenseMap<Instruction *, PHINode *> &PHIMap, 8061 unsigned Depth) { 8062 if (Depth > MaxConstantEvolvingDepth) 8063 return nullptr; 8064 8065 // Otherwise, we can evaluate this instruction if all of its operands are 8066 // constant or derived from a PHI node themselves. 8067 PHINode *PHI = nullptr; 8068 for (Value *Op : UseInst->operands()) { 8069 if (isa<Constant>(Op)) continue; 8070 8071 Instruction *OpInst = dyn_cast<Instruction>(Op); 8072 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8073 8074 PHINode *P = dyn_cast<PHINode>(OpInst); 8075 if (!P) 8076 // If this operand is already visited, reuse the prior result. 8077 // We may have P != PHI if this is the deepest point at which the 8078 // inconsistent paths meet. 8079 P = PHIMap.lookup(OpInst); 8080 if (!P) { 8081 // Recurse and memoize the results, whether a phi is found or not. 8082 // This recursive call invalidates pointers into PHIMap. 8083 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8084 PHIMap[OpInst] = P; 8085 } 8086 if (!P) 8087 return nullptr; // Not evolving from PHI 8088 if (PHI && PHI != P) 8089 return nullptr; // Evolving from multiple different PHIs. 8090 PHI = P; 8091 } 8092 // This is a expression evolving from a constant PHI! 8093 return PHI; 8094 } 8095 8096 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8097 /// in the loop that V is derived from. We allow arbitrary operations along the 8098 /// way, but the operands of an operation must either be constants or a value 8099 /// derived from a constant PHI. If this expression does not fit with these 8100 /// constraints, return null. 8101 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8102 Instruction *I = dyn_cast<Instruction>(V); 8103 if (!I || !canConstantEvolve(I, L)) return nullptr; 8104 8105 if (PHINode *PN = dyn_cast<PHINode>(I)) 8106 return PN; 8107 8108 // Record non-constant instructions contained by the loop. 8109 DenseMap<Instruction *, PHINode *> PHIMap; 8110 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8111 } 8112 8113 /// EvaluateExpression - Given an expression that passes the 8114 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8115 /// in the loop has the value PHIVal. If we can't fold this expression for some 8116 /// reason, return null. 8117 static Constant *EvaluateExpression(Value *V, const Loop *L, 8118 DenseMap<Instruction *, Constant *> &Vals, 8119 const DataLayout &DL, 8120 const TargetLibraryInfo *TLI) { 8121 // Convenient constant check, but redundant for recursive calls. 8122 if (Constant *C = dyn_cast<Constant>(V)) return C; 8123 Instruction *I = dyn_cast<Instruction>(V); 8124 if (!I) return nullptr; 8125 8126 if (Constant *C = Vals.lookup(I)) return C; 8127 8128 // An instruction inside the loop depends on a value outside the loop that we 8129 // weren't given a mapping for, or a value such as a call inside the loop. 8130 if (!canConstantEvolve(I, L)) return nullptr; 8131 8132 // An unmapped PHI can be due to a branch or another loop inside this loop, 8133 // or due to this not being the initial iteration through a loop where we 8134 // couldn't compute the evolution of this particular PHI last time. 8135 if (isa<PHINode>(I)) return nullptr; 8136 8137 std::vector<Constant*> Operands(I->getNumOperands()); 8138 8139 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8140 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8141 if (!Operand) { 8142 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8143 if (!Operands[i]) return nullptr; 8144 continue; 8145 } 8146 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8147 Vals[Operand] = C; 8148 if (!C) return nullptr; 8149 Operands[i] = C; 8150 } 8151 8152 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8153 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8154 Operands[1], DL, TLI); 8155 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8156 if (!LI->isVolatile()) 8157 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8158 } 8159 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8160 } 8161 8162 8163 // If every incoming value to PN except the one for BB is a specific Constant, 8164 // return that, else return nullptr. 8165 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8166 Constant *IncomingVal = nullptr; 8167 8168 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8169 if (PN->getIncomingBlock(i) == BB) 8170 continue; 8171 8172 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8173 if (!CurrentVal) 8174 return nullptr; 8175 8176 if (IncomingVal != CurrentVal) { 8177 if (IncomingVal) 8178 return nullptr; 8179 IncomingVal = CurrentVal; 8180 } 8181 } 8182 8183 return IncomingVal; 8184 } 8185 8186 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8187 /// in the header of its containing loop, we know the loop executes a 8188 /// constant number of times, and the PHI node is just a recurrence 8189 /// involving constants, fold it. 8190 Constant * 8191 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8192 const APInt &BEs, 8193 const Loop *L) { 8194 auto I = ConstantEvolutionLoopExitValue.find(PN); 8195 if (I != ConstantEvolutionLoopExitValue.end()) 8196 return I->second; 8197 8198 if (BEs.ugt(MaxBruteForceIterations)) 8199 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8200 8201 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8202 8203 DenseMap<Instruction *, Constant *> CurrentIterVals; 8204 BasicBlock *Header = L->getHeader(); 8205 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8206 8207 BasicBlock *Latch = L->getLoopLatch(); 8208 if (!Latch) 8209 return nullptr; 8210 8211 for (PHINode &PHI : Header->phis()) { 8212 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8213 CurrentIterVals[&PHI] = StartCST; 8214 } 8215 if (!CurrentIterVals.count(PN)) 8216 return RetVal = nullptr; 8217 8218 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8219 8220 // Execute the loop symbolically to determine the exit value. 8221 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8222 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8223 8224 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8225 unsigned IterationNum = 0; 8226 const DataLayout &DL = getDataLayout(); 8227 for (; ; ++IterationNum) { 8228 if (IterationNum == NumIterations) 8229 return RetVal = CurrentIterVals[PN]; // Got exit value! 8230 8231 // Compute the value of the PHIs for the next iteration. 8232 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8233 DenseMap<Instruction *, Constant *> NextIterVals; 8234 Constant *NextPHI = 8235 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8236 if (!NextPHI) 8237 return nullptr; // Couldn't evaluate! 8238 NextIterVals[PN] = NextPHI; 8239 8240 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8241 8242 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8243 // cease to be able to evaluate one of them or if they stop evolving, 8244 // because that doesn't necessarily prevent us from computing PN. 8245 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8246 for (const auto &I : CurrentIterVals) { 8247 PHINode *PHI = dyn_cast<PHINode>(I.first); 8248 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8249 PHIsToCompute.emplace_back(PHI, I.second); 8250 } 8251 // We use two distinct loops because EvaluateExpression may invalidate any 8252 // iterators into CurrentIterVals. 8253 for (const auto &I : PHIsToCompute) { 8254 PHINode *PHI = I.first; 8255 Constant *&NextPHI = NextIterVals[PHI]; 8256 if (!NextPHI) { // Not already computed. 8257 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8258 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8259 } 8260 if (NextPHI != I.second) 8261 StoppedEvolving = false; 8262 } 8263 8264 // If all entries in CurrentIterVals == NextIterVals then we can stop 8265 // iterating, the loop can't continue to change. 8266 if (StoppedEvolving) 8267 return RetVal = CurrentIterVals[PN]; 8268 8269 CurrentIterVals.swap(NextIterVals); 8270 } 8271 } 8272 8273 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8274 Value *Cond, 8275 bool ExitWhen) { 8276 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8277 if (!PN) return getCouldNotCompute(); 8278 8279 // If the loop is canonicalized, the PHI will have exactly two entries. 8280 // That's the only form we support here. 8281 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8282 8283 DenseMap<Instruction *, Constant *> CurrentIterVals; 8284 BasicBlock *Header = L->getHeader(); 8285 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8286 8287 BasicBlock *Latch = L->getLoopLatch(); 8288 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8289 8290 for (PHINode &PHI : Header->phis()) { 8291 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8292 CurrentIterVals[&PHI] = StartCST; 8293 } 8294 if (!CurrentIterVals.count(PN)) 8295 return getCouldNotCompute(); 8296 8297 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8298 // the loop symbolically to determine when the condition gets a value of 8299 // "ExitWhen". 8300 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8301 const DataLayout &DL = getDataLayout(); 8302 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8303 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8304 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8305 8306 // Couldn't symbolically evaluate. 8307 if (!CondVal) return getCouldNotCompute(); 8308 8309 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8310 ++NumBruteForceTripCountsComputed; 8311 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8312 } 8313 8314 // Update all the PHI nodes for the next iteration. 8315 DenseMap<Instruction *, Constant *> NextIterVals; 8316 8317 // Create a list of which PHIs we need to compute. We want to do this before 8318 // calling EvaluateExpression on them because that may invalidate iterators 8319 // into CurrentIterVals. 8320 SmallVector<PHINode *, 8> PHIsToCompute; 8321 for (const auto &I : CurrentIterVals) { 8322 PHINode *PHI = dyn_cast<PHINode>(I.first); 8323 if (!PHI || PHI->getParent() != Header) continue; 8324 PHIsToCompute.push_back(PHI); 8325 } 8326 for (PHINode *PHI : PHIsToCompute) { 8327 Constant *&NextPHI = NextIterVals[PHI]; 8328 if (NextPHI) continue; // Already computed! 8329 8330 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8331 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8332 } 8333 CurrentIterVals.swap(NextIterVals); 8334 } 8335 8336 // Too many iterations were needed to evaluate. 8337 return getCouldNotCompute(); 8338 } 8339 8340 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8341 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8342 ValuesAtScopes[V]; 8343 // Check to see if we've folded this expression at this loop before. 8344 for (auto &LS : Values) 8345 if (LS.first == L) 8346 return LS.second ? LS.second : V; 8347 8348 Values.emplace_back(L, nullptr); 8349 8350 // Otherwise compute it. 8351 const SCEV *C = computeSCEVAtScope(V, L); 8352 for (auto &LS : reverse(ValuesAtScopes[V])) 8353 if (LS.first == L) { 8354 LS.second = C; 8355 break; 8356 } 8357 return C; 8358 } 8359 8360 /// This builds up a Constant using the ConstantExpr interface. That way, we 8361 /// will return Constants for objects which aren't represented by a 8362 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8363 /// Returns NULL if the SCEV isn't representable as a Constant. 8364 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8365 switch (V->getSCEVType()) { 8366 case scCouldNotCompute: 8367 case scAddRecExpr: 8368 return nullptr; 8369 case scConstant: 8370 return cast<SCEVConstant>(V)->getValue(); 8371 case scUnknown: 8372 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8373 case scSignExtend: { 8374 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8375 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8376 return ConstantExpr::getSExt(CastOp, SS->getType()); 8377 return nullptr; 8378 } 8379 case scZeroExtend: { 8380 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8381 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8382 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8383 return nullptr; 8384 } 8385 case scPtrToInt: { 8386 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 8387 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 8388 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 8389 8390 return nullptr; 8391 } 8392 case scTruncate: { 8393 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8394 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8395 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8396 return nullptr; 8397 } 8398 case scAddExpr: { 8399 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8400 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8401 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8402 unsigned AS = PTy->getAddressSpace(); 8403 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8404 C = ConstantExpr::getBitCast(C, DestPtrTy); 8405 } 8406 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8407 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8408 if (!C2) 8409 return nullptr; 8410 8411 // First pointer! 8412 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8413 unsigned AS = C2->getType()->getPointerAddressSpace(); 8414 std::swap(C, C2); 8415 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8416 // The offsets have been converted to bytes. We can add bytes to an 8417 // i8* by GEP with the byte count in the first index. 8418 C = ConstantExpr::getBitCast(C, DestPtrTy); 8419 } 8420 8421 // Don't bother trying to sum two pointers. We probably can't 8422 // statically compute a load that results from it anyway. 8423 if (C2->getType()->isPointerTy()) 8424 return nullptr; 8425 8426 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8427 if (PTy->getElementType()->isStructTy()) 8428 C2 = ConstantExpr::getIntegerCast( 8429 C2, Type::getInt32Ty(C->getContext()), true); 8430 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8431 } else 8432 C = ConstantExpr::getAdd(C, C2); 8433 } 8434 return C; 8435 } 8436 return nullptr; 8437 } 8438 case scMulExpr: { 8439 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8440 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8441 // Don't bother with pointers at all. 8442 if (C->getType()->isPointerTy()) 8443 return nullptr; 8444 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8445 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8446 if (!C2 || C2->getType()->isPointerTy()) 8447 return nullptr; 8448 C = ConstantExpr::getMul(C, C2); 8449 } 8450 return C; 8451 } 8452 return nullptr; 8453 } 8454 case scUDivExpr: { 8455 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8456 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8457 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8458 if (LHS->getType() == RHS->getType()) 8459 return ConstantExpr::getUDiv(LHS, RHS); 8460 return nullptr; 8461 } 8462 case scSMaxExpr: 8463 case scUMaxExpr: 8464 case scSMinExpr: 8465 case scUMinExpr: 8466 return nullptr; // TODO: smax, umax, smin, umax. 8467 } 8468 llvm_unreachable("Unknown SCEV kind!"); 8469 } 8470 8471 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8472 if (isa<SCEVConstant>(V)) return V; 8473 8474 // If this instruction is evolved from a constant-evolving PHI, compute the 8475 // exit value from the loop without using SCEVs. 8476 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8477 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8478 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8479 const Loop *CurrLoop = this->LI[I->getParent()]; 8480 // Looking for loop exit value. 8481 if (CurrLoop && CurrLoop->getParentLoop() == L && 8482 PN->getParent() == CurrLoop->getHeader()) { 8483 // Okay, there is no closed form solution for the PHI node. Check 8484 // to see if the loop that contains it has a known backedge-taken 8485 // count. If so, we may be able to force computation of the exit 8486 // value. 8487 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8488 // This trivial case can show up in some degenerate cases where 8489 // the incoming IR has not yet been fully simplified. 8490 if (BackedgeTakenCount->isZero()) { 8491 Value *InitValue = nullptr; 8492 bool MultipleInitValues = false; 8493 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8494 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8495 if (!InitValue) 8496 InitValue = PN->getIncomingValue(i); 8497 else if (InitValue != PN->getIncomingValue(i)) { 8498 MultipleInitValues = true; 8499 break; 8500 } 8501 } 8502 } 8503 if (!MultipleInitValues && InitValue) 8504 return getSCEV(InitValue); 8505 } 8506 // Do we have a loop invariant value flowing around the backedge 8507 // for a loop which must execute the backedge? 8508 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8509 isKnownPositive(BackedgeTakenCount) && 8510 PN->getNumIncomingValues() == 2) { 8511 8512 unsigned InLoopPred = 8513 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8514 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8515 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8516 return getSCEV(BackedgeVal); 8517 } 8518 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8519 // Okay, we know how many times the containing loop executes. If 8520 // this is a constant evolving PHI node, get the final value at 8521 // the specified iteration number. 8522 Constant *RV = getConstantEvolutionLoopExitValue( 8523 PN, BTCC->getAPInt(), CurrLoop); 8524 if (RV) return getSCEV(RV); 8525 } 8526 } 8527 8528 // If there is a single-input Phi, evaluate it at our scope. If we can 8529 // prove that this replacement does not break LCSSA form, use new value. 8530 if (PN->getNumOperands() == 1) { 8531 const SCEV *Input = getSCEV(PN->getOperand(0)); 8532 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8533 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8534 // for the simplest case just support constants. 8535 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8536 } 8537 } 8538 8539 // Okay, this is an expression that we cannot symbolically evaluate 8540 // into a SCEV. Check to see if it's possible to symbolically evaluate 8541 // the arguments into constants, and if so, try to constant propagate the 8542 // result. This is particularly useful for computing loop exit values. 8543 if (CanConstantFold(I)) { 8544 SmallVector<Constant *, 4> Operands; 8545 bool MadeImprovement = false; 8546 for (Value *Op : I->operands()) { 8547 if (Constant *C = dyn_cast<Constant>(Op)) { 8548 Operands.push_back(C); 8549 continue; 8550 } 8551 8552 // If any of the operands is non-constant and if they are 8553 // non-integer and non-pointer, don't even try to analyze them 8554 // with scev techniques. 8555 if (!isSCEVable(Op->getType())) 8556 return V; 8557 8558 const SCEV *OrigV = getSCEV(Op); 8559 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8560 MadeImprovement |= OrigV != OpV; 8561 8562 Constant *C = BuildConstantFromSCEV(OpV); 8563 if (!C) return V; 8564 if (C->getType() != Op->getType()) 8565 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8566 Op->getType(), 8567 false), 8568 C, Op->getType()); 8569 Operands.push_back(C); 8570 } 8571 8572 // Check to see if getSCEVAtScope actually made an improvement. 8573 if (MadeImprovement) { 8574 Constant *C = nullptr; 8575 const DataLayout &DL = getDataLayout(); 8576 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8577 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8578 Operands[1], DL, &TLI); 8579 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8580 if (!Load->isVolatile()) 8581 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8582 DL); 8583 } else 8584 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8585 if (!C) return V; 8586 return getSCEV(C); 8587 } 8588 } 8589 } 8590 8591 // This is some other type of SCEVUnknown, just return it. 8592 return V; 8593 } 8594 8595 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8596 // Avoid performing the look-up in the common case where the specified 8597 // expression has no loop-variant portions. 8598 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8599 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8600 if (OpAtScope != Comm->getOperand(i)) { 8601 // Okay, at least one of these operands is loop variant but might be 8602 // foldable. Build a new instance of the folded commutative expression. 8603 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8604 Comm->op_begin()+i); 8605 NewOps.push_back(OpAtScope); 8606 8607 for (++i; i != e; ++i) { 8608 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8609 NewOps.push_back(OpAtScope); 8610 } 8611 if (isa<SCEVAddExpr>(Comm)) 8612 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8613 if (isa<SCEVMulExpr>(Comm)) 8614 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8615 if (isa<SCEVMinMaxExpr>(Comm)) 8616 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8617 llvm_unreachable("Unknown commutative SCEV type!"); 8618 } 8619 } 8620 // If we got here, all operands are loop invariant. 8621 return Comm; 8622 } 8623 8624 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8625 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8626 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8627 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8628 return Div; // must be loop invariant 8629 return getUDivExpr(LHS, RHS); 8630 } 8631 8632 // If this is a loop recurrence for a loop that does not contain L, then we 8633 // are dealing with the final value computed by the loop. 8634 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8635 // First, attempt to evaluate each operand. 8636 // Avoid performing the look-up in the common case where the specified 8637 // expression has no loop-variant portions. 8638 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8639 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8640 if (OpAtScope == AddRec->getOperand(i)) 8641 continue; 8642 8643 // Okay, at least one of these operands is loop variant but might be 8644 // foldable. Build a new instance of the folded commutative expression. 8645 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8646 AddRec->op_begin()+i); 8647 NewOps.push_back(OpAtScope); 8648 for (++i; i != e; ++i) 8649 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8650 8651 const SCEV *FoldedRec = 8652 getAddRecExpr(NewOps, AddRec->getLoop(), 8653 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8654 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8655 // The addrec may be folded to a nonrecurrence, for example, if the 8656 // induction variable is multiplied by zero after constant folding. Go 8657 // ahead and return the folded value. 8658 if (!AddRec) 8659 return FoldedRec; 8660 break; 8661 } 8662 8663 // If the scope is outside the addrec's loop, evaluate it by using the 8664 // loop exit value of the addrec. 8665 if (!AddRec->getLoop()->contains(L)) { 8666 // To evaluate this recurrence, we need to know how many times the AddRec 8667 // loop iterates. Compute this now. 8668 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8669 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8670 8671 // Then, evaluate the AddRec. 8672 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8673 } 8674 8675 return AddRec; 8676 } 8677 8678 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8679 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8680 if (Op == Cast->getOperand()) 8681 return Cast; // must be loop invariant 8682 return getZeroExtendExpr(Op, Cast->getType()); 8683 } 8684 8685 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8686 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8687 if (Op == Cast->getOperand()) 8688 return Cast; // must be loop invariant 8689 return getSignExtendExpr(Op, Cast->getType()); 8690 } 8691 8692 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8693 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8694 if (Op == Cast->getOperand()) 8695 return Cast; // must be loop invariant 8696 return getTruncateExpr(Op, Cast->getType()); 8697 } 8698 8699 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 8700 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8701 if (Op == Cast->getOperand()) 8702 return Cast; // must be loop invariant 8703 return getPtrToIntExpr(Op, Cast->getType()); 8704 } 8705 8706 llvm_unreachable("Unknown SCEV type!"); 8707 } 8708 8709 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8710 return getSCEVAtScope(getSCEV(V), L); 8711 } 8712 8713 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8714 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8715 return stripInjectiveFunctions(ZExt->getOperand()); 8716 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8717 return stripInjectiveFunctions(SExt->getOperand()); 8718 return S; 8719 } 8720 8721 /// Finds the minimum unsigned root of the following equation: 8722 /// 8723 /// A * X = B (mod N) 8724 /// 8725 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8726 /// A and B isn't important. 8727 /// 8728 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8729 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8730 ScalarEvolution &SE) { 8731 uint32_t BW = A.getBitWidth(); 8732 assert(BW == SE.getTypeSizeInBits(B->getType())); 8733 assert(A != 0 && "A must be non-zero."); 8734 8735 // 1. D = gcd(A, N) 8736 // 8737 // The gcd of A and N may have only one prime factor: 2. The number of 8738 // trailing zeros in A is its multiplicity 8739 uint32_t Mult2 = A.countTrailingZeros(); 8740 // D = 2^Mult2 8741 8742 // 2. Check if B is divisible by D. 8743 // 8744 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8745 // is not less than multiplicity of this prime factor for D. 8746 if (SE.GetMinTrailingZeros(B) < Mult2) 8747 return SE.getCouldNotCompute(); 8748 8749 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8750 // modulo (N / D). 8751 // 8752 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8753 // (N / D) in general. The inverse itself always fits into BW bits, though, 8754 // so we immediately truncate it. 8755 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8756 APInt Mod(BW + 1, 0); 8757 Mod.setBit(BW - Mult2); // Mod = N / D 8758 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8759 8760 // 4. Compute the minimum unsigned root of the equation: 8761 // I * (B / D) mod (N / D) 8762 // To simplify the computation, we factor out the divide by D: 8763 // (I * B mod N) / D 8764 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8765 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8766 } 8767 8768 /// For a given quadratic addrec, generate coefficients of the corresponding 8769 /// quadratic equation, multiplied by a common value to ensure that they are 8770 /// integers. 8771 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8772 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8773 /// were multiplied by, and BitWidth is the bit width of the original addrec 8774 /// coefficients. 8775 /// This function returns None if the addrec coefficients are not compile- 8776 /// time constants. 8777 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8778 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8779 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8780 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8781 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8782 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8783 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8784 << *AddRec << '\n'); 8785 8786 // We currently can only solve this if the coefficients are constants. 8787 if (!LC || !MC || !NC) { 8788 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8789 return None; 8790 } 8791 8792 APInt L = LC->getAPInt(); 8793 APInt M = MC->getAPInt(); 8794 APInt N = NC->getAPInt(); 8795 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8796 8797 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8798 unsigned NewWidth = BitWidth + 1; 8799 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8800 << BitWidth << '\n'); 8801 // The sign-extension (as opposed to a zero-extension) here matches the 8802 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8803 N = N.sext(NewWidth); 8804 M = M.sext(NewWidth); 8805 L = L.sext(NewWidth); 8806 8807 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8808 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8809 // L+M, L+2M+N, L+3M+3N, ... 8810 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8811 // 8812 // The equation Acc = 0 is then 8813 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8814 // In a quadratic form it becomes: 8815 // N n^2 + (2M-N) n + 2L = 0. 8816 8817 APInt A = N; 8818 APInt B = 2 * M - A; 8819 APInt C = 2 * L; 8820 APInt T = APInt(NewWidth, 2); 8821 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8822 << "x + " << C << ", coeff bw: " << NewWidth 8823 << ", multiplied by " << T << '\n'); 8824 return std::make_tuple(A, B, C, T, BitWidth); 8825 } 8826 8827 /// Helper function to compare optional APInts: 8828 /// (a) if X and Y both exist, return min(X, Y), 8829 /// (b) if neither X nor Y exist, return None, 8830 /// (c) if exactly one of X and Y exists, return that value. 8831 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8832 if (X.hasValue() && Y.hasValue()) { 8833 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8834 APInt XW = X->sextOrSelf(W); 8835 APInt YW = Y->sextOrSelf(W); 8836 return XW.slt(YW) ? *X : *Y; 8837 } 8838 if (!X.hasValue() && !Y.hasValue()) 8839 return None; 8840 return X.hasValue() ? *X : *Y; 8841 } 8842 8843 /// Helper function to truncate an optional APInt to a given BitWidth. 8844 /// When solving addrec-related equations, it is preferable to return a value 8845 /// that has the same bit width as the original addrec's coefficients. If the 8846 /// solution fits in the original bit width, truncate it (except for i1). 8847 /// Returning a value of a different bit width may inhibit some optimizations. 8848 /// 8849 /// In general, a solution to a quadratic equation generated from an addrec 8850 /// may require BW+1 bits, where BW is the bit width of the addrec's 8851 /// coefficients. The reason is that the coefficients of the quadratic 8852 /// equation are BW+1 bits wide (to avoid truncation when converting from 8853 /// the addrec to the equation). 8854 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8855 if (!X.hasValue()) 8856 return None; 8857 unsigned W = X->getBitWidth(); 8858 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8859 return X->trunc(BitWidth); 8860 return X; 8861 } 8862 8863 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8864 /// iterations. The values L, M, N are assumed to be signed, and they 8865 /// should all have the same bit widths. 8866 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8867 /// where BW is the bit width of the addrec's coefficients. 8868 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8869 /// returned as such, otherwise the bit width of the returned value may 8870 /// be greater than BW. 8871 /// 8872 /// This function returns None if 8873 /// (a) the addrec coefficients are not constant, or 8874 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8875 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8876 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8877 static Optional<APInt> 8878 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8879 APInt A, B, C, M; 8880 unsigned BitWidth; 8881 auto T = GetQuadraticEquation(AddRec); 8882 if (!T.hasValue()) 8883 return None; 8884 8885 std::tie(A, B, C, M, BitWidth) = *T; 8886 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8887 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8888 if (!X.hasValue()) 8889 return None; 8890 8891 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8892 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8893 if (!V->isZero()) 8894 return None; 8895 8896 return TruncIfPossible(X, BitWidth); 8897 } 8898 8899 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8900 /// iterations. The values M, N are assumed to be signed, and they 8901 /// should all have the same bit widths. 8902 /// Find the least n such that c(n) does not belong to the given range, 8903 /// while c(n-1) does. 8904 /// 8905 /// This function returns None if 8906 /// (a) the addrec coefficients are not constant, or 8907 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8908 /// bounds of the range. 8909 static Optional<APInt> 8910 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8911 const ConstantRange &Range, ScalarEvolution &SE) { 8912 assert(AddRec->getOperand(0)->isZero() && 8913 "Starting value of addrec should be 0"); 8914 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8915 << Range << ", addrec " << *AddRec << '\n'); 8916 // This case is handled in getNumIterationsInRange. Here we can assume that 8917 // we start in the range. 8918 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8919 "Addrec's initial value should be in range"); 8920 8921 APInt A, B, C, M; 8922 unsigned BitWidth; 8923 auto T = GetQuadraticEquation(AddRec); 8924 if (!T.hasValue()) 8925 return None; 8926 8927 // Be careful about the return value: there can be two reasons for not 8928 // returning an actual number. First, if no solutions to the equations 8929 // were found, and second, if the solutions don't leave the given range. 8930 // The first case means that the actual solution is "unknown", the second 8931 // means that it's known, but not valid. If the solution is unknown, we 8932 // cannot make any conclusions. 8933 // Return a pair: the optional solution and a flag indicating if the 8934 // solution was found. 8935 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8936 // Solve for signed overflow and unsigned overflow, pick the lower 8937 // solution. 8938 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8939 << Bound << " (before multiplying by " << M << ")\n"); 8940 Bound *= M; // The quadratic equation multiplier. 8941 8942 Optional<APInt> SO = None; 8943 if (BitWidth > 1) { 8944 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8945 "signed overflow\n"); 8946 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8947 } 8948 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8949 "unsigned overflow\n"); 8950 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8951 BitWidth+1); 8952 8953 auto LeavesRange = [&] (const APInt &X) { 8954 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8955 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8956 if (Range.contains(V0->getValue())) 8957 return false; 8958 // X should be at least 1, so X-1 is non-negative. 8959 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8960 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8961 if (Range.contains(V1->getValue())) 8962 return true; 8963 return false; 8964 }; 8965 8966 // If SolveQuadraticEquationWrap returns None, it means that there can 8967 // be a solution, but the function failed to find it. We cannot treat it 8968 // as "no solution". 8969 if (!SO.hasValue() || !UO.hasValue()) 8970 return { None, false }; 8971 8972 // Check the smaller value first to see if it leaves the range. 8973 // At this point, both SO and UO must have values. 8974 Optional<APInt> Min = MinOptional(SO, UO); 8975 if (LeavesRange(*Min)) 8976 return { Min, true }; 8977 Optional<APInt> Max = Min == SO ? UO : SO; 8978 if (LeavesRange(*Max)) 8979 return { Max, true }; 8980 8981 // Solutions were found, but were eliminated, hence the "true". 8982 return { None, true }; 8983 }; 8984 8985 std::tie(A, B, C, M, BitWidth) = *T; 8986 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8987 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8988 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8989 auto SL = SolveForBoundary(Lower); 8990 auto SU = SolveForBoundary(Upper); 8991 // If any of the solutions was unknown, no meaninigful conclusions can 8992 // be made. 8993 if (!SL.second || !SU.second) 8994 return None; 8995 8996 // Claim: The correct solution is not some value between Min and Max. 8997 // 8998 // Justification: Assuming that Min and Max are different values, one of 8999 // them is when the first signed overflow happens, the other is when the 9000 // first unsigned overflow happens. Crossing the range boundary is only 9001 // possible via an overflow (treating 0 as a special case of it, modeling 9002 // an overflow as crossing k*2^W for some k). 9003 // 9004 // The interesting case here is when Min was eliminated as an invalid 9005 // solution, but Max was not. The argument is that if there was another 9006 // overflow between Min and Max, it would also have been eliminated if 9007 // it was considered. 9008 // 9009 // For a given boundary, it is possible to have two overflows of the same 9010 // type (signed/unsigned) without having the other type in between: this 9011 // can happen when the vertex of the parabola is between the iterations 9012 // corresponding to the overflows. This is only possible when the two 9013 // overflows cross k*2^W for the same k. In such case, if the second one 9014 // left the range (and was the first one to do so), the first overflow 9015 // would have to enter the range, which would mean that either we had left 9016 // the range before or that we started outside of it. Both of these cases 9017 // are contradictions. 9018 // 9019 // Claim: In the case where SolveForBoundary returns None, the correct 9020 // solution is not some value between the Max for this boundary and the 9021 // Min of the other boundary. 9022 // 9023 // Justification: Assume that we had such Max_A and Min_B corresponding 9024 // to range boundaries A and B and such that Max_A < Min_B. If there was 9025 // a solution between Max_A and Min_B, it would have to be caused by an 9026 // overflow corresponding to either A or B. It cannot correspond to B, 9027 // since Min_B is the first occurrence of such an overflow. If it 9028 // corresponded to A, it would have to be either a signed or an unsigned 9029 // overflow that is larger than both eliminated overflows for A. But 9030 // between the eliminated overflows and this overflow, the values would 9031 // cover the entire value space, thus crossing the other boundary, which 9032 // is a contradiction. 9033 9034 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9035 } 9036 9037 ScalarEvolution::ExitLimit 9038 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9039 bool AllowPredicates) { 9040 9041 // This is only used for loops with a "x != y" exit test. The exit condition 9042 // is now expressed as a single expression, V = x-y. So the exit test is 9043 // effectively V != 0. We know and take advantage of the fact that this 9044 // expression only being used in a comparison by zero context. 9045 9046 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9047 // If the value is a constant 9048 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9049 // If the value is already zero, the branch will execute zero times. 9050 if (C->getValue()->isZero()) return C; 9051 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9052 } 9053 9054 const SCEVAddRecExpr *AddRec = 9055 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9056 9057 if (!AddRec && AllowPredicates) 9058 // Try to make this an AddRec using runtime tests, in the first X 9059 // iterations of this loop, where X is the SCEV expression found by the 9060 // algorithm below. 9061 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9062 9063 if (!AddRec || AddRec->getLoop() != L) 9064 return getCouldNotCompute(); 9065 9066 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9067 // the quadratic equation to solve it. 9068 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9069 // We can only use this value if the chrec ends up with an exact zero 9070 // value at this index. When solving for "X*X != 5", for example, we 9071 // should not accept a root of 2. 9072 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9073 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9074 return ExitLimit(R, R, false, Predicates); 9075 } 9076 return getCouldNotCompute(); 9077 } 9078 9079 // Otherwise we can only handle this if it is affine. 9080 if (!AddRec->isAffine()) 9081 return getCouldNotCompute(); 9082 9083 // If this is an affine expression, the execution count of this branch is 9084 // the minimum unsigned root of the following equation: 9085 // 9086 // Start + Step*N = 0 (mod 2^BW) 9087 // 9088 // equivalent to: 9089 // 9090 // Step*N = -Start (mod 2^BW) 9091 // 9092 // where BW is the common bit width of Start and Step. 9093 9094 // Get the initial value for the loop. 9095 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9096 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9097 9098 // For now we handle only constant steps. 9099 // 9100 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9101 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9102 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9103 // We have not yet seen any such cases. 9104 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9105 if (!StepC || StepC->getValue()->isZero()) 9106 return getCouldNotCompute(); 9107 9108 // For positive steps (counting up until unsigned overflow): 9109 // N = -Start/Step (as unsigned) 9110 // For negative steps (counting down to zero): 9111 // N = Start/-Step 9112 // First compute the unsigned distance from zero in the direction of Step. 9113 bool CountDown = StepC->getAPInt().isNegative(); 9114 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9115 9116 // Handle unitary steps, which cannot wraparound. 9117 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9118 // N = Distance (as unsigned) 9119 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9120 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9121 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 9122 if (MaxBECountBase.ult(MaxBECount)) 9123 MaxBECount = MaxBECountBase; 9124 9125 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9126 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9127 // case, and see if we can improve the bound. 9128 // 9129 // Explicitly handling this here is necessary because getUnsignedRange 9130 // isn't context-sensitive; it doesn't know that we only care about the 9131 // range inside the loop. 9132 const SCEV *Zero = getZero(Distance->getType()); 9133 const SCEV *One = getOne(Distance->getType()); 9134 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9135 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9136 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9137 // as "unsigned_max(Distance + 1) - 1". 9138 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9139 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9140 } 9141 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9142 } 9143 9144 // If the condition controls loop exit (the loop exits only if the expression 9145 // is true) and the addition is no-wrap we can use unsigned divide to 9146 // compute the backedge count. In this case, the step may not divide the 9147 // distance, but we don't care because if the condition is "missed" the loop 9148 // will have undefined behavior due to wrapping. 9149 if (ControlsExit && AddRec->hasNoSelfWrap() && 9150 loopHasNoAbnormalExits(AddRec->getLoop())) { 9151 const SCEV *Exact = 9152 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9153 const SCEV *Max = 9154 Exact == getCouldNotCompute() 9155 ? Exact 9156 : getConstant(getUnsignedRangeMax(Exact)); 9157 return ExitLimit(Exact, Max, false, Predicates); 9158 } 9159 9160 // Solve the general equation. 9161 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9162 getNegativeSCEV(Start), *this); 9163 const SCEV *M = E == getCouldNotCompute() 9164 ? E 9165 : getConstant(getUnsignedRangeMax(E)); 9166 return ExitLimit(E, M, false, Predicates); 9167 } 9168 9169 ScalarEvolution::ExitLimit 9170 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9171 // Loops that look like: while (X == 0) are very strange indeed. We don't 9172 // handle them yet except for the trivial case. This could be expanded in the 9173 // future as needed. 9174 9175 // If the value is a constant, check to see if it is known to be non-zero 9176 // already. If so, the backedge will execute zero times. 9177 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9178 if (!C->getValue()->isZero()) 9179 return getZero(C->getType()); 9180 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9181 } 9182 9183 // We could implement others, but I really doubt anyone writes loops like 9184 // this, and if they did, they would already be constant folded. 9185 return getCouldNotCompute(); 9186 } 9187 9188 std::pair<const BasicBlock *, const BasicBlock *> 9189 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9190 const { 9191 // If the block has a unique predecessor, then there is no path from the 9192 // predecessor to the block that does not go through the direct edge 9193 // from the predecessor to the block. 9194 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9195 return {Pred, BB}; 9196 9197 // A loop's header is defined to be a block that dominates the loop. 9198 // If the header has a unique predecessor outside the loop, it must be 9199 // a block that has exactly one successor that can reach the loop. 9200 if (const Loop *L = LI.getLoopFor(BB)) 9201 return {L->getLoopPredecessor(), L->getHeader()}; 9202 9203 return {nullptr, nullptr}; 9204 } 9205 9206 /// SCEV structural equivalence is usually sufficient for testing whether two 9207 /// expressions are equal, however for the purposes of looking for a condition 9208 /// guarding a loop, it can be useful to be a little more general, since a 9209 /// front-end may have replicated the controlling expression. 9210 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9211 // Quick check to see if they are the same SCEV. 9212 if (A == B) return true; 9213 9214 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9215 // Not all instructions that are "identical" compute the same value. For 9216 // instance, two distinct alloca instructions allocating the same type are 9217 // identical and do not read memory; but compute distinct values. 9218 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9219 }; 9220 9221 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9222 // two different instructions with the same value. Check for this case. 9223 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9224 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9225 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9226 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9227 if (ComputesEqualValues(AI, BI)) 9228 return true; 9229 9230 // Otherwise assume they may have a different value. 9231 return false; 9232 } 9233 9234 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9235 const SCEV *&LHS, const SCEV *&RHS, 9236 unsigned Depth) { 9237 bool Changed = false; 9238 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9239 // '0 != 0'. 9240 auto TrivialCase = [&](bool TriviallyTrue) { 9241 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9242 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9243 return true; 9244 }; 9245 // If we hit the max recursion limit bail out. 9246 if (Depth >= 3) 9247 return false; 9248 9249 // Canonicalize a constant to the right side. 9250 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9251 // Check for both operands constant. 9252 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9253 if (ConstantExpr::getICmp(Pred, 9254 LHSC->getValue(), 9255 RHSC->getValue())->isNullValue()) 9256 return TrivialCase(false); 9257 else 9258 return TrivialCase(true); 9259 } 9260 // Otherwise swap the operands to put the constant on the right. 9261 std::swap(LHS, RHS); 9262 Pred = ICmpInst::getSwappedPredicate(Pred); 9263 Changed = true; 9264 } 9265 9266 // If we're comparing an addrec with a value which is loop-invariant in the 9267 // addrec's loop, put the addrec on the left. Also make a dominance check, 9268 // as both operands could be addrecs loop-invariant in each other's loop. 9269 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9270 const Loop *L = AR->getLoop(); 9271 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9272 std::swap(LHS, RHS); 9273 Pred = ICmpInst::getSwappedPredicate(Pred); 9274 Changed = true; 9275 } 9276 } 9277 9278 // If there's a constant operand, canonicalize comparisons with boundary 9279 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9280 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9281 const APInt &RA = RC->getAPInt(); 9282 9283 bool SimplifiedByConstantRange = false; 9284 9285 if (!ICmpInst::isEquality(Pred)) { 9286 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9287 if (ExactCR.isFullSet()) 9288 return TrivialCase(true); 9289 else if (ExactCR.isEmptySet()) 9290 return TrivialCase(false); 9291 9292 APInt NewRHS; 9293 CmpInst::Predicate NewPred; 9294 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9295 ICmpInst::isEquality(NewPred)) { 9296 // We were able to convert an inequality to an equality. 9297 Pred = NewPred; 9298 RHS = getConstant(NewRHS); 9299 Changed = SimplifiedByConstantRange = true; 9300 } 9301 } 9302 9303 if (!SimplifiedByConstantRange) { 9304 switch (Pred) { 9305 default: 9306 break; 9307 case ICmpInst::ICMP_EQ: 9308 case ICmpInst::ICMP_NE: 9309 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9310 if (!RA) 9311 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9312 if (const SCEVMulExpr *ME = 9313 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9314 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9315 ME->getOperand(0)->isAllOnesValue()) { 9316 RHS = AE->getOperand(1); 9317 LHS = ME->getOperand(1); 9318 Changed = true; 9319 } 9320 break; 9321 9322 9323 // The "Should have been caught earlier!" messages refer to the fact 9324 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9325 // should have fired on the corresponding cases, and canonicalized the 9326 // check to trivial case. 9327 9328 case ICmpInst::ICMP_UGE: 9329 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9330 Pred = ICmpInst::ICMP_UGT; 9331 RHS = getConstant(RA - 1); 9332 Changed = true; 9333 break; 9334 case ICmpInst::ICMP_ULE: 9335 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9336 Pred = ICmpInst::ICMP_ULT; 9337 RHS = getConstant(RA + 1); 9338 Changed = true; 9339 break; 9340 case ICmpInst::ICMP_SGE: 9341 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9342 Pred = ICmpInst::ICMP_SGT; 9343 RHS = getConstant(RA - 1); 9344 Changed = true; 9345 break; 9346 case ICmpInst::ICMP_SLE: 9347 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9348 Pred = ICmpInst::ICMP_SLT; 9349 RHS = getConstant(RA + 1); 9350 Changed = true; 9351 break; 9352 } 9353 } 9354 } 9355 9356 // Check for obvious equality. 9357 if (HasSameValue(LHS, RHS)) { 9358 if (ICmpInst::isTrueWhenEqual(Pred)) 9359 return TrivialCase(true); 9360 if (ICmpInst::isFalseWhenEqual(Pred)) 9361 return TrivialCase(false); 9362 } 9363 9364 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9365 // adding or subtracting 1 from one of the operands. 9366 switch (Pred) { 9367 case ICmpInst::ICMP_SLE: 9368 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9369 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9370 SCEV::FlagNSW); 9371 Pred = ICmpInst::ICMP_SLT; 9372 Changed = true; 9373 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9374 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9375 SCEV::FlagNSW); 9376 Pred = ICmpInst::ICMP_SLT; 9377 Changed = true; 9378 } 9379 break; 9380 case ICmpInst::ICMP_SGE: 9381 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9382 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9383 SCEV::FlagNSW); 9384 Pred = ICmpInst::ICMP_SGT; 9385 Changed = true; 9386 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9387 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9388 SCEV::FlagNSW); 9389 Pred = ICmpInst::ICMP_SGT; 9390 Changed = true; 9391 } 9392 break; 9393 case ICmpInst::ICMP_ULE: 9394 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9395 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9396 SCEV::FlagNUW); 9397 Pred = ICmpInst::ICMP_ULT; 9398 Changed = true; 9399 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9400 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9401 Pred = ICmpInst::ICMP_ULT; 9402 Changed = true; 9403 } 9404 break; 9405 case ICmpInst::ICMP_UGE: 9406 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9407 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9408 Pred = ICmpInst::ICMP_UGT; 9409 Changed = true; 9410 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9411 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9412 SCEV::FlagNUW); 9413 Pred = ICmpInst::ICMP_UGT; 9414 Changed = true; 9415 } 9416 break; 9417 default: 9418 break; 9419 } 9420 9421 // TODO: More simplifications are possible here. 9422 9423 // Recursively simplify until we either hit a recursion limit or nothing 9424 // changes. 9425 if (Changed) 9426 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9427 9428 return Changed; 9429 } 9430 9431 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9432 return getSignedRangeMax(S).isNegative(); 9433 } 9434 9435 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9436 return getSignedRangeMin(S).isStrictlyPositive(); 9437 } 9438 9439 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9440 return !getSignedRangeMin(S).isNegative(); 9441 } 9442 9443 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9444 return !getSignedRangeMax(S).isStrictlyPositive(); 9445 } 9446 9447 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9448 return isKnownNegative(S) || isKnownPositive(S); 9449 } 9450 9451 std::pair<const SCEV *, const SCEV *> 9452 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9453 // Compute SCEV on entry of loop L. 9454 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9455 if (Start == getCouldNotCompute()) 9456 return { Start, Start }; 9457 // Compute post increment SCEV for loop L. 9458 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9459 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9460 return { Start, PostInc }; 9461 } 9462 9463 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9464 const SCEV *LHS, const SCEV *RHS) { 9465 // First collect all loops. 9466 SmallPtrSet<const Loop *, 8> LoopsUsed; 9467 getUsedLoops(LHS, LoopsUsed); 9468 getUsedLoops(RHS, LoopsUsed); 9469 9470 if (LoopsUsed.empty()) 9471 return false; 9472 9473 // Domination relationship must be a linear order on collected loops. 9474 #ifndef NDEBUG 9475 for (auto *L1 : LoopsUsed) 9476 for (auto *L2 : LoopsUsed) 9477 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9478 DT.dominates(L2->getHeader(), L1->getHeader())) && 9479 "Domination relationship is not a linear order"); 9480 #endif 9481 9482 const Loop *MDL = 9483 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9484 [&](const Loop *L1, const Loop *L2) { 9485 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9486 }); 9487 9488 // Get init and post increment value for LHS. 9489 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9490 // if LHS contains unknown non-invariant SCEV then bail out. 9491 if (SplitLHS.first == getCouldNotCompute()) 9492 return false; 9493 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9494 // Get init and post increment value for RHS. 9495 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9496 // if RHS contains unknown non-invariant SCEV then bail out. 9497 if (SplitRHS.first == getCouldNotCompute()) 9498 return false; 9499 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9500 // It is possible that init SCEV contains an invariant load but it does 9501 // not dominate MDL and is not available at MDL loop entry, so we should 9502 // check it here. 9503 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9504 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9505 return false; 9506 9507 // It seems backedge guard check is faster than entry one so in some cases 9508 // it can speed up whole estimation by short circuit 9509 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9510 SplitRHS.second) && 9511 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9512 } 9513 9514 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9515 const SCEV *LHS, const SCEV *RHS) { 9516 // Canonicalize the inputs first. 9517 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9518 9519 if (isKnownViaInduction(Pred, LHS, RHS)) 9520 return true; 9521 9522 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9523 return true; 9524 9525 // Otherwise see what can be done with some simple reasoning. 9526 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9527 } 9528 9529 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9530 const SCEV *LHS, const SCEV *RHS, 9531 const Instruction *Context) { 9532 // TODO: Analyze guards and assumes from Context's block. 9533 return isKnownPredicate(Pred, LHS, RHS) || 9534 isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS); 9535 } 9536 9537 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9538 const SCEVAddRecExpr *LHS, 9539 const SCEV *RHS) { 9540 const Loop *L = LHS->getLoop(); 9541 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9542 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9543 } 9544 9545 Optional<ScalarEvolution::MonotonicPredicateType> 9546 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 9547 ICmpInst::Predicate Pred) { 9548 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 9549 9550 #ifndef NDEBUG 9551 // Verify an invariant: inverting the predicate should turn a monotonically 9552 // increasing change to a monotonically decreasing one, and vice versa. 9553 if (Result) { 9554 auto ResultSwapped = 9555 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 9556 9557 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 9558 assert(ResultSwapped.getValue() != Result.getValue() && 9559 "monotonicity should flip as we flip the predicate"); 9560 } 9561 #endif 9562 9563 return Result; 9564 } 9565 9566 Optional<ScalarEvolution::MonotonicPredicateType> 9567 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 9568 ICmpInst::Predicate Pred) { 9569 // A zero step value for LHS means the induction variable is essentially a 9570 // loop invariant value. We don't really depend on the predicate actually 9571 // flipping from false to true (for increasing predicates, and the other way 9572 // around for decreasing predicates), all we care about is that *if* the 9573 // predicate changes then it only changes from false to true. 9574 // 9575 // A zero step value in itself is not very useful, but there may be places 9576 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9577 // as general as possible. 9578 9579 // Only handle LE/LT/GE/GT predicates. 9580 if (!ICmpInst::isRelational(Pred)) 9581 return None; 9582 9583 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 9584 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 9585 "Should be greater or less!"); 9586 9587 // Check that AR does not wrap. 9588 if (ICmpInst::isUnsigned(Pred)) { 9589 if (!LHS->hasNoUnsignedWrap()) 9590 return None; 9591 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9592 } else { 9593 assert(ICmpInst::isSigned(Pred) && 9594 "Relational predicate is either signed or unsigned!"); 9595 if (!LHS->hasNoSignedWrap()) 9596 return None; 9597 9598 const SCEV *Step = LHS->getStepRecurrence(*this); 9599 9600 if (isKnownNonNegative(Step)) 9601 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9602 9603 if (isKnownNonPositive(Step)) 9604 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9605 9606 return None; 9607 } 9608 } 9609 9610 Optional<ScalarEvolution::LoopInvariantPredicate> 9611 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 9612 const SCEV *LHS, const SCEV *RHS, 9613 const Loop *L) { 9614 9615 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9616 if (!isLoopInvariant(RHS, L)) { 9617 if (!isLoopInvariant(LHS, L)) 9618 return None; 9619 9620 std::swap(LHS, RHS); 9621 Pred = ICmpInst::getSwappedPredicate(Pred); 9622 } 9623 9624 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9625 if (!ArLHS || ArLHS->getLoop() != L) 9626 return None; 9627 9628 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 9629 if (!MonotonicType) 9630 return None; 9631 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9632 // true as the loop iterates, and the backedge is control dependent on 9633 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9634 // 9635 // * if the predicate was false in the first iteration then the predicate 9636 // is never evaluated again, since the loop exits without taking the 9637 // backedge. 9638 // * if the predicate was true in the first iteration then it will 9639 // continue to be true for all future iterations since it is 9640 // monotonically increasing. 9641 // 9642 // For both the above possibilities, we can replace the loop varying 9643 // predicate with its value on the first iteration of the loop (which is 9644 // loop invariant). 9645 // 9646 // A similar reasoning applies for a monotonically decreasing predicate, by 9647 // replacing true with false and false with true in the above two bullets. 9648 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 9649 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9650 9651 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9652 return None; 9653 9654 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 9655 } 9656 9657 Optional<ScalarEvolution::LoopInvariantPredicate> 9658 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 9659 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9660 const Instruction *Context, const SCEV *MaxIter) { 9661 // Try to prove the following set of facts: 9662 // - The predicate is monotonic in the iteration space. 9663 // - If the check does not fail on the 1st iteration: 9664 // - No overflow will happen during first MaxIter iterations; 9665 // - It will not fail on the MaxIter'th iteration. 9666 // If the check does fail on the 1st iteration, we leave the loop and no 9667 // other checks matter. 9668 9669 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9670 if (!isLoopInvariant(RHS, L)) { 9671 if (!isLoopInvariant(LHS, L)) 9672 return None; 9673 9674 std::swap(LHS, RHS); 9675 Pred = ICmpInst::getSwappedPredicate(Pred); 9676 } 9677 9678 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 9679 if (!AR || AR->getLoop() != L) 9680 return None; 9681 9682 // The predicate must be relational (i.e. <, <=, >=, >). 9683 if (!ICmpInst::isRelational(Pred)) 9684 return None; 9685 9686 // TODO: Support steps other than +/- 1. 9687 const SCEV *Step = AR->getStepRecurrence(*this); 9688 auto *One = getOne(Step->getType()); 9689 auto *MinusOne = getNegativeSCEV(One); 9690 if (Step != One && Step != MinusOne) 9691 return None; 9692 9693 // Type mismatch here means that MaxIter is potentially larger than max 9694 // unsigned value in start type, which mean we cannot prove no wrap for the 9695 // indvar. 9696 if (AR->getType() != MaxIter->getType()) 9697 return None; 9698 9699 // Value of IV on suggested last iteration. 9700 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 9701 // Does it still meet the requirement? 9702 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 9703 return None; 9704 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 9705 // not exceed max unsigned value of this type), this effectively proves 9706 // that there is no wrap during the iteration. To prove that there is no 9707 // signed/unsigned wrap, we need to check that 9708 // Start <= Last for step = 1 or Start >= Last for step = -1. 9709 ICmpInst::Predicate NoOverflowPred = 9710 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 9711 if (Step == MinusOne) 9712 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 9713 const SCEV *Start = AR->getStart(); 9714 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context)) 9715 return None; 9716 9717 // Everything is fine. 9718 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 9719 } 9720 9721 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9722 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9723 if (HasSameValue(LHS, RHS)) 9724 return ICmpInst::isTrueWhenEqual(Pred); 9725 9726 // This code is split out from isKnownPredicate because it is called from 9727 // within isLoopEntryGuardedByCond. 9728 9729 auto CheckRanges = 9730 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9731 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9732 .contains(RangeLHS); 9733 }; 9734 9735 // The check at the top of the function catches the case where the values are 9736 // known to be equal. 9737 if (Pred == CmpInst::ICMP_EQ) 9738 return false; 9739 9740 if (Pred == CmpInst::ICMP_NE) 9741 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9742 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9743 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9744 9745 if (CmpInst::isSigned(Pred)) 9746 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9747 9748 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9749 } 9750 9751 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9752 const SCEV *LHS, 9753 const SCEV *RHS) { 9754 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9755 // Return Y via OutY. 9756 auto MatchBinaryAddToConst = 9757 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9758 SCEV::NoWrapFlags ExpectedFlags) { 9759 const SCEV *NonConstOp, *ConstOp; 9760 SCEV::NoWrapFlags FlagsPresent; 9761 9762 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9763 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9764 return false; 9765 9766 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9767 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9768 }; 9769 9770 APInt C; 9771 9772 switch (Pred) { 9773 default: 9774 break; 9775 9776 case ICmpInst::ICMP_SGE: 9777 std::swap(LHS, RHS); 9778 LLVM_FALLTHROUGH; 9779 case ICmpInst::ICMP_SLE: 9780 // X s<= (X + C)<nsw> if C >= 0 9781 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9782 return true; 9783 9784 // (X + C)<nsw> s<= X if C <= 0 9785 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9786 !C.isStrictlyPositive()) 9787 return true; 9788 break; 9789 9790 case ICmpInst::ICMP_SGT: 9791 std::swap(LHS, RHS); 9792 LLVM_FALLTHROUGH; 9793 case ICmpInst::ICMP_SLT: 9794 // X s< (X + C)<nsw> if C > 0 9795 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9796 C.isStrictlyPositive()) 9797 return true; 9798 9799 // (X + C)<nsw> s< X if C < 0 9800 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9801 return true; 9802 break; 9803 9804 case ICmpInst::ICMP_UGE: 9805 std::swap(LHS, RHS); 9806 LLVM_FALLTHROUGH; 9807 case ICmpInst::ICMP_ULE: 9808 // X u<= (X + C)<nuw> for any C 9809 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW)) 9810 return true; 9811 break; 9812 9813 case ICmpInst::ICMP_UGT: 9814 std::swap(LHS, RHS); 9815 LLVM_FALLTHROUGH; 9816 case ICmpInst::ICMP_ULT: 9817 // X u< (X + C)<nuw> if C != 0 9818 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue()) 9819 return true; 9820 break; 9821 } 9822 9823 return false; 9824 } 9825 9826 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9827 const SCEV *LHS, 9828 const SCEV *RHS) { 9829 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9830 return false; 9831 9832 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9833 // the stack can result in exponential time complexity. 9834 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9835 9836 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9837 // 9838 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9839 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9840 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9841 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9842 // use isKnownPredicate later if needed. 9843 return isKnownNonNegative(RHS) && 9844 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9845 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9846 } 9847 9848 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 9849 ICmpInst::Predicate Pred, 9850 const SCEV *LHS, const SCEV *RHS) { 9851 // No need to even try if we know the module has no guards. 9852 if (!HasGuards) 9853 return false; 9854 9855 return any_of(*BB, [&](const Instruction &I) { 9856 using namespace llvm::PatternMatch; 9857 9858 Value *Condition; 9859 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9860 m_Value(Condition))) && 9861 isImpliedCond(Pred, LHS, RHS, Condition, false); 9862 }); 9863 } 9864 9865 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9866 /// protected by a conditional between LHS and RHS. This is used to 9867 /// to eliminate casts. 9868 bool 9869 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9870 ICmpInst::Predicate Pred, 9871 const SCEV *LHS, const SCEV *RHS) { 9872 // Interpret a null as meaning no loop, where there is obviously no guard 9873 // (interprocedural conditions notwithstanding). 9874 if (!L) return true; 9875 9876 if (VerifyIR) 9877 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9878 "This cannot be done on broken IR!"); 9879 9880 9881 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9882 return true; 9883 9884 BasicBlock *Latch = L->getLoopLatch(); 9885 if (!Latch) 9886 return false; 9887 9888 BranchInst *LoopContinuePredicate = 9889 dyn_cast<BranchInst>(Latch->getTerminator()); 9890 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9891 isImpliedCond(Pred, LHS, RHS, 9892 LoopContinuePredicate->getCondition(), 9893 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9894 return true; 9895 9896 // We don't want more than one activation of the following loops on the stack 9897 // -- that can lead to O(n!) time complexity. 9898 if (WalkingBEDominatingConds) 9899 return false; 9900 9901 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9902 9903 // See if we can exploit a trip count to prove the predicate. 9904 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9905 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9906 if (LatchBECount != getCouldNotCompute()) { 9907 // We know that Latch branches back to the loop header exactly 9908 // LatchBECount times. This means the backdege condition at Latch is 9909 // equivalent to "{0,+,1} u< LatchBECount". 9910 Type *Ty = LatchBECount->getType(); 9911 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9912 const SCEV *LoopCounter = 9913 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9914 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9915 LatchBECount)) 9916 return true; 9917 } 9918 9919 // Check conditions due to any @llvm.assume intrinsics. 9920 for (auto &AssumeVH : AC.assumptions()) { 9921 if (!AssumeVH) 9922 continue; 9923 auto *CI = cast<CallInst>(AssumeVH); 9924 if (!DT.dominates(CI, Latch->getTerminator())) 9925 continue; 9926 9927 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9928 return true; 9929 } 9930 9931 // If the loop is not reachable from the entry block, we risk running into an 9932 // infinite loop as we walk up into the dom tree. These loops do not matter 9933 // anyway, so we just return a conservative answer when we see them. 9934 if (!DT.isReachableFromEntry(L->getHeader())) 9935 return false; 9936 9937 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9938 return true; 9939 9940 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9941 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9942 assert(DTN && "should reach the loop header before reaching the root!"); 9943 9944 BasicBlock *BB = DTN->getBlock(); 9945 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9946 return true; 9947 9948 BasicBlock *PBB = BB->getSinglePredecessor(); 9949 if (!PBB) 9950 continue; 9951 9952 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9953 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9954 continue; 9955 9956 Value *Condition = ContinuePredicate->getCondition(); 9957 9958 // If we have an edge `E` within the loop body that dominates the only 9959 // latch, the condition guarding `E` also guards the backedge. This 9960 // reasoning works only for loops with a single latch. 9961 9962 BasicBlockEdge DominatingEdge(PBB, BB); 9963 if (DominatingEdge.isSingleEdge()) { 9964 // We're constructively (and conservatively) enumerating edges within the 9965 // loop body that dominate the latch. The dominator tree better agree 9966 // with us on this: 9967 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9968 9969 if (isImpliedCond(Pred, LHS, RHS, Condition, 9970 BB != ContinuePredicate->getSuccessor(0))) 9971 return true; 9972 } 9973 } 9974 9975 return false; 9976 } 9977 9978 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 9979 ICmpInst::Predicate Pred, 9980 const SCEV *LHS, 9981 const SCEV *RHS) { 9982 if (VerifyIR) 9983 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 9984 "This cannot be done on broken IR!"); 9985 9986 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9987 return true; 9988 9989 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9990 // the facts (a >= b && a != b) separately. A typical situation is when the 9991 // non-strict comparison is known from ranges and non-equality is known from 9992 // dominating predicates. If we are proving strict comparison, we always try 9993 // to prove non-equality and non-strict comparison separately. 9994 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9995 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9996 bool ProvedNonStrictComparison = false; 9997 bool ProvedNonEquality = false; 9998 9999 if (ProvingStrictComparison) { 10000 ProvedNonStrictComparison = 10001 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 10002 ProvedNonEquality = 10003 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 10004 if (ProvedNonStrictComparison && ProvedNonEquality) 10005 return true; 10006 } 10007 10008 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10009 auto ProveViaGuard = [&](const BasicBlock *Block) { 10010 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10011 return true; 10012 if (ProvingStrictComparison) { 10013 if (!ProvedNonStrictComparison) 10014 ProvedNonStrictComparison = 10015 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 10016 if (!ProvedNonEquality) 10017 ProvedNonEquality = 10018 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 10019 if (ProvedNonStrictComparison && ProvedNonEquality) 10020 return true; 10021 } 10022 return false; 10023 }; 10024 10025 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10026 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10027 const Instruction *Context = &BB->front(); 10028 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context)) 10029 return true; 10030 if (ProvingStrictComparison) { 10031 if (!ProvedNonStrictComparison) 10032 ProvedNonStrictComparison = isImpliedCond(NonStrictPredicate, LHS, RHS, 10033 Condition, Inverse, Context); 10034 if (!ProvedNonEquality) 10035 ProvedNonEquality = isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, 10036 Condition, Inverse, Context); 10037 if (ProvedNonStrictComparison && ProvedNonEquality) 10038 return true; 10039 } 10040 return false; 10041 }; 10042 10043 // Starting at the block's predecessor, climb up the predecessor chain, as long 10044 // as there are predecessors that can be found that have unique successors 10045 // leading to the original block. 10046 const Loop *ContainingLoop = LI.getLoopFor(BB); 10047 const BasicBlock *PredBB; 10048 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10049 PredBB = ContainingLoop->getLoopPredecessor(); 10050 else 10051 PredBB = BB->getSinglePredecessor(); 10052 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10053 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10054 if (ProveViaGuard(Pair.first)) 10055 return true; 10056 10057 const BranchInst *LoopEntryPredicate = 10058 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10059 if (!LoopEntryPredicate || 10060 LoopEntryPredicate->isUnconditional()) 10061 continue; 10062 10063 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10064 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10065 return true; 10066 } 10067 10068 // Check conditions due to any @llvm.assume intrinsics. 10069 for (auto &AssumeVH : AC.assumptions()) { 10070 if (!AssumeVH) 10071 continue; 10072 auto *CI = cast<CallInst>(AssumeVH); 10073 if (!DT.dominates(CI, BB)) 10074 continue; 10075 10076 if (ProveViaCond(CI->getArgOperand(0), false)) 10077 return true; 10078 } 10079 10080 return false; 10081 } 10082 10083 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10084 ICmpInst::Predicate Pred, 10085 const SCEV *LHS, 10086 const SCEV *RHS) { 10087 // Interpret a null as meaning no loop, where there is obviously no guard 10088 // (interprocedural conditions notwithstanding). 10089 if (!L) 10090 return false; 10091 10092 // Both LHS and RHS must be available at loop entry. 10093 assert(isAvailableAtLoopEntry(LHS, L) && 10094 "LHS is not available at Loop Entry"); 10095 assert(isAvailableAtLoopEntry(RHS, L) && 10096 "RHS is not available at Loop Entry"); 10097 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10098 } 10099 10100 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10101 const SCEV *RHS, 10102 const Value *FoundCondValue, bool Inverse, 10103 const Instruction *Context) { 10104 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10105 return false; 10106 10107 auto ClearOnExit = 10108 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10109 10110 // Recursively handle And and Or conditions. 10111 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 10112 if (BO->getOpcode() == Instruction::And) { 10113 if (!Inverse) 10114 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse, 10115 Context) || 10116 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse, 10117 Context); 10118 } else if (BO->getOpcode() == Instruction::Or) { 10119 if (Inverse) 10120 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse, 10121 Context) || 10122 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse, 10123 Context); 10124 } 10125 } 10126 10127 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10128 if (!ICI) return false; 10129 10130 // Now that we found a conditional branch that dominates the loop or controls 10131 // the loop latch. Check to see if it is the comparison we are looking for. 10132 ICmpInst::Predicate FoundPred; 10133 if (Inverse) 10134 FoundPred = ICI->getInversePredicate(); 10135 else 10136 FoundPred = ICI->getPredicate(); 10137 10138 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10139 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10140 10141 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context); 10142 } 10143 10144 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10145 const SCEV *RHS, 10146 ICmpInst::Predicate FoundPred, 10147 const SCEV *FoundLHS, const SCEV *FoundRHS, 10148 const Instruction *Context) { 10149 // Balance the types. 10150 if (getTypeSizeInBits(LHS->getType()) < 10151 getTypeSizeInBits(FoundLHS->getType())) { 10152 // For unsigned and equality predicates, try to prove that both found 10153 // operands fit into narrow unsigned range. If so, try to prove facts in 10154 // narrow types. 10155 if (!CmpInst::isSigned(FoundPred)) { 10156 auto *NarrowType = LHS->getType(); 10157 auto *WideType = FoundLHS->getType(); 10158 auto BitWidth = getTypeSizeInBits(NarrowType); 10159 const SCEV *MaxValue = getZeroExtendExpr( 10160 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10161 if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) && 10162 isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) { 10163 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10164 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10165 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10166 TruncFoundRHS, Context)) 10167 return true; 10168 } 10169 } 10170 10171 if (CmpInst::isSigned(Pred)) { 10172 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10173 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10174 } else { 10175 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10176 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10177 } 10178 } else if (getTypeSizeInBits(LHS->getType()) > 10179 getTypeSizeInBits(FoundLHS->getType())) { 10180 if (CmpInst::isSigned(FoundPred)) { 10181 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10182 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10183 } else { 10184 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10185 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10186 } 10187 } 10188 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10189 FoundRHS, Context); 10190 } 10191 10192 bool ScalarEvolution::isImpliedCondBalancedTypes( 10193 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10194 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10195 const Instruction *Context) { 10196 assert(getTypeSizeInBits(LHS->getType()) == 10197 getTypeSizeInBits(FoundLHS->getType()) && 10198 "Types should be balanced!"); 10199 // Canonicalize the query to match the way instcombine will have 10200 // canonicalized the comparison. 10201 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10202 if (LHS == RHS) 10203 return CmpInst::isTrueWhenEqual(Pred); 10204 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10205 if (FoundLHS == FoundRHS) 10206 return CmpInst::isFalseWhenEqual(FoundPred); 10207 10208 // Check to see if we can make the LHS or RHS match. 10209 if (LHS == FoundRHS || RHS == FoundLHS) { 10210 if (isa<SCEVConstant>(RHS)) { 10211 std::swap(FoundLHS, FoundRHS); 10212 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10213 } else { 10214 std::swap(LHS, RHS); 10215 Pred = ICmpInst::getSwappedPredicate(Pred); 10216 } 10217 } 10218 10219 // Check whether the found predicate is the same as the desired predicate. 10220 if (FoundPred == Pred) 10221 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10222 10223 // Check whether swapping the found predicate makes it the same as the 10224 // desired predicate. 10225 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 10226 if (isa<SCEVConstant>(RHS)) 10227 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context); 10228 else 10229 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), RHS, 10230 LHS, FoundLHS, FoundRHS, Context); 10231 } 10232 10233 // Unsigned comparison is the same as signed comparison when both the operands 10234 // are non-negative. 10235 if (CmpInst::isUnsigned(FoundPred) && 10236 CmpInst::getSignedPredicate(FoundPred) == Pred && 10237 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 10238 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10239 10240 // Check if we can make progress by sharpening ranges. 10241 if (FoundPred == ICmpInst::ICMP_NE && 10242 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 10243 10244 const SCEVConstant *C = nullptr; 10245 const SCEV *V = nullptr; 10246 10247 if (isa<SCEVConstant>(FoundLHS)) { 10248 C = cast<SCEVConstant>(FoundLHS); 10249 V = FoundRHS; 10250 } else { 10251 C = cast<SCEVConstant>(FoundRHS); 10252 V = FoundLHS; 10253 } 10254 10255 // The guarding predicate tells us that C != V. If the known range 10256 // of V is [C, t), we can sharpen the range to [C + 1, t). The 10257 // range we consider has to correspond to same signedness as the 10258 // predicate we're interested in folding. 10259 10260 APInt Min = ICmpInst::isSigned(Pred) ? 10261 getSignedRangeMin(V) : getUnsignedRangeMin(V); 10262 10263 if (Min == C->getAPInt()) { 10264 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 10265 // This is true even if (Min + 1) wraps around -- in case of 10266 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 10267 10268 APInt SharperMin = Min + 1; 10269 10270 switch (Pred) { 10271 case ICmpInst::ICMP_SGE: 10272 case ICmpInst::ICMP_UGE: 10273 // We know V `Pred` SharperMin. If this implies LHS `Pred` 10274 // RHS, we're done. 10275 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 10276 Context)) 10277 return true; 10278 LLVM_FALLTHROUGH; 10279 10280 case ICmpInst::ICMP_SGT: 10281 case ICmpInst::ICMP_UGT: 10282 // We know from the range information that (V `Pred` Min || 10283 // V == Min). We know from the guarding condition that !(V 10284 // == Min). This gives us 10285 // 10286 // V `Pred` Min || V == Min && !(V == Min) 10287 // => V `Pred` Min 10288 // 10289 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 10290 10291 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), 10292 Context)) 10293 return true; 10294 break; 10295 10296 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 10297 case ICmpInst::ICMP_SLE: 10298 case ICmpInst::ICMP_ULE: 10299 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10300 LHS, V, getConstant(SharperMin), Context)) 10301 return true; 10302 LLVM_FALLTHROUGH; 10303 10304 case ICmpInst::ICMP_SLT: 10305 case ICmpInst::ICMP_ULT: 10306 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10307 LHS, V, getConstant(Min), Context)) 10308 return true; 10309 break; 10310 10311 default: 10312 // No change 10313 break; 10314 } 10315 } 10316 } 10317 10318 // Check whether the actual condition is beyond sufficient. 10319 if (FoundPred == ICmpInst::ICMP_EQ) 10320 if (ICmpInst::isTrueWhenEqual(Pred)) 10321 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context)) 10322 return true; 10323 if (Pred == ICmpInst::ICMP_NE) 10324 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 10325 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, 10326 Context)) 10327 return true; 10328 10329 // Otherwise assume the worst. 10330 return false; 10331 } 10332 10333 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 10334 const SCEV *&L, const SCEV *&R, 10335 SCEV::NoWrapFlags &Flags) { 10336 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 10337 if (!AE || AE->getNumOperands() != 2) 10338 return false; 10339 10340 L = AE->getOperand(0); 10341 R = AE->getOperand(1); 10342 Flags = AE->getNoWrapFlags(); 10343 return true; 10344 } 10345 10346 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 10347 const SCEV *Less) { 10348 // We avoid subtracting expressions here because this function is usually 10349 // fairly deep in the call stack (i.e. is called many times). 10350 10351 // X - X = 0. 10352 if (More == Less) 10353 return APInt(getTypeSizeInBits(More->getType()), 0); 10354 10355 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 10356 const auto *LAR = cast<SCEVAddRecExpr>(Less); 10357 const auto *MAR = cast<SCEVAddRecExpr>(More); 10358 10359 if (LAR->getLoop() != MAR->getLoop()) 10360 return None; 10361 10362 // We look at affine expressions only; not for correctness but to keep 10363 // getStepRecurrence cheap. 10364 if (!LAR->isAffine() || !MAR->isAffine()) 10365 return None; 10366 10367 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 10368 return None; 10369 10370 Less = LAR->getStart(); 10371 More = MAR->getStart(); 10372 10373 // fall through 10374 } 10375 10376 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10377 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10378 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10379 return M - L; 10380 } 10381 10382 SCEV::NoWrapFlags Flags; 10383 const SCEV *LLess = nullptr, *RLess = nullptr; 10384 const SCEV *LMore = nullptr, *RMore = nullptr; 10385 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10386 // Compare (X + C1) vs X. 10387 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10388 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10389 if (RLess == More) 10390 return -(C1->getAPInt()); 10391 10392 // Compare X vs (X + C2). 10393 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10394 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10395 if (RMore == Less) 10396 return C2->getAPInt(); 10397 10398 // Compare (X + C1) vs (X + C2). 10399 if (C1 && C2 && RLess == RMore) 10400 return C2->getAPInt() - C1->getAPInt(); 10401 10402 return None; 10403 } 10404 10405 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10406 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10407 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) { 10408 // Try to recognize the following pattern: 10409 // 10410 // FoundRHS = ... 10411 // ... 10412 // loop: 10413 // FoundLHS = {Start,+,W} 10414 // context_bb: // Basic block from the same loop 10415 // known(Pred, FoundLHS, FoundRHS) 10416 // 10417 // If some predicate is known in the context of a loop, it is also known on 10418 // each iteration of this loop, including the first iteration. Therefore, in 10419 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10420 // prove the original pred using this fact. 10421 if (!Context) 10422 return false; 10423 const BasicBlock *ContextBB = Context->getParent(); 10424 // Make sure AR varies in the context block. 10425 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10426 const Loop *L = AR->getLoop(); 10427 // Make sure that context belongs to the loop and executes on 1st iteration 10428 // (if it ever executes at all). 10429 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10430 return false; 10431 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10432 return false; 10433 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10434 } 10435 10436 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10437 const Loop *L = AR->getLoop(); 10438 // Make sure that context belongs to the loop and executes on 1st iteration 10439 // (if it ever executes at all). 10440 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10441 return false; 10442 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10443 return false; 10444 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10445 } 10446 10447 return false; 10448 } 10449 10450 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10451 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10452 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10453 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10454 return false; 10455 10456 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10457 if (!AddRecLHS) 10458 return false; 10459 10460 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10461 if (!AddRecFoundLHS) 10462 return false; 10463 10464 // We'd like to let SCEV reason about control dependencies, so we constrain 10465 // both the inequalities to be about add recurrences on the same loop. This 10466 // way we can use isLoopEntryGuardedByCond later. 10467 10468 const Loop *L = AddRecFoundLHS->getLoop(); 10469 if (L != AddRecLHS->getLoop()) 10470 return false; 10471 10472 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10473 // 10474 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10475 // ... (2) 10476 // 10477 // Informal proof for (2), assuming (1) [*]: 10478 // 10479 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10480 // 10481 // Then 10482 // 10483 // FoundLHS s< FoundRHS s< INT_MIN - C 10484 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10485 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10486 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10487 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10488 // <=> FoundLHS + C s< FoundRHS + C 10489 // 10490 // [*]: (1) can be proved by ruling out overflow. 10491 // 10492 // [**]: This can be proved by analyzing all the four possibilities: 10493 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10494 // (A s>= 0, B s>= 0). 10495 // 10496 // Note: 10497 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10498 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10499 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10500 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10501 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10502 // C)". 10503 10504 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10505 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10506 if (!LDiff || !RDiff || *LDiff != *RDiff) 10507 return false; 10508 10509 if (LDiff->isMinValue()) 10510 return true; 10511 10512 APInt FoundRHSLimit; 10513 10514 if (Pred == CmpInst::ICMP_ULT) { 10515 FoundRHSLimit = -(*RDiff); 10516 } else { 10517 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10518 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10519 } 10520 10521 // Try to prove (1) or (2), as needed. 10522 return isAvailableAtLoopEntry(FoundRHS, L) && 10523 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10524 getConstant(FoundRHSLimit)); 10525 } 10526 10527 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10528 const SCEV *LHS, const SCEV *RHS, 10529 const SCEV *FoundLHS, 10530 const SCEV *FoundRHS, unsigned Depth) { 10531 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10532 10533 auto ClearOnExit = make_scope_exit([&]() { 10534 if (LPhi) { 10535 bool Erased = PendingMerges.erase(LPhi); 10536 assert(Erased && "Failed to erase LPhi!"); 10537 (void)Erased; 10538 } 10539 if (RPhi) { 10540 bool Erased = PendingMerges.erase(RPhi); 10541 assert(Erased && "Failed to erase RPhi!"); 10542 (void)Erased; 10543 } 10544 }); 10545 10546 // Find respective Phis and check that they are not being pending. 10547 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10548 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10549 if (!PendingMerges.insert(Phi).second) 10550 return false; 10551 LPhi = Phi; 10552 } 10553 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10554 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10555 // If we detect a loop of Phi nodes being processed by this method, for 10556 // example: 10557 // 10558 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10559 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10560 // 10561 // we don't want to deal with a case that complex, so return conservative 10562 // answer false. 10563 if (!PendingMerges.insert(Phi).second) 10564 return false; 10565 RPhi = Phi; 10566 } 10567 10568 // If none of LHS, RHS is a Phi, nothing to do here. 10569 if (!LPhi && !RPhi) 10570 return false; 10571 10572 // If there is a SCEVUnknown Phi we are interested in, make it left. 10573 if (!LPhi) { 10574 std::swap(LHS, RHS); 10575 std::swap(FoundLHS, FoundRHS); 10576 std::swap(LPhi, RPhi); 10577 Pred = ICmpInst::getSwappedPredicate(Pred); 10578 } 10579 10580 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10581 const BasicBlock *LBB = LPhi->getParent(); 10582 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10583 10584 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10585 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10586 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10587 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10588 }; 10589 10590 if (RPhi && RPhi->getParent() == LBB) { 10591 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10592 // If we compare two Phis from the same block, and for each entry block 10593 // the predicate is true for incoming values from this block, then the 10594 // predicate is also true for the Phis. 10595 for (const BasicBlock *IncBB : predecessors(LBB)) { 10596 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10597 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10598 if (!ProvedEasily(L, R)) 10599 return false; 10600 } 10601 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10602 // Case two: RHS is also a Phi from the same basic block, and it is an 10603 // AddRec. It means that there is a loop which has both AddRec and Unknown 10604 // PHIs, for it we can compare incoming values of AddRec from above the loop 10605 // and latch with their respective incoming values of LPhi. 10606 // TODO: Generalize to handle loops with many inputs in a header. 10607 if (LPhi->getNumIncomingValues() != 2) return false; 10608 10609 auto *RLoop = RAR->getLoop(); 10610 auto *Predecessor = RLoop->getLoopPredecessor(); 10611 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10612 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10613 if (!ProvedEasily(L1, RAR->getStart())) 10614 return false; 10615 auto *Latch = RLoop->getLoopLatch(); 10616 assert(Latch && "Loop with AddRec with no latch?"); 10617 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10618 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10619 return false; 10620 } else { 10621 // In all other cases go over inputs of LHS and compare each of them to RHS, 10622 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10623 // At this point RHS is either a non-Phi, or it is a Phi from some block 10624 // different from LBB. 10625 for (const BasicBlock *IncBB : predecessors(LBB)) { 10626 // Check that RHS is available in this block. 10627 if (!dominates(RHS, IncBB)) 10628 return false; 10629 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10630 if (!ProvedEasily(L, RHS)) 10631 return false; 10632 } 10633 } 10634 return true; 10635 } 10636 10637 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10638 const SCEV *LHS, const SCEV *RHS, 10639 const SCEV *FoundLHS, 10640 const SCEV *FoundRHS, 10641 const Instruction *Context) { 10642 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10643 return true; 10644 10645 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10646 return true; 10647 10648 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 10649 Context)) 10650 return true; 10651 10652 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10653 FoundLHS, FoundRHS) || 10654 // ~x < ~y --> x > y 10655 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10656 getNotSCEV(FoundRHS), 10657 getNotSCEV(FoundLHS)); 10658 } 10659 10660 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10661 template <typename MinMaxExprType> 10662 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10663 const SCEV *Candidate) { 10664 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10665 if (!MinMaxExpr) 10666 return false; 10667 10668 return is_contained(MinMaxExpr->operands(), Candidate); 10669 } 10670 10671 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10672 ICmpInst::Predicate Pred, 10673 const SCEV *LHS, const SCEV *RHS) { 10674 // If both sides are affine addrecs for the same loop, with equal 10675 // steps, and we know the recurrences don't wrap, then we only 10676 // need to check the predicate on the starting values. 10677 10678 if (!ICmpInst::isRelational(Pred)) 10679 return false; 10680 10681 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10682 if (!LAR) 10683 return false; 10684 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10685 if (!RAR) 10686 return false; 10687 if (LAR->getLoop() != RAR->getLoop()) 10688 return false; 10689 if (!LAR->isAffine() || !RAR->isAffine()) 10690 return false; 10691 10692 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10693 return false; 10694 10695 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10696 SCEV::FlagNSW : SCEV::FlagNUW; 10697 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10698 return false; 10699 10700 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10701 } 10702 10703 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10704 /// expression? 10705 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10706 ICmpInst::Predicate Pred, 10707 const SCEV *LHS, const SCEV *RHS) { 10708 switch (Pred) { 10709 default: 10710 return false; 10711 10712 case ICmpInst::ICMP_SGE: 10713 std::swap(LHS, RHS); 10714 LLVM_FALLTHROUGH; 10715 case ICmpInst::ICMP_SLE: 10716 return 10717 // min(A, ...) <= A 10718 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10719 // A <= max(A, ...) 10720 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10721 10722 case ICmpInst::ICMP_UGE: 10723 std::swap(LHS, RHS); 10724 LLVM_FALLTHROUGH; 10725 case ICmpInst::ICMP_ULE: 10726 return 10727 // min(A, ...) <= A 10728 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10729 // A <= max(A, ...) 10730 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10731 } 10732 10733 llvm_unreachable("covered switch fell through?!"); 10734 } 10735 10736 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10737 const SCEV *LHS, const SCEV *RHS, 10738 const SCEV *FoundLHS, 10739 const SCEV *FoundRHS, 10740 unsigned Depth) { 10741 assert(getTypeSizeInBits(LHS->getType()) == 10742 getTypeSizeInBits(RHS->getType()) && 10743 "LHS and RHS have different sizes?"); 10744 assert(getTypeSizeInBits(FoundLHS->getType()) == 10745 getTypeSizeInBits(FoundRHS->getType()) && 10746 "FoundLHS and FoundRHS have different sizes?"); 10747 // We want to avoid hurting the compile time with analysis of too big trees. 10748 if (Depth > MaxSCEVOperationsImplicationDepth) 10749 return false; 10750 10751 // We only want to work with GT comparison so far. 10752 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 10753 Pred = CmpInst::getSwappedPredicate(Pred); 10754 std::swap(LHS, RHS); 10755 std::swap(FoundLHS, FoundRHS); 10756 } 10757 10758 // For unsigned, try to reduce it to corresponding signed comparison. 10759 if (Pred == ICmpInst::ICMP_UGT) 10760 // We can replace unsigned predicate with its signed counterpart if all 10761 // involved values are non-negative. 10762 // TODO: We could have better support for unsigned. 10763 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 10764 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 10765 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 10766 // use this fact to prove that LHS and RHS are non-negative. 10767 const SCEV *MinusOne = getMinusOne(LHS->getType()); 10768 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 10769 FoundRHS) && 10770 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 10771 FoundRHS)) 10772 Pred = ICmpInst::ICMP_SGT; 10773 } 10774 10775 if (Pred != ICmpInst::ICMP_SGT) 10776 return false; 10777 10778 auto GetOpFromSExt = [&](const SCEV *S) { 10779 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10780 return Ext->getOperand(); 10781 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10782 // the constant in some cases. 10783 return S; 10784 }; 10785 10786 // Acquire values from extensions. 10787 auto *OrigLHS = LHS; 10788 auto *OrigFoundLHS = FoundLHS; 10789 LHS = GetOpFromSExt(LHS); 10790 FoundLHS = GetOpFromSExt(FoundLHS); 10791 10792 // Is the SGT predicate can be proved trivially or using the found context. 10793 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10794 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10795 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10796 FoundRHS, Depth + 1); 10797 }; 10798 10799 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10800 // We want to avoid creation of any new non-constant SCEV. Since we are 10801 // going to compare the operands to RHS, we should be certain that we don't 10802 // need any size extensions for this. So let's decline all cases when the 10803 // sizes of types of LHS and RHS do not match. 10804 // TODO: Maybe try to get RHS from sext to catch more cases? 10805 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10806 return false; 10807 10808 // Should not overflow. 10809 if (!LHSAddExpr->hasNoSignedWrap()) 10810 return false; 10811 10812 auto *LL = LHSAddExpr->getOperand(0); 10813 auto *LR = LHSAddExpr->getOperand(1); 10814 auto *MinusOne = getMinusOne(RHS->getType()); 10815 10816 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10817 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10818 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10819 }; 10820 // Try to prove the following rule: 10821 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10822 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10823 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10824 return true; 10825 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10826 Value *LL, *LR; 10827 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10828 10829 using namespace llvm::PatternMatch; 10830 10831 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10832 // Rules for division. 10833 // We are going to perform some comparisons with Denominator and its 10834 // derivative expressions. In general case, creating a SCEV for it may 10835 // lead to a complex analysis of the entire graph, and in particular it 10836 // can request trip count recalculation for the same loop. This would 10837 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10838 // this, we only want to create SCEVs that are constants in this section. 10839 // So we bail if Denominator is not a constant. 10840 if (!isa<ConstantInt>(LR)) 10841 return false; 10842 10843 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10844 10845 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10846 // then a SCEV for the numerator already exists and matches with FoundLHS. 10847 auto *Numerator = getExistingSCEV(LL); 10848 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10849 return false; 10850 10851 // Make sure that the numerator matches with FoundLHS and the denominator 10852 // is positive. 10853 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10854 return false; 10855 10856 auto *DTy = Denominator->getType(); 10857 auto *FRHSTy = FoundRHS->getType(); 10858 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10859 // One of types is a pointer and another one is not. We cannot extend 10860 // them properly to a wider type, so let us just reject this case. 10861 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10862 // to avoid this check. 10863 return false; 10864 10865 // Given that: 10866 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10867 auto *WTy = getWiderType(DTy, FRHSTy); 10868 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10869 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10870 10871 // Try to prove the following rule: 10872 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10873 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10874 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10875 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10876 if (isKnownNonPositive(RHS) && 10877 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10878 return true; 10879 10880 // Try to prove the following rule: 10881 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10882 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10883 // If we divide it by Denominator > 2, then: 10884 // 1. If FoundLHS is negative, then the result is 0. 10885 // 2. If FoundLHS is non-negative, then the result is non-negative. 10886 // Anyways, the result is non-negative. 10887 auto *MinusOne = getMinusOne(WTy); 10888 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10889 if (isKnownNegative(RHS) && 10890 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10891 return true; 10892 } 10893 } 10894 10895 // If our expression contained SCEVUnknown Phis, and we split it down and now 10896 // need to prove something for them, try to prove the predicate for every 10897 // possible incoming values of those Phis. 10898 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10899 return true; 10900 10901 return false; 10902 } 10903 10904 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10905 const SCEV *LHS, const SCEV *RHS) { 10906 // zext x u<= sext x, sext x s<= zext x 10907 switch (Pred) { 10908 case ICmpInst::ICMP_SGE: 10909 std::swap(LHS, RHS); 10910 LLVM_FALLTHROUGH; 10911 case ICmpInst::ICMP_SLE: { 10912 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10913 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10914 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10915 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10916 return true; 10917 break; 10918 } 10919 case ICmpInst::ICMP_UGE: 10920 std::swap(LHS, RHS); 10921 LLVM_FALLTHROUGH; 10922 case ICmpInst::ICMP_ULE: { 10923 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10924 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10925 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10926 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10927 return true; 10928 break; 10929 } 10930 default: 10931 break; 10932 }; 10933 return false; 10934 } 10935 10936 bool 10937 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10938 const SCEV *LHS, const SCEV *RHS) { 10939 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10940 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10941 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10942 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10943 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10944 } 10945 10946 bool 10947 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10948 const SCEV *LHS, const SCEV *RHS, 10949 const SCEV *FoundLHS, 10950 const SCEV *FoundRHS) { 10951 switch (Pred) { 10952 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10953 case ICmpInst::ICMP_EQ: 10954 case ICmpInst::ICMP_NE: 10955 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10956 return true; 10957 break; 10958 case ICmpInst::ICMP_SLT: 10959 case ICmpInst::ICMP_SLE: 10960 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10961 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10962 return true; 10963 break; 10964 case ICmpInst::ICMP_SGT: 10965 case ICmpInst::ICMP_SGE: 10966 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10967 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10968 return true; 10969 break; 10970 case ICmpInst::ICMP_ULT: 10971 case ICmpInst::ICMP_ULE: 10972 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10973 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10974 return true; 10975 break; 10976 case ICmpInst::ICMP_UGT: 10977 case ICmpInst::ICMP_UGE: 10978 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10979 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10980 return true; 10981 break; 10982 } 10983 10984 // Maybe it can be proved via operations? 10985 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10986 return true; 10987 10988 return false; 10989 } 10990 10991 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10992 const SCEV *LHS, 10993 const SCEV *RHS, 10994 const SCEV *FoundLHS, 10995 const SCEV *FoundRHS) { 10996 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10997 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10998 // reduce the compile time impact of this optimization. 10999 return false; 11000 11001 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 11002 if (!Addend) 11003 return false; 11004 11005 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 11006 11007 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 11008 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 11009 ConstantRange FoundLHSRange = 11010 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 11011 11012 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 11013 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 11014 11015 // We can also compute the range of values for `LHS` that satisfy the 11016 // consequent, "`LHS` `Pred` `RHS`": 11017 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 11018 ConstantRange SatisfyingLHSRange = 11019 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 11020 11021 // The antecedent implies the consequent if every value of `LHS` that 11022 // satisfies the antecedent also satisfies the consequent. 11023 return SatisfyingLHSRange.contains(LHSRange); 11024 } 11025 11026 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 11027 bool IsSigned, bool NoWrap) { 11028 assert(isKnownPositive(Stride) && "Positive stride expected!"); 11029 11030 if (NoWrap) return false; 11031 11032 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11033 const SCEV *One = getOne(Stride->getType()); 11034 11035 if (IsSigned) { 11036 APInt MaxRHS = getSignedRangeMax(RHS); 11037 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11038 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11039 11040 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11041 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11042 } 11043 11044 APInt MaxRHS = getUnsignedRangeMax(RHS); 11045 APInt MaxValue = APInt::getMaxValue(BitWidth); 11046 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11047 11048 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11049 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11050 } 11051 11052 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11053 bool IsSigned, bool NoWrap) { 11054 if (NoWrap) return false; 11055 11056 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11057 const SCEV *One = getOne(Stride->getType()); 11058 11059 if (IsSigned) { 11060 APInt MinRHS = getSignedRangeMin(RHS); 11061 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11062 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11063 11064 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11065 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11066 } 11067 11068 APInt MinRHS = getUnsignedRangeMin(RHS); 11069 APInt MinValue = APInt::getMinValue(BitWidth); 11070 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11071 11072 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11073 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11074 } 11075 11076 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 11077 bool Equality) { 11078 const SCEV *One = getOne(Step->getType()); 11079 Delta = Equality ? getAddExpr(Delta, Step) 11080 : getAddExpr(Delta, getMinusSCEV(Step, One)); 11081 return getUDivExpr(Delta, Step); 11082 } 11083 11084 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11085 const SCEV *Stride, 11086 const SCEV *End, 11087 unsigned BitWidth, 11088 bool IsSigned) { 11089 11090 assert(!isKnownNonPositive(Stride) && 11091 "Stride is expected strictly positive!"); 11092 // Calculate the maximum backedge count based on the range of values 11093 // permitted by Start, End, and Stride. 11094 const SCEV *MaxBECount; 11095 APInt MinStart = 11096 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11097 11098 APInt StrideForMaxBECount = 11099 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11100 11101 // We already know that the stride is positive, so we paper over conservatism 11102 // in our range computation by forcing StrideForMaxBECount to be at least one. 11103 // In theory this is unnecessary, but we expect MaxBECount to be a 11104 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 11105 // is nothing to constant fold it to). 11106 APInt One(BitWidth, 1, IsSigned); 11107 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 11108 11109 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11110 : APInt::getMaxValue(BitWidth); 11111 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11112 11113 // Although End can be a MAX expression we estimate MaxEnd considering only 11114 // the case End = RHS of the loop termination condition. This is safe because 11115 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11116 // taken count. 11117 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11118 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11119 11120 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 11121 getConstant(StrideForMaxBECount) /* Step */, 11122 false /* Equality */); 11123 11124 return MaxBECount; 11125 } 11126 11127 ScalarEvolution::ExitLimit 11128 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11129 const Loop *L, bool IsSigned, 11130 bool ControlsExit, bool AllowPredicates) { 11131 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11132 11133 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11134 bool PredicatedIV = false; 11135 11136 if (!IV && AllowPredicates) { 11137 // Try to make this an AddRec using runtime tests, in the first X 11138 // iterations of this loop, where X is the SCEV expression found by the 11139 // algorithm below. 11140 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11141 PredicatedIV = true; 11142 } 11143 11144 // Avoid weird loops 11145 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11146 return getCouldNotCompute(); 11147 11148 bool NoWrap = ControlsExit && 11149 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 11150 11151 const SCEV *Stride = IV->getStepRecurrence(*this); 11152 11153 bool PositiveStride = isKnownPositive(Stride); 11154 11155 // Avoid negative or zero stride values. 11156 if (!PositiveStride) { 11157 // We can compute the correct backedge taken count for loops with unknown 11158 // strides if we can prove that the loop is not an infinite loop with side 11159 // effects. Here's the loop structure we are trying to handle - 11160 // 11161 // i = start 11162 // do { 11163 // A[i] = i; 11164 // i += s; 11165 // } while (i < end); 11166 // 11167 // The backedge taken count for such loops is evaluated as - 11168 // (max(end, start + stride) - start - 1) /u stride 11169 // 11170 // The additional preconditions that we need to check to prove correctness 11171 // of the above formula is as follows - 11172 // 11173 // a) IV is either nuw or nsw depending upon signedness (indicated by the 11174 // NoWrap flag). 11175 // b) loop is single exit with no side effects. 11176 // 11177 // 11178 // Precondition a) implies that if the stride is negative, this is a single 11179 // trip loop. The backedge taken count formula reduces to zero in this case. 11180 // 11181 // Precondition b) implies that the unknown stride cannot be zero otherwise 11182 // we have UB. 11183 // 11184 // The positive stride case is the same as isKnownPositive(Stride) returning 11185 // true (original behavior of the function). 11186 // 11187 // We want to make sure that the stride is truly unknown as there are edge 11188 // cases where ScalarEvolution propagates no wrap flags to the 11189 // post-increment/decrement IV even though the increment/decrement operation 11190 // itself is wrapping. The computed backedge taken count may be wrong in 11191 // such cases. This is prevented by checking that the stride is not known to 11192 // be either positive or non-positive. For example, no wrap flags are 11193 // propagated to the post-increment IV of this loop with a trip count of 2 - 11194 // 11195 // unsigned char i; 11196 // for(i=127; i<128; i+=129) 11197 // A[i] = i; 11198 // 11199 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 11200 !loopHasNoSideEffects(L)) 11201 return getCouldNotCompute(); 11202 } else if (!Stride->isOne() && 11203 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 11204 // Avoid proven overflow cases: this will ensure that the backedge taken 11205 // count will not generate any unsigned overflow. Relaxed no-overflow 11206 // conditions exploit NoWrapFlags, allowing to optimize in presence of 11207 // undefined behaviors like the case of C language. 11208 return getCouldNotCompute(); 11209 11210 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 11211 : ICmpInst::ICMP_ULT; 11212 const SCEV *Start = IV->getStart(); 11213 const SCEV *End = RHS; 11214 // When the RHS is not invariant, we do not know the end bound of the loop and 11215 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 11216 // calculate the MaxBECount, given the start, stride and max value for the end 11217 // bound of the loop (RHS), and the fact that IV does not overflow (which is 11218 // checked above). 11219 if (!isLoopInvariant(RHS, L)) { 11220 const SCEV *MaxBECount = computeMaxBECountForLT( 11221 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11222 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 11223 false /*MaxOrZero*/, Predicates); 11224 } 11225 // If the backedge is taken at least once, then it will be taken 11226 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 11227 // is the LHS value of the less-than comparison the first time it is evaluated 11228 // and End is the RHS. 11229 const SCEV *BECountIfBackedgeTaken = 11230 computeBECount(getMinusSCEV(End, Start), Stride, false); 11231 // If the loop entry is guarded by the result of the backedge test of the 11232 // first loop iteration, then we know the backedge will be taken at least 11233 // once and so the backedge taken count is as above. If not then we use the 11234 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 11235 // as if the backedge is taken at least once max(End,Start) is End and so the 11236 // result is as above, and if not max(End,Start) is Start so we get a backedge 11237 // count of zero. 11238 const SCEV *BECount; 11239 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 11240 BECount = BECountIfBackedgeTaken; 11241 else { 11242 // If we know that RHS >= Start in the context of loop, then we know that 11243 // max(RHS, Start) = RHS at this point. 11244 if (isLoopEntryGuardedByCond( 11245 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start)) 11246 End = RHS; 11247 else 11248 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 11249 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 11250 } 11251 11252 const SCEV *MaxBECount; 11253 bool MaxOrZero = false; 11254 if (isa<SCEVConstant>(BECount)) 11255 MaxBECount = BECount; 11256 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 11257 // If we know exactly how many times the backedge will be taken if it's 11258 // taken at least once, then the backedge count will either be that or 11259 // zero. 11260 MaxBECount = BECountIfBackedgeTaken; 11261 MaxOrZero = true; 11262 } else { 11263 MaxBECount = computeMaxBECountForLT( 11264 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11265 } 11266 11267 if (isa<SCEVCouldNotCompute>(MaxBECount) && 11268 !isa<SCEVCouldNotCompute>(BECount)) 11269 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 11270 11271 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 11272 } 11273 11274 ScalarEvolution::ExitLimit 11275 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 11276 const Loop *L, bool IsSigned, 11277 bool ControlsExit, bool AllowPredicates) { 11278 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11279 // We handle only IV > Invariant 11280 if (!isLoopInvariant(RHS, L)) 11281 return getCouldNotCompute(); 11282 11283 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11284 if (!IV && AllowPredicates) 11285 // Try to make this an AddRec using runtime tests, in the first X 11286 // iterations of this loop, where X is the SCEV expression found by the 11287 // algorithm below. 11288 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11289 11290 // Avoid weird loops 11291 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11292 return getCouldNotCompute(); 11293 11294 bool NoWrap = ControlsExit && 11295 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 11296 11297 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 11298 11299 // Avoid negative or zero stride values 11300 if (!isKnownPositive(Stride)) 11301 return getCouldNotCompute(); 11302 11303 // Avoid proven overflow cases: this will ensure that the backedge taken count 11304 // will not generate any unsigned overflow. Relaxed no-overflow conditions 11305 // exploit NoWrapFlags, allowing to optimize in presence of undefined 11306 // behaviors like the case of C language. 11307 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 11308 return getCouldNotCompute(); 11309 11310 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 11311 : ICmpInst::ICMP_UGT; 11312 11313 const SCEV *Start = IV->getStart(); 11314 const SCEV *End = RHS; 11315 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 11316 // If we know that Start >= RHS in the context of loop, then we know that 11317 // min(RHS, Start) = RHS at this point. 11318 if (isLoopEntryGuardedByCond( 11319 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 11320 End = RHS; 11321 else 11322 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 11323 } 11324 11325 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 11326 11327 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 11328 : getUnsignedRangeMax(Start); 11329 11330 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 11331 : getUnsignedRangeMin(Stride); 11332 11333 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 11334 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 11335 : APInt::getMinValue(BitWidth) + (MinStride - 1); 11336 11337 // Although End can be a MIN expression we estimate MinEnd considering only 11338 // the case End = RHS. This is safe because in the other case (Start - End) 11339 // is zero, leading to a zero maximum backedge taken count. 11340 APInt MinEnd = 11341 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 11342 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 11343 11344 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 11345 ? BECount 11346 : computeBECount(getConstant(MaxStart - MinEnd), 11347 getConstant(MinStride), false); 11348 11349 if (isa<SCEVCouldNotCompute>(MaxBECount)) 11350 MaxBECount = BECount; 11351 11352 return ExitLimit(BECount, MaxBECount, false, Predicates); 11353 } 11354 11355 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 11356 ScalarEvolution &SE) const { 11357 if (Range.isFullSet()) // Infinite loop. 11358 return SE.getCouldNotCompute(); 11359 11360 // If the start is a non-zero constant, shift the range to simplify things. 11361 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 11362 if (!SC->getValue()->isZero()) { 11363 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 11364 Operands[0] = SE.getZero(SC->getType()); 11365 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 11366 getNoWrapFlags(FlagNW)); 11367 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 11368 return ShiftedAddRec->getNumIterationsInRange( 11369 Range.subtract(SC->getAPInt()), SE); 11370 // This is strange and shouldn't happen. 11371 return SE.getCouldNotCompute(); 11372 } 11373 11374 // The only time we can solve this is when we have all constant indices. 11375 // Otherwise, we cannot determine the overflow conditions. 11376 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 11377 return SE.getCouldNotCompute(); 11378 11379 // Okay at this point we know that all elements of the chrec are constants and 11380 // that the start element is zero. 11381 11382 // First check to see if the range contains zero. If not, the first 11383 // iteration exits. 11384 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 11385 if (!Range.contains(APInt(BitWidth, 0))) 11386 return SE.getZero(getType()); 11387 11388 if (isAffine()) { 11389 // If this is an affine expression then we have this situation: 11390 // Solve {0,+,A} in Range === Ax in Range 11391 11392 // We know that zero is in the range. If A is positive then we know that 11393 // the upper value of the range must be the first possible exit value. 11394 // If A is negative then the lower of the range is the last possible loop 11395 // value. Also note that we already checked for a full range. 11396 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 11397 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 11398 11399 // The exit value should be (End+A)/A. 11400 APInt ExitVal = (End + A).udiv(A); 11401 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 11402 11403 // Evaluate at the exit value. If we really did fall out of the valid 11404 // range, then we computed our trip count, otherwise wrap around or other 11405 // things must have happened. 11406 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 11407 if (Range.contains(Val->getValue())) 11408 return SE.getCouldNotCompute(); // Something strange happened 11409 11410 // Ensure that the previous value is in the range. This is a sanity check. 11411 assert(Range.contains( 11412 EvaluateConstantChrecAtConstant(this, 11413 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 11414 "Linear scev computation is off in a bad way!"); 11415 return SE.getConstant(ExitValue); 11416 } 11417 11418 if (isQuadratic()) { 11419 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 11420 return SE.getConstant(S.getValue()); 11421 } 11422 11423 return SE.getCouldNotCompute(); 11424 } 11425 11426 const SCEVAddRecExpr * 11427 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 11428 assert(getNumOperands() > 1 && "AddRec with zero step?"); 11429 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 11430 // but in this case we cannot guarantee that the value returned will be an 11431 // AddRec because SCEV does not have a fixed point where it stops 11432 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 11433 // may happen if we reach arithmetic depth limit while simplifying. So we 11434 // construct the returned value explicitly. 11435 SmallVector<const SCEV *, 3> Ops; 11436 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 11437 // (this + Step) is {A+B,+,B+C,+...,+,N}. 11438 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 11439 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 11440 // We know that the last operand is not a constant zero (otherwise it would 11441 // have been popped out earlier). This guarantees us that if the result has 11442 // the same last operand, then it will also not be popped out, meaning that 11443 // the returned value will be an AddRec. 11444 const SCEV *Last = getOperand(getNumOperands() - 1); 11445 assert(!Last->isZero() && "Recurrency with zero step?"); 11446 Ops.push_back(Last); 11447 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 11448 SCEV::FlagAnyWrap)); 11449 } 11450 11451 // Return true when S contains at least an undef value. 11452 static inline bool containsUndefs(const SCEV *S) { 11453 return SCEVExprContains(S, [](const SCEV *S) { 11454 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 11455 return isa<UndefValue>(SU->getValue()); 11456 return false; 11457 }); 11458 } 11459 11460 namespace { 11461 11462 // Collect all steps of SCEV expressions. 11463 struct SCEVCollectStrides { 11464 ScalarEvolution &SE; 11465 SmallVectorImpl<const SCEV *> &Strides; 11466 11467 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 11468 : SE(SE), Strides(S) {} 11469 11470 bool follow(const SCEV *S) { 11471 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 11472 Strides.push_back(AR->getStepRecurrence(SE)); 11473 return true; 11474 } 11475 11476 bool isDone() const { return false; } 11477 }; 11478 11479 // Collect all SCEVUnknown and SCEVMulExpr expressions. 11480 struct SCEVCollectTerms { 11481 SmallVectorImpl<const SCEV *> &Terms; 11482 11483 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 11484 11485 bool follow(const SCEV *S) { 11486 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 11487 isa<SCEVSignExtendExpr>(S)) { 11488 if (!containsUndefs(S)) 11489 Terms.push_back(S); 11490 11491 // Stop recursion: once we collected a term, do not walk its operands. 11492 return false; 11493 } 11494 11495 // Keep looking. 11496 return true; 11497 } 11498 11499 bool isDone() const { return false; } 11500 }; 11501 11502 // Check if a SCEV contains an AddRecExpr. 11503 struct SCEVHasAddRec { 11504 bool &ContainsAddRec; 11505 11506 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 11507 ContainsAddRec = false; 11508 } 11509 11510 bool follow(const SCEV *S) { 11511 if (isa<SCEVAddRecExpr>(S)) { 11512 ContainsAddRec = true; 11513 11514 // Stop recursion: once we collected a term, do not walk its operands. 11515 return false; 11516 } 11517 11518 // Keep looking. 11519 return true; 11520 } 11521 11522 bool isDone() const { return false; } 11523 }; 11524 11525 // Find factors that are multiplied with an expression that (possibly as a 11526 // subexpression) contains an AddRecExpr. In the expression: 11527 // 11528 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11529 // 11530 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11531 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11532 // parameters as they form a product with an induction variable. 11533 // 11534 // This collector expects all array size parameters to be in the same MulExpr. 11535 // It might be necessary to later add support for collecting parameters that are 11536 // spread over different nested MulExpr. 11537 struct SCEVCollectAddRecMultiplies { 11538 SmallVectorImpl<const SCEV *> &Terms; 11539 ScalarEvolution &SE; 11540 11541 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11542 : Terms(T), SE(SE) {} 11543 11544 bool follow(const SCEV *S) { 11545 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11546 bool HasAddRec = false; 11547 SmallVector<const SCEV *, 0> Operands; 11548 for (auto Op : Mul->operands()) { 11549 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11550 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11551 Operands.push_back(Op); 11552 } else if (Unknown) { 11553 HasAddRec = true; 11554 } else { 11555 bool ContainsAddRec = false; 11556 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11557 visitAll(Op, ContiansAddRec); 11558 HasAddRec |= ContainsAddRec; 11559 } 11560 } 11561 if (Operands.size() == 0) 11562 return true; 11563 11564 if (!HasAddRec) 11565 return false; 11566 11567 Terms.push_back(SE.getMulExpr(Operands)); 11568 // Stop recursion: once we collected a term, do not walk its operands. 11569 return false; 11570 } 11571 11572 // Keep looking. 11573 return true; 11574 } 11575 11576 bool isDone() const { return false; } 11577 }; 11578 11579 } // end anonymous namespace 11580 11581 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11582 /// two places: 11583 /// 1) The strides of AddRec expressions. 11584 /// 2) Unknowns that are multiplied with AddRec expressions. 11585 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11586 SmallVectorImpl<const SCEV *> &Terms) { 11587 SmallVector<const SCEV *, 4> Strides; 11588 SCEVCollectStrides StrideCollector(*this, Strides); 11589 visitAll(Expr, StrideCollector); 11590 11591 LLVM_DEBUG({ 11592 dbgs() << "Strides:\n"; 11593 for (const SCEV *S : Strides) 11594 dbgs() << *S << "\n"; 11595 }); 11596 11597 for (const SCEV *S : Strides) { 11598 SCEVCollectTerms TermCollector(Terms); 11599 visitAll(S, TermCollector); 11600 } 11601 11602 LLVM_DEBUG({ 11603 dbgs() << "Terms:\n"; 11604 for (const SCEV *T : Terms) 11605 dbgs() << *T << "\n"; 11606 }); 11607 11608 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11609 visitAll(Expr, MulCollector); 11610 } 11611 11612 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11613 SmallVectorImpl<const SCEV *> &Terms, 11614 SmallVectorImpl<const SCEV *> &Sizes) { 11615 int Last = Terms.size() - 1; 11616 const SCEV *Step = Terms[Last]; 11617 11618 // End of recursion. 11619 if (Last == 0) { 11620 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11621 SmallVector<const SCEV *, 2> Qs; 11622 for (const SCEV *Op : M->operands()) 11623 if (!isa<SCEVConstant>(Op)) 11624 Qs.push_back(Op); 11625 11626 Step = SE.getMulExpr(Qs); 11627 } 11628 11629 Sizes.push_back(Step); 11630 return true; 11631 } 11632 11633 for (const SCEV *&Term : Terms) { 11634 // Normalize the terms before the next call to findArrayDimensionsRec. 11635 const SCEV *Q, *R; 11636 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11637 11638 // Bail out when GCD does not evenly divide one of the terms. 11639 if (!R->isZero()) 11640 return false; 11641 11642 Term = Q; 11643 } 11644 11645 // Remove all SCEVConstants. 11646 erase_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }); 11647 11648 if (Terms.size() > 0) 11649 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11650 return false; 11651 11652 Sizes.push_back(Step); 11653 return true; 11654 } 11655 11656 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11657 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11658 for (const SCEV *T : Terms) 11659 if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); })) 11660 return true; 11661 11662 return false; 11663 } 11664 11665 // Return the number of product terms in S. 11666 static inline int numberOfTerms(const SCEV *S) { 11667 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11668 return Expr->getNumOperands(); 11669 return 1; 11670 } 11671 11672 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11673 if (isa<SCEVConstant>(T)) 11674 return nullptr; 11675 11676 if (isa<SCEVUnknown>(T)) 11677 return T; 11678 11679 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11680 SmallVector<const SCEV *, 2> Factors; 11681 for (const SCEV *Op : M->operands()) 11682 if (!isa<SCEVConstant>(Op)) 11683 Factors.push_back(Op); 11684 11685 return SE.getMulExpr(Factors); 11686 } 11687 11688 return T; 11689 } 11690 11691 /// Return the size of an element read or written by Inst. 11692 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11693 Type *Ty; 11694 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11695 Ty = Store->getValueOperand()->getType(); 11696 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11697 Ty = Load->getType(); 11698 else 11699 return nullptr; 11700 11701 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11702 return getSizeOfExpr(ETy, Ty); 11703 } 11704 11705 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11706 SmallVectorImpl<const SCEV *> &Sizes, 11707 const SCEV *ElementSize) { 11708 if (Terms.size() < 1 || !ElementSize) 11709 return; 11710 11711 // Early return when Terms do not contain parameters: we do not delinearize 11712 // non parametric SCEVs. 11713 if (!containsParameters(Terms)) 11714 return; 11715 11716 LLVM_DEBUG({ 11717 dbgs() << "Terms:\n"; 11718 for (const SCEV *T : Terms) 11719 dbgs() << *T << "\n"; 11720 }); 11721 11722 // Remove duplicates. 11723 array_pod_sort(Terms.begin(), Terms.end()); 11724 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11725 11726 // Put larger terms first. 11727 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11728 return numberOfTerms(LHS) > numberOfTerms(RHS); 11729 }); 11730 11731 // Try to divide all terms by the element size. If term is not divisible by 11732 // element size, proceed with the original term. 11733 for (const SCEV *&Term : Terms) { 11734 const SCEV *Q, *R; 11735 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11736 if (!Q->isZero()) 11737 Term = Q; 11738 } 11739 11740 SmallVector<const SCEV *, 4> NewTerms; 11741 11742 // Remove constant factors. 11743 for (const SCEV *T : Terms) 11744 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11745 NewTerms.push_back(NewT); 11746 11747 LLVM_DEBUG({ 11748 dbgs() << "Terms after sorting:\n"; 11749 for (const SCEV *T : NewTerms) 11750 dbgs() << *T << "\n"; 11751 }); 11752 11753 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11754 Sizes.clear(); 11755 return; 11756 } 11757 11758 // The last element to be pushed into Sizes is the size of an element. 11759 Sizes.push_back(ElementSize); 11760 11761 LLVM_DEBUG({ 11762 dbgs() << "Sizes:\n"; 11763 for (const SCEV *S : Sizes) 11764 dbgs() << *S << "\n"; 11765 }); 11766 } 11767 11768 void ScalarEvolution::computeAccessFunctions( 11769 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11770 SmallVectorImpl<const SCEV *> &Sizes) { 11771 // Early exit in case this SCEV is not an affine multivariate function. 11772 if (Sizes.empty()) 11773 return; 11774 11775 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11776 if (!AR->isAffine()) 11777 return; 11778 11779 const SCEV *Res = Expr; 11780 int Last = Sizes.size() - 1; 11781 for (int i = Last; i >= 0; i--) { 11782 const SCEV *Q, *R; 11783 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11784 11785 LLVM_DEBUG({ 11786 dbgs() << "Res: " << *Res << "\n"; 11787 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11788 dbgs() << "Res divided by Sizes[i]:\n"; 11789 dbgs() << "Quotient: " << *Q << "\n"; 11790 dbgs() << "Remainder: " << *R << "\n"; 11791 }); 11792 11793 Res = Q; 11794 11795 // Do not record the last subscript corresponding to the size of elements in 11796 // the array. 11797 if (i == Last) { 11798 11799 // Bail out if the remainder is too complex. 11800 if (isa<SCEVAddRecExpr>(R)) { 11801 Subscripts.clear(); 11802 Sizes.clear(); 11803 return; 11804 } 11805 11806 continue; 11807 } 11808 11809 // Record the access function for the current subscript. 11810 Subscripts.push_back(R); 11811 } 11812 11813 // Also push in last position the remainder of the last division: it will be 11814 // the access function of the innermost dimension. 11815 Subscripts.push_back(Res); 11816 11817 std::reverse(Subscripts.begin(), Subscripts.end()); 11818 11819 LLVM_DEBUG({ 11820 dbgs() << "Subscripts:\n"; 11821 for (const SCEV *S : Subscripts) 11822 dbgs() << *S << "\n"; 11823 }); 11824 } 11825 11826 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11827 /// sizes of an array access. Returns the remainder of the delinearization that 11828 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11829 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11830 /// expressions in the stride and base of a SCEV corresponding to the 11831 /// computation of a GCD (greatest common divisor) of base and stride. When 11832 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11833 /// 11834 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11835 /// 11836 /// void foo(long n, long m, long o, double A[n][m][o]) { 11837 /// 11838 /// for (long i = 0; i < n; i++) 11839 /// for (long j = 0; j < m; j++) 11840 /// for (long k = 0; k < o; k++) 11841 /// A[i][j][k] = 1.0; 11842 /// } 11843 /// 11844 /// the delinearization input is the following AddRec SCEV: 11845 /// 11846 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11847 /// 11848 /// From this SCEV, we are able to say that the base offset of the access is %A 11849 /// because it appears as an offset that does not divide any of the strides in 11850 /// the loops: 11851 /// 11852 /// CHECK: Base offset: %A 11853 /// 11854 /// and then SCEV->delinearize determines the size of some of the dimensions of 11855 /// the array as these are the multiples by which the strides are happening: 11856 /// 11857 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11858 /// 11859 /// Note that the outermost dimension remains of UnknownSize because there are 11860 /// no strides that would help identifying the size of the last dimension: when 11861 /// the array has been statically allocated, one could compute the size of that 11862 /// dimension by dividing the overall size of the array by the size of the known 11863 /// dimensions: %m * %o * 8. 11864 /// 11865 /// Finally delinearize provides the access functions for the array reference 11866 /// that does correspond to A[i][j][k] of the above C testcase: 11867 /// 11868 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11869 /// 11870 /// The testcases are checking the output of a function pass: 11871 /// DelinearizationPass that walks through all loads and stores of a function 11872 /// asking for the SCEV of the memory access with respect to all enclosing 11873 /// loops, calling SCEV->delinearize on that and printing the results. 11874 void ScalarEvolution::delinearize(const SCEV *Expr, 11875 SmallVectorImpl<const SCEV *> &Subscripts, 11876 SmallVectorImpl<const SCEV *> &Sizes, 11877 const SCEV *ElementSize) { 11878 // First step: collect parametric terms. 11879 SmallVector<const SCEV *, 4> Terms; 11880 collectParametricTerms(Expr, Terms); 11881 11882 if (Terms.empty()) 11883 return; 11884 11885 // Second step: find subscript sizes. 11886 findArrayDimensions(Terms, Sizes, ElementSize); 11887 11888 if (Sizes.empty()) 11889 return; 11890 11891 // Third step: compute the access functions for each subscript. 11892 computeAccessFunctions(Expr, Subscripts, Sizes); 11893 11894 if (Subscripts.empty()) 11895 return; 11896 11897 LLVM_DEBUG({ 11898 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11899 dbgs() << "ArrayDecl[UnknownSize]"; 11900 for (const SCEV *S : Sizes) 11901 dbgs() << "[" << *S << "]"; 11902 11903 dbgs() << "\nArrayRef"; 11904 for (const SCEV *S : Subscripts) 11905 dbgs() << "[" << *S << "]"; 11906 dbgs() << "\n"; 11907 }); 11908 } 11909 11910 bool ScalarEvolution::getIndexExpressionsFromGEP( 11911 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 11912 SmallVectorImpl<int> &Sizes) { 11913 assert(Subscripts.empty() && Sizes.empty() && 11914 "Expected output lists to be empty on entry to this function."); 11915 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 11916 Type *Ty = GEP->getPointerOperandType(); 11917 bool DroppedFirstDim = false; 11918 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 11919 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 11920 if (i == 1) { 11921 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 11922 Ty = PtrTy->getElementType(); 11923 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 11924 Ty = ArrayTy->getElementType(); 11925 } else { 11926 Subscripts.clear(); 11927 Sizes.clear(); 11928 return false; 11929 } 11930 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 11931 if (Const->getValue()->isZero()) { 11932 DroppedFirstDim = true; 11933 continue; 11934 } 11935 Subscripts.push_back(Expr); 11936 continue; 11937 } 11938 11939 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 11940 if (!ArrayTy) { 11941 Subscripts.clear(); 11942 Sizes.clear(); 11943 return false; 11944 } 11945 11946 Subscripts.push_back(Expr); 11947 if (!(DroppedFirstDim && i == 2)) 11948 Sizes.push_back(ArrayTy->getNumElements()); 11949 11950 Ty = ArrayTy->getElementType(); 11951 } 11952 return !Subscripts.empty(); 11953 } 11954 11955 //===----------------------------------------------------------------------===// 11956 // SCEVCallbackVH Class Implementation 11957 //===----------------------------------------------------------------------===// 11958 11959 void ScalarEvolution::SCEVCallbackVH::deleted() { 11960 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11961 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11962 SE->ConstantEvolutionLoopExitValue.erase(PN); 11963 SE->eraseValueFromMap(getValPtr()); 11964 // this now dangles! 11965 } 11966 11967 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11968 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11969 11970 // Forget all the expressions associated with users of the old value, 11971 // so that future queries will recompute the expressions using the new 11972 // value. 11973 Value *Old = getValPtr(); 11974 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11975 SmallPtrSet<User *, 8> Visited; 11976 while (!Worklist.empty()) { 11977 User *U = Worklist.pop_back_val(); 11978 // Deleting the Old value will cause this to dangle. Postpone 11979 // that until everything else is done. 11980 if (U == Old) 11981 continue; 11982 if (!Visited.insert(U).second) 11983 continue; 11984 if (PHINode *PN = dyn_cast<PHINode>(U)) 11985 SE->ConstantEvolutionLoopExitValue.erase(PN); 11986 SE->eraseValueFromMap(U); 11987 llvm::append_range(Worklist, U->users()); 11988 } 11989 // Delete the Old value. 11990 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11991 SE->ConstantEvolutionLoopExitValue.erase(PN); 11992 SE->eraseValueFromMap(Old); 11993 // this now dangles! 11994 } 11995 11996 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11997 : CallbackVH(V), SE(se) {} 11998 11999 //===----------------------------------------------------------------------===// 12000 // ScalarEvolution Class Implementation 12001 //===----------------------------------------------------------------------===// 12002 12003 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12004 AssumptionCache &AC, DominatorTree &DT, 12005 LoopInfo &LI) 12006 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12007 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12008 LoopDispositions(64), BlockDispositions(64) { 12009 // To use guards for proving predicates, we need to scan every instruction in 12010 // relevant basic blocks, and not just terminators. Doing this is a waste of 12011 // time if the IR does not actually contain any calls to 12012 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12013 // 12014 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12015 // to _add_ guards to the module when there weren't any before, and wants 12016 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12017 // efficient in lieu of being smart in that rather obscure case. 12018 12019 auto *GuardDecl = F.getParent()->getFunction( 12020 Intrinsic::getName(Intrinsic::experimental_guard)); 12021 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12022 } 12023 12024 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12025 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12026 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12027 ValueExprMap(std::move(Arg.ValueExprMap)), 12028 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12029 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12030 PendingMerges(std::move(Arg.PendingMerges)), 12031 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12032 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12033 PredicatedBackedgeTakenCounts( 12034 std::move(Arg.PredicatedBackedgeTakenCounts)), 12035 ConstantEvolutionLoopExitValue( 12036 std::move(Arg.ConstantEvolutionLoopExitValue)), 12037 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12038 LoopDispositions(std::move(Arg.LoopDispositions)), 12039 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12040 BlockDispositions(std::move(Arg.BlockDispositions)), 12041 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12042 SignedRanges(std::move(Arg.SignedRanges)), 12043 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12044 UniquePreds(std::move(Arg.UniquePreds)), 12045 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12046 LoopUsers(std::move(Arg.LoopUsers)), 12047 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12048 FirstUnknown(Arg.FirstUnknown) { 12049 Arg.FirstUnknown = nullptr; 12050 } 12051 12052 ScalarEvolution::~ScalarEvolution() { 12053 // Iterate through all the SCEVUnknown instances and call their 12054 // destructors, so that they release their references to their values. 12055 for (SCEVUnknown *U = FirstUnknown; U;) { 12056 SCEVUnknown *Tmp = U; 12057 U = U->Next; 12058 Tmp->~SCEVUnknown(); 12059 } 12060 FirstUnknown = nullptr; 12061 12062 ExprValueMap.clear(); 12063 ValueExprMap.clear(); 12064 HasRecMap.clear(); 12065 12066 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 12067 // that a loop had multiple computable exits. 12068 for (auto &BTCI : BackedgeTakenCounts) 12069 BTCI.second.clear(); 12070 for (auto &BTCI : PredicatedBackedgeTakenCounts) 12071 BTCI.second.clear(); 12072 12073 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12074 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12075 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12076 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12077 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12078 } 12079 12080 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12081 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12082 } 12083 12084 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12085 const Loop *L) { 12086 // Print all inner loops first 12087 for (Loop *I : *L) 12088 PrintLoopInfo(OS, SE, I); 12089 12090 OS << "Loop "; 12091 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12092 OS << ": "; 12093 12094 SmallVector<BasicBlock *, 8> ExitingBlocks; 12095 L->getExitingBlocks(ExitingBlocks); 12096 if (ExitingBlocks.size() != 1) 12097 OS << "<multiple exits> "; 12098 12099 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12100 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12101 else 12102 OS << "Unpredictable backedge-taken count.\n"; 12103 12104 if (ExitingBlocks.size() > 1) 12105 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12106 OS << " exit count for " << ExitingBlock->getName() << ": " 12107 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12108 } 12109 12110 OS << "Loop "; 12111 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12112 OS << ": "; 12113 12114 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12115 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12116 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12117 OS << ", actual taken count either this or zero."; 12118 } else { 12119 OS << "Unpredictable max backedge-taken count. "; 12120 } 12121 12122 OS << "\n" 12123 "Loop "; 12124 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12125 OS << ": "; 12126 12127 SCEVUnionPredicate Pred; 12128 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12129 if (!isa<SCEVCouldNotCompute>(PBT)) { 12130 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12131 OS << " Predicates:\n"; 12132 Pred.print(OS, 4); 12133 } else { 12134 OS << "Unpredictable predicated backedge-taken count. "; 12135 } 12136 OS << "\n"; 12137 12138 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12139 OS << "Loop "; 12140 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12141 OS << ": "; 12142 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12143 } 12144 } 12145 12146 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12147 switch (LD) { 12148 case ScalarEvolution::LoopVariant: 12149 return "Variant"; 12150 case ScalarEvolution::LoopInvariant: 12151 return "Invariant"; 12152 case ScalarEvolution::LoopComputable: 12153 return "Computable"; 12154 } 12155 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12156 } 12157 12158 void ScalarEvolution::print(raw_ostream &OS) const { 12159 // ScalarEvolution's implementation of the print method is to print 12160 // out SCEV values of all instructions that are interesting. Doing 12161 // this potentially causes it to create new SCEV objects though, 12162 // which technically conflicts with the const qualifier. This isn't 12163 // observable from outside the class though, so casting away the 12164 // const isn't dangerous. 12165 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12166 12167 if (ClassifyExpressions) { 12168 OS << "Classifying expressions for: "; 12169 F.printAsOperand(OS, /*PrintType=*/false); 12170 OS << "\n"; 12171 for (Instruction &I : instructions(F)) 12172 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12173 OS << I << '\n'; 12174 OS << " --> "; 12175 const SCEV *SV = SE.getSCEV(&I); 12176 SV->print(OS); 12177 if (!isa<SCEVCouldNotCompute>(SV)) { 12178 OS << " U: "; 12179 SE.getUnsignedRange(SV).print(OS); 12180 OS << " S: "; 12181 SE.getSignedRange(SV).print(OS); 12182 } 12183 12184 const Loop *L = LI.getLoopFor(I.getParent()); 12185 12186 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12187 if (AtUse != SV) { 12188 OS << " --> "; 12189 AtUse->print(OS); 12190 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12191 OS << " U: "; 12192 SE.getUnsignedRange(AtUse).print(OS); 12193 OS << " S: "; 12194 SE.getSignedRange(AtUse).print(OS); 12195 } 12196 } 12197 12198 if (L) { 12199 OS << "\t\t" "Exits: "; 12200 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12201 if (!SE.isLoopInvariant(ExitValue, L)) { 12202 OS << "<<Unknown>>"; 12203 } else { 12204 OS << *ExitValue; 12205 } 12206 12207 bool First = true; 12208 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12209 if (First) { 12210 OS << "\t\t" "LoopDispositions: { "; 12211 First = false; 12212 } else { 12213 OS << ", "; 12214 } 12215 12216 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12217 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12218 } 12219 12220 for (auto *InnerL : depth_first(L)) { 12221 if (InnerL == L) 12222 continue; 12223 if (First) { 12224 OS << "\t\t" "LoopDispositions: { "; 12225 First = false; 12226 } else { 12227 OS << ", "; 12228 } 12229 12230 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12231 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12232 } 12233 12234 OS << " }"; 12235 } 12236 12237 OS << "\n"; 12238 } 12239 } 12240 12241 OS << "Determining loop execution counts for: "; 12242 F.printAsOperand(OS, /*PrintType=*/false); 12243 OS << "\n"; 12244 for (Loop *I : LI) 12245 PrintLoopInfo(OS, &SE, I); 12246 } 12247 12248 ScalarEvolution::LoopDisposition 12249 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12250 auto &Values = LoopDispositions[S]; 12251 for (auto &V : Values) { 12252 if (V.getPointer() == L) 12253 return V.getInt(); 12254 } 12255 Values.emplace_back(L, LoopVariant); 12256 LoopDisposition D = computeLoopDisposition(S, L); 12257 auto &Values2 = LoopDispositions[S]; 12258 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12259 if (V.getPointer() == L) { 12260 V.setInt(D); 12261 break; 12262 } 12263 } 12264 return D; 12265 } 12266 12267 ScalarEvolution::LoopDisposition 12268 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12269 switch (S->getSCEVType()) { 12270 case scConstant: 12271 return LoopInvariant; 12272 case scPtrToInt: 12273 case scTruncate: 12274 case scZeroExtend: 12275 case scSignExtend: 12276 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12277 case scAddRecExpr: { 12278 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12279 12280 // If L is the addrec's loop, it's computable. 12281 if (AR->getLoop() == L) 12282 return LoopComputable; 12283 12284 // Add recurrences are never invariant in the function-body (null loop). 12285 if (!L) 12286 return LoopVariant; 12287 12288 // Everything that is not defined at loop entry is variant. 12289 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12290 return LoopVariant; 12291 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12292 " dominate the contained loop's header?"); 12293 12294 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12295 if (AR->getLoop()->contains(L)) 12296 return LoopInvariant; 12297 12298 // This recurrence is variant w.r.t. L if any of its operands 12299 // are variant. 12300 for (auto *Op : AR->operands()) 12301 if (!isLoopInvariant(Op, L)) 12302 return LoopVariant; 12303 12304 // Otherwise it's loop-invariant. 12305 return LoopInvariant; 12306 } 12307 case scAddExpr: 12308 case scMulExpr: 12309 case scUMaxExpr: 12310 case scSMaxExpr: 12311 case scUMinExpr: 12312 case scSMinExpr: { 12313 bool HasVarying = false; 12314 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12315 LoopDisposition D = getLoopDisposition(Op, L); 12316 if (D == LoopVariant) 12317 return LoopVariant; 12318 if (D == LoopComputable) 12319 HasVarying = true; 12320 } 12321 return HasVarying ? LoopComputable : LoopInvariant; 12322 } 12323 case scUDivExpr: { 12324 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12325 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12326 if (LD == LoopVariant) 12327 return LoopVariant; 12328 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12329 if (RD == LoopVariant) 12330 return LoopVariant; 12331 return (LD == LoopInvariant && RD == LoopInvariant) ? 12332 LoopInvariant : LoopComputable; 12333 } 12334 case scUnknown: 12335 // All non-instruction values are loop invariant. All instructions are loop 12336 // invariant if they are not contained in the specified loop. 12337 // Instructions are never considered invariant in the function body 12338 // (null loop) because they are defined within the "loop". 12339 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12340 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12341 return LoopInvariant; 12342 case scCouldNotCompute: 12343 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12344 } 12345 llvm_unreachable("Unknown SCEV kind!"); 12346 } 12347 12348 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 12349 return getLoopDisposition(S, L) == LoopInvariant; 12350 } 12351 12352 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 12353 return getLoopDisposition(S, L) == LoopComputable; 12354 } 12355 12356 ScalarEvolution::BlockDisposition 12357 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12358 auto &Values = BlockDispositions[S]; 12359 for (auto &V : Values) { 12360 if (V.getPointer() == BB) 12361 return V.getInt(); 12362 } 12363 Values.emplace_back(BB, DoesNotDominateBlock); 12364 BlockDisposition D = computeBlockDisposition(S, BB); 12365 auto &Values2 = BlockDispositions[S]; 12366 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12367 if (V.getPointer() == BB) { 12368 V.setInt(D); 12369 break; 12370 } 12371 } 12372 return D; 12373 } 12374 12375 ScalarEvolution::BlockDisposition 12376 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12377 switch (S->getSCEVType()) { 12378 case scConstant: 12379 return ProperlyDominatesBlock; 12380 case scPtrToInt: 12381 case scTruncate: 12382 case scZeroExtend: 12383 case scSignExtend: 12384 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 12385 case scAddRecExpr: { 12386 // This uses a "dominates" query instead of "properly dominates" query 12387 // to test for proper dominance too, because the instruction which 12388 // produces the addrec's value is a PHI, and a PHI effectively properly 12389 // dominates its entire containing block. 12390 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12391 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 12392 return DoesNotDominateBlock; 12393 12394 // Fall through into SCEVNAryExpr handling. 12395 LLVM_FALLTHROUGH; 12396 } 12397 case scAddExpr: 12398 case scMulExpr: 12399 case scUMaxExpr: 12400 case scSMaxExpr: 12401 case scUMinExpr: 12402 case scSMinExpr: { 12403 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12404 bool Proper = true; 12405 for (const SCEV *NAryOp : NAry->operands()) { 12406 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12407 if (D == DoesNotDominateBlock) 12408 return DoesNotDominateBlock; 12409 if (D == DominatesBlock) 12410 Proper = false; 12411 } 12412 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12413 } 12414 case scUDivExpr: { 12415 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12416 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12417 BlockDisposition LD = getBlockDisposition(LHS, BB); 12418 if (LD == DoesNotDominateBlock) 12419 return DoesNotDominateBlock; 12420 BlockDisposition RD = getBlockDisposition(RHS, BB); 12421 if (RD == DoesNotDominateBlock) 12422 return DoesNotDominateBlock; 12423 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12424 ProperlyDominatesBlock : DominatesBlock; 12425 } 12426 case scUnknown: 12427 if (Instruction *I = 12428 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12429 if (I->getParent() == BB) 12430 return DominatesBlock; 12431 if (DT.properlyDominates(I->getParent(), BB)) 12432 return ProperlyDominatesBlock; 12433 return DoesNotDominateBlock; 12434 } 12435 return ProperlyDominatesBlock; 12436 case scCouldNotCompute: 12437 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12438 } 12439 llvm_unreachable("Unknown SCEV kind!"); 12440 } 12441 12442 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12443 return getBlockDisposition(S, BB) >= DominatesBlock; 12444 } 12445 12446 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12447 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12448 } 12449 12450 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12451 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12452 } 12453 12454 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 12455 auto IsS = [&](const SCEV *X) { return S == X; }; 12456 auto ContainsS = [&](const SCEV *X) { 12457 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 12458 }; 12459 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 12460 } 12461 12462 void 12463 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12464 ValuesAtScopes.erase(S); 12465 LoopDispositions.erase(S); 12466 BlockDispositions.erase(S); 12467 UnsignedRanges.erase(S); 12468 SignedRanges.erase(S); 12469 ExprValueMap.erase(S); 12470 HasRecMap.erase(S); 12471 MinTrailingZerosCache.erase(S); 12472 12473 for (auto I = PredicatedSCEVRewrites.begin(); 12474 I != PredicatedSCEVRewrites.end();) { 12475 std::pair<const SCEV *, const Loop *> Entry = I->first; 12476 if (Entry.first == S) 12477 PredicatedSCEVRewrites.erase(I++); 12478 else 12479 ++I; 12480 } 12481 12482 auto RemoveSCEVFromBackedgeMap = 12483 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12484 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12485 BackedgeTakenInfo &BEInfo = I->second; 12486 if (BEInfo.hasOperand(S, this)) { 12487 BEInfo.clear(); 12488 Map.erase(I++); 12489 } else 12490 ++I; 12491 } 12492 }; 12493 12494 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12495 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12496 } 12497 12498 void 12499 ScalarEvolution::getUsedLoops(const SCEV *S, 12500 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12501 struct FindUsedLoops { 12502 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12503 : LoopsUsed(LoopsUsed) {} 12504 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12505 bool follow(const SCEV *S) { 12506 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12507 LoopsUsed.insert(AR->getLoop()); 12508 return true; 12509 } 12510 12511 bool isDone() const { return false; } 12512 }; 12513 12514 FindUsedLoops F(LoopsUsed); 12515 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12516 } 12517 12518 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12519 SmallPtrSet<const Loop *, 8> LoopsUsed; 12520 getUsedLoops(S, LoopsUsed); 12521 for (auto *L : LoopsUsed) 12522 LoopUsers[L].push_back(S); 12523 } 12524 12525 void ScalarEvolution::verify() const { 12526 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12527 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12528 12529 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12530 12531 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12532 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12533 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12534 12535 const SCEV *visitConstant(const SCEVConstant *Constant) { 12536 return SE.getConstant(Constant->getAPInt()); 12537 } 12538 12539 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12540 return SE.getUnknown(Expr->getValue()); 12541 } 12542 12543 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12544 return SE.getCouldNotCompute(); 12545 } 12546 }; 12547 12548 SCEVMapper SCM(SE2); 12549 12550 while (!LoopStack.empty()) { 12551 auto *L = LoopStack.pop_back_val(); 12552 llvm::append_range(LoopStack, *L); 12553 12554 auto *CurBECount = SCM.visit( 12555 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12556 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12557 12558 if (CurBECount == SE2.getCouldNotCompute() || 12559 NewBECount == SE2.getCouldNotCompute()) { 12560 // NB! This situation is legal, but is very suspicious -- whatever pass 12561 // change the loop to make a trip count go from could not compute to 12562 // computable or vice-versa *should have* invalidated SCEV. However, we 12563 // choose not to assert here (for now) since we don't want false 12564 // positives. 12565 continue; 12566 } 12567 12568 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12569 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12570 // not propagate undef aggressively). This means we can (and do) fail 12571 // verification in cases where a transform makes the trip count of a loop 12572 // go from "undef" to "undef+1" (say). The transform is fine, since in 12573 // both cases the loop iterates "undef" times, but SCEV thinks we 12574 // increased the trip count of the loop by 1 incorrectly. 12575 continue; 12576 } 12577 12578 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12579 SE.getTypeSizeInBits(NewBECount->getType())) 12580 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12581 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12582 SE.getTypeSizeInBits(NewBECount->getType())) 12583 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12584 12585 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12586 12587 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12588 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12589 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12590 dbgs() << "Old: " << *CurBECount << "\n"; 12591 dbgs() << "New: " << *NewBECount << "\n"; 12592 dbgs() << "Delta: " << *Delta << "\n"; 12593 std::abort(); 12594 } 12595 } 12596 12597 // Collect all valid loops currently in LoopInfo. 12598 SmallPtrSet<Loop *, 32> ValidLoops; 12599 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12600 while (!Worklist.empty()) { 12601 Loop *L = Worklist.pop_back_val(); 12602 if (ValidLoops.contains(L)) 12603 continue; 12604 ValidLoops.insert(L); 12605 Worklist.append(L->begin(), L->end()); 12606 } 12607 // Check for SCEV expressions referencing invalid/deleted loops. 12608 for (auto &KV : ValueExprMap) { 12609 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12610 if (!AR) 12611 continue; 12612 assert(ValidLoops.contains(AR->getLoop()) && 12613 "AddRec references invalid loop"); 12614 } 12615 } 12616 12617 bool ScalarEvolution::invalidate( 12618 Function &F, const PreservedAnalyses &PA, 12619 FunctionAnalysisManager::Invalidator &Inv) { 12620 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12621 // of its dependencies is invalidated. 12622 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12623 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12624 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12625 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12626 Inv.invalidate<LoopAnalysis>(F, PA); 12627 } 12628 12629 AnalysisKey ScalarEvolutionAnalysis::Key; 12630 12631 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12632 FunctionAnalysisManager &AM) { 12633 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12634 AM.getResult<AssumptionAnalysis>(F), 12635 AM.getResult<DominatorTreeAnalysis>(F), 12636 AM.getResult<LoopAnalysis>(F)); 12637 } 12638 12639 PreservedAnalyses 12640 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12641 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12642 return PreservedAnalyses::all(); 12643 } 12644 12645 PreservedAnalyses 12646 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12647 // For compatibility with opt's -analyze feature under legacy pass manager 12648 // which was not ported to NPM. This keeps tests using 12649 // update_analyze_test_checks.py working. 12650 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12651 << F.getName() << "':\n"; 12652 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12653 return PreservedAnalyses::all(); 12654 } 12655 12656 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12657 "Scalar Evolution Analysis", false, true) 12658 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12659 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12660 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12661 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12662 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12663 "Scalar Evolution Analysis", false, true) 12664 12665 char ScalarEvolutionWrapperPass::ID = 0; 12666 12667 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12668 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12669 } 12670 12671 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12672 SE.reset(new ScalarEvolution( 12673 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12674 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12675 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12676 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12677 return false; 12678 } 12679 12680 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12681 12682 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12683 SE->print(OS); 12684 } 12685 12686 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12687 if (!VerifySCEV) 12688 return; 12689 12690 SE->verify(); 12691 } 12692 12693 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12694 AU.setPreservesAll(); 12695 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12696 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12697 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12698 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12699 } 12700 12701 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12702 const SCEV *RHS) { 12703 FoldingSetNodeID ID; 12704 assert(LHS->getType() == RHS->getType() && 12705 "Type mismatch between LHS and RHS"); 12706 // Unique this node based on the arguments 12707 ID.AddInteger(SCEVPredicate::P_Equal); 12708 ID.AddPointer(LHS); 12709 ID.AddPointer(RHS); 12710 void *IP = nullptr; 12711 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12712 return S; 12713 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12714 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12715 UniquePreds.InsertNode(Eq, IP); 12716 return Eq; 12717 } 12718 12719 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12720 const SCEVAddRecExpr *AR, 12721 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12722 FoldingSetNodeID ID; 12723 // Unique this node based on the arguments 12724 ID.AddInteger(SCEVPredicate::P_Wrap); 12725 ID.AddPointer(AR); 12726 ID.AddInteger(AddedFlags); 12727 void *IP = nullptr; 12728 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12729 return S; 12730 auto *OF = new (SCEVAllocator) 12731 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12732 UniquePreds.InsertNode(OF, IP); 12733 return OF; 12734 } 12735 12736 namespace { 12737 12738 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12739 public: 12740 12741 /// Rewrites \p S in the context of a loop L and the SCEV predication 12742 /// infrastructure. 12743 /// 12744 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12745 /// equivalences present in \p Pred. 12746 /// 12747 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12748 /// \p NewPreds such that the result will be an AddRecExpr. 12749 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12750 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12751 SCEVUnionPredicate *Pred) { 12752 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12753 return Rewriter.visit(S); 12754 } 12755 12756 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12757 if (Pred) { 12758 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12759 for (auto *Pred : ExprPreds) 12760 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12761 if (IPred->getLHS() == Expr) 12762 return IPred->getRHS(); 12763 } 12764 return convertToAddRecWithPreds(Expr); 12765 } 12766 12767 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12768 const SCEV *Operand = visit(Expr->getOperand()); 12769 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12770 if (AR && AR->getLoop() == L && AR->isAffine()) { 12771 // This couldn't be folded because the operand didn't have the nuw 12772 // flag. Add the nusw flag as an assumption that we could make. 12773 const SCEV *Step = AR->getStepRecurrence(SE); 12774 Type *Ty = Expr->getType(); 12775 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12776 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12777 SE.getSignExtendExpr(Step, Ty), L, 12778 AR->getNoWrapFlags()); 12779 } 12780 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12781 } 12782 12783 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12784 const SCEV *Operand = visit(Expr->getOperand()); 12785 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12786 if (AR && AR->getLoop() == L && AR->isAffine()) { 12787 // This couldn't be folded because the operand didn't have the nsw 12788 // flag. Add the nssw flag as an assumption that we could make. 12789 const SCEV *Step = AR->getStepRecurrence(SE); 12790 Type *Ty = Expr->getType(); 12791 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12792 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12793 SE.getSignExtendExpr(Step, Ty), L, 12794 AR->getNoWrapFlags()); 12795 } 12796 return SE.getSignExtendExpr(Operand, Expr->getType()); 12797 } 12798 12799 private: 12800 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12801 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12802 SCEVUnionPredicate *Pred) 12803 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12804 12805 bool addOverflowAssumption(const SCEVPredicate *P) { 12806 if (!NewPreds) { 12807 // Check if we've already made this assumption. 12808 return Pred && Pred->implies(P); 12809 } 12810 NewPreds->insert(P); 12811 return true; 12812 } 12813 12814 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12815 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12816 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12817 return addOverflowAssumption(A); 12818 } 12819 12820 // If \p Expr represents a PHINode, we try to see if it can be represented 12821 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12822 // to add this predicate as a runtime overflow check, we return the AddRec. 12823 // If \p Expr does not meet these conditions (is not a PHI node, or we 12824 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12825 // return \p Expr. 12826 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12827 if (!isa<PHINode>(Expr->getValue())) 12828 return Expr; 12829 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12830 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12831 if (!PredicatedRewrite) 12832 return Expr; 12833 for (auto *P : PredicatedRewrite->second){ 12834 // Wrap predicates from outer loops are not supported. 12835 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12836 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12837 if (L != AR->getLoop()) 12838 return Expr; 12839 } 12840 if (!addOverflowAssumption(P)) 12841 return Expr; 12842 } 12843 return PredicatedRewrite->first; 12844 } 12845 12846 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12847 SCEVUnionPredicate *Pred; 12848 const Loop *L; 12849 }; 12850 12851 } // end anonymous namespace 12852 12853 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12854 SCEVUnionPredicate &Preds) { 12855 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12856 } 12857 12858 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12859 const SCEV *S, const Loop *L, 12860 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12861 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12862 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12863 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12864 12865 if (!AddRec) 12866 return nullptr; 12867 12868 // Since the transformation was successful, we can now transfer the SCEV 12869 // predicates. 12870 for (auto *P : TransformPreds) 12871 Preds.insert(P); 12872 12873 return AddRec; 12874 } 12875 12876 /// SCEV predicates 12877 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12878 SCEVPredicateKind Kind) 12879 : FastID(ID), Kind(Kind) {} 12880 12881 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12882 const SCEV *LHS, const SCEV *RHS) 12883 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12884 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12885 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12886 } 12887 12888 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12889 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12890 12891 if (!Op) 12892 return false; 12893 12894 return Op->LHS == LHS && Op->RHS == RHS; 12895 } 12896 12897 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12898 12899 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12900 12901 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12902 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12903 } 12904 12905 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12906 const SCEVAddRecExpr *AR, 12907 IncrementWrapFlags Flags) 12908 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12909 12910 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12911 12912 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12913 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12914 12915 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12916 } 12917 12918 bool SCEVWrapPredicate::isAlwaysTrue() const { 12919 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12920 IncrementWrapFlags IFlags = Flags; 12921 12922 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12923 IFlags = clearFlags(IFlags, IncrementNSSW); 12924 12925 return IFlags == IncrementAnyWrap; 12926 } 12927 12928 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12929 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12930 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12931 OS << "<nusw>"; 12932 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12933 OS << "<nssw>"; 12934 OS << "\n"; 12935 } 12936 12937 SCEVWrapPredicate::IncrementWrapFlags 12938 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12939 ScalarEvolution &SE) { 12940 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12941 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12942 12943 // We can safely transfer the NSW flag as NSSW. 12944 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12945 ImpliedFlags = IncrementNSSW; 12946 12947 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12948 // If the increment is positive, the SCEV NUW flag will also imply the 12949 // WrapPredicate NUSW flag. 12950 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12951 if (Step->getValue()->getValue().isNonNegative()) 12952 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12953 } 12954 12955 return ImpliedFlags; 12956 } 12957 12958 /// Union predicates don't get cached so create a dummy set ID for it. 12959 SCEVUnionPredicate::SCEVUnionPredicate() 12960 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12961 12962 bool SCEVUnionPredicate::isAlwaysTrue() const { 12963 return all_of(Preds, 12964 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12965 } 12966 12967 ArrayRef<const SCEVPredicate *> 12968 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12969 auto I = SCEVToPreds.find(Expr); 12970 if (I == SCEVToPreds.end()) 12971 return ArrayRef<const SCEVPredicate *>(); 12972 return I->second; 12973 } 12974 12975 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12976 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12977 return all_of(Set->Preds, 12978 [this](const SCEVPredicate *I) { return this->implies(I); }); 12979 12980 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12981 if (ScevPredsIt == SCEVToPreds.end()) 12982 return false; 12983 auto &SCEVPreds = ScevPredsIt->second; 12984 12985 return any_of(SCEVPreds, 12986 [N](const SCEVPredicate *I) { return I->implies(N); }); 12987 } 12988 12989 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12990 12991 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12992 for (auto Pred : Preds) 12993 Pred->print(OS, Depth); 12994 } 12995 12996 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12997 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12998 for (auto Pred : Set->Preds) 12999 add(Pred); 13000 return; 13001 } 13002 13003 if (implies(N)) 13004 return; 13005 13006 const SCEV *Key = N->getExpr(); 13007 assert(Key && "Only SCEVUnionPredicate doesn't have an " 13008 " associated expression!"); 13009 13010 SCEVToPreds[Key].push_back(N); 13011 Preds.push_back(N); 13012 } 13013 13014 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 13015 Loop &L) 13016 : SE(SE), L(L) {} 13017 13018 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 13019 const SCEV *Expr = SE.getSCEV(V); 13020 RewriteEntry &Entry = RewriteMap[Expr]; 13021 13022 // If we already have an entry and the version matches, return it. 13023 if (Entry.second && Generation == Entry.first) 13024 return Entry.second; 13025 13026 // We found an entry but it's stale. Rewrite the stale entry 13027 // according to the current predicate. 13028 if (Entry.second) 13029 Expr = Entry.second; 13030 13031 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 13032 Entry = {Generation, NewSCEV}; 13033 13034 return NewSCEV; 13035 } 13036 13037 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13038 if (!BackedgeCount) { 13039 SCEVUnionPredicate BackedgePred; 13040 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 13041 addPredicate(BackedgePred); 13042 } 13043 return BackedgeCount; 13044 } 13045 13046 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13047 if (Preds.implies(&Pred)) 13048 return; 13049 Preds.add(&Pred); 13050 updateGeneration(); 13051 } 13052 13053 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 13054 return Preds; 13055 } 13056 13057 void PredicatedScalarEvolution::updateGeneration() { 13058 // If the generation number wrapped recompute everything. 13059 if (++Generation == 0) { 13060 for (auto &II : RewriteMap) { 13061 const SCEV *Rewritten = II.second.second; 13062 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 13063 } 13064 } 13065 } 13066 13067 void PredicatedScalarEvolution::setNoOverflow( 13068 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13069 const SCEV *Expr = getSCEV(V); 13070 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13071 13072 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13073 13074 // Clear the statically implied flags. 13075 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13076 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13077 13078 auto II = FlagsMap.insert({V, Flags}); 13079 if (!II.second) 13080 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13081 } 13082 13083 bool PredicatedScalarEvolution::hasNoOverflow( 13084 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13085 const SCEV *Expr = getSCEV(V); 13086 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13087 13088 Flags = SCEVWrapPredicate::clearFlags( 13089 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13090 13091 auto II = FlagsMap.find(V); 13092 13093 if (II != FlagsMap.end()) 13094 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13095 13096 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13097 } 13098 13099 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13100 const SCEV *Expr = this->getSCEV(V); 13101 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13102 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13103 13104 if (!New) 13105 return nullptr; 13106 13107 for (auto *P : NewPreds) 13108 Preds.add(P); 13109 13110 updateGeneration(); 13111 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13112 return New; 13113 } 13114 13115 PredicatedScalarEvolution::PredicatedScalarEvolution( 13116 const PredicatedScalarEvolution &Init) 13117 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13118 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13119 for (auto I : Init.FlagsMap) 13120 FlagsMap.insert(I); 13121 } 13122 13123 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13124 // For each block. 13125 for (auto *BB : L.getBlocks()) 13126 for (auto &I : *BB) { 13127 if (!SE.isSCEVable(I.getType())) 13128 continue; 13129 13130 auto *Expr = SE.getSCEV(&I); 13131 auto II = RewriteMap.find(Expr); 13132 13133 if (II == RewriteMap.end()) 13134 continue; 13135 13136 // Don't print things that are not interesting. 13137 if (II->second.second == Expr) 13138 continue; 13139 13140 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13141 OS.indent(Depth + 2) << *Expr << "\n"; 13142 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13143 } 13144 } 13145 13146 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13147 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13148 // for URem with constant power-of-2 second operands. 13149 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13150 // 4, A / B becomes X / 8). 13151 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13152 const SCEV *&RHS) { 13153 // Try to match 'zext (trunc A to iB) to iY', which is used 13154 // for URem with constant power-of-2 second operands. Make sure the size of 13155 // the operand A matches the size of the whole expressions. 13156 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13157 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13158 LHS = Trunc->getOperand(); 13159 if (LHS->getType() != Expr->getType()) 13160 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13161 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13162 << getTypeSizeInBits(Trunc->getType())); 13163 return true; 13164 } 13165 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13166 if (Add == nullptr || Add->getNumOperands() != 2) 13167 return false; 13168 13169 const SCEV *A = Add->getOperand(1); 13170 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13171 13172 if (Mul == nullptr) 13173 return false; 13174 13175 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13176 // (SomeExpr + (-(SomeExpr / B) * B)). 13177 if (Expr == getURemExpr(A, B)) { 13178 LHS = A; 13179 RHS = B; 13180 return true; 13181 } 13182 return false; 13183 }; 13184 13185 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13186 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13187 return MatchURemWithDivisor(Mul->getOperand(1)) || 13188 MatchURemWithDivisor(Mul->getOperand(2)); 13189 13190 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13191 if (Mul->getNumOperands() == 2) 13192 return MatchURemWithDivisor(Mul->getOperand(1)) || 13193 MatchURemWithDivisor(Mul->getOperand(0)) || 13194 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 13195 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 13196 return false; 13197 } 13198 13199 const SCEV * 13200 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 13201 SmallVector<BasicBlock*, 16> ExitingBlocks; 13202 L->getExitingBlocks(ExitingBlocks); 13203 13204 // Form an expression for the maximum exit count possible for this loop. We 13205 // merge the max and exact information to approximate a version of 13206 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 13207 SmallVector<const SCEV*, 4> ExitCounts; 13208 for (BasicBlock *ExitingBB : ExitingBlocks) { 13209 const SCEV *ExitCount = getExitCount(L, ExitingBB); 13210 if (isa<SCEVCouldNotCompute>(ExitCount)) 13211 ExitCount = getExitCount(L, ExitingBB, 13212 ScalarEvolution::ConstantMaximum); 13213 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 13214 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 13215 "We should only have known counts for exiting blocks that " 13216 "dominate latch!"); 13217 ExitCounts.push_back(ExitCount); 13218 } 13219 } 13220 if (ExitCounts.empty()) 13221 return getCouldNotCompute(); 13222 return getUMinFromMismatchedTypes(ExitCounts); 13223 } 13224 13225 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 13226 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 13227 /// we cannot guarantee that the replacement is loop invariant in the loop of 13228 /// the AddRec. 13229 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 13230 ValueToSCEVMapTy ⤅ 13231 13232 public: 13233 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 13234 : SCEVRewriteVisitor(SE), Map(M) {} 13235 13236 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 13237 13238 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13239 auto I = Map.find(Expr->getValue()); 13240 if (I == Map.end()) 13241 return Expr; 13242 return I->second; 13243 } 13244 }; 13245 13246 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 13247 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 13248 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 13249 if (!isa<SCEVUnknown>(LHS)) { 13250 std::swap(LHS, RHS); 13251 Predicate = CmpInst::getSwappedPredicate(Predicate); 13252 } 13253 13254 // For now, limit to conditions that provide information about unknown 13255 // expressions. 13256 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 13257 if (!LHSUnknown) 13258 return; 13259 13260 // TODO: use information from more predicates. 13261 switch (Predicate) { 13262 case CmpInst::ICMP_ULT: { 13263 if (!containsAddRecurrence(RHS)) { 13264 const SCEV *Base = LHS; 13265 auto I = RewriteMap.find(LHSUnknown->getValue()); 13266 if (I != RewriteMap.end()) 13267 Base = I->second; 13268 13269 RewriteMap[LHSUnknown->getValue()] = 13270 getUMinExpr(Base, getMinusSCEV(RHS, getOne(RHS->getType()))); 13271 } 13272 break; 13273 } 13274 case CmpInst::ICMP_ULE: { 13275 if (!containsAddRecurrence(RHS)) { 13276 const SCEV *Base = LHS; 13277 auto I = RewriteMap.find(LHSUnknown->getValue()); 13278 if (I != RewriteMap.end()) 13279 Base = I->second; 13280 RewriteMap[LHSUnknown->getValue()] = getUMinExpr(Base, RHS); 13281 } 13282 break; 13283 } 13284 case CmpInst::ICMP_EQ: 13285 if (isa<SCEVConstant>(RHS)) 13286 RewriteMap[LHSUnknown->getValue()] = RHS; 13287 break; 13288 case CmpInst::ICMP_NE: 13289 if (isa<SCEVConstant>(RHS) && 13290 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 13291 RewriteMap[LHSUnknown->getValue()] = 13292 getUMaxExpr(LHS, getOne(RHS->getType())); 13293 break; 13294 default: 13295 break; 13296 } 13297 }; 13298 // Starting at the loop predecessor, climb up the predecessor chain, as long 13299 // as there are predecessors that can be found that have unique successors 13300 // leading to the original header. 13301 // TODO: share this logic with isLoopEntryGuardedByCond. 13302 ValueToSCEVMapTy RewriteMap; 13303 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 13304 L->getLoopPredecessor(), L->getHeader()); 13305 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 13306 13307 const BranchInst *LoopEntryPredicate = 13308 dyn_cast<BranchInst>(Pair.first->getTerminator()); 13309 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 13310 continue; 13311 13312 // TODO: use information from more complex conditions, e.g. AND expressions. 13313 auto *Cmp = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition()); 13314 if (!Cmp) 13315 continue; 13316 13317 auto Predicate = Cmp->getPredicate(); 13318 if (LoopEntryPredicate->getSuccessor(1) == Pair.second) 13319 Predicate = CmpInst::getInversePredicate(Predicate); 13320 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 13321 getSCEV(Cmp->getOperand(1)), RewriteMap); 13322 } 13323 13324 // Also collect information from assumptions dominating the loop. 13325 for (auto &AssumeVH : AC.assumptions()) { 13326 if (!AssumeVH) 13327 continue; 13328 auto *AssumeI = cast<CallInst>(AssumeVH); 13329 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 13330 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 13331 continue; 13332 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 13333 getSCEV(Cmp->getOperand(1)), RewriteMap); 13334 } 13335 13336 if (RewriteMap.empty()) 13337 return Expr; 13338 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 13339 return Rewriter.visit(Expr); 13340 } 13341