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(NumTripCountsComputed, 143 "Number of loops with predictable loop counts"); 144 STATISTIC(NumTripCountsNotComputed, 145 "Number of loops without predictable loop counts"); 146 STATISTIC(NumBruteForceTripCountsComputed, 147 "Number of loops with trip counts computed by force"); 148 149 static cl::opt<unsigned> 150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 151 cl::ZeroOrMore, 152 cl::desc("Maximum number of iterations SCEV will " 153 "symbolically execute a constant " 154 "derived loop"), 155 cl::init(100)); 156 157 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 158 static cl::opt<bool> VerifySCEV( 159 "verify-scev", cl::Hidden, 160 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 161 static cl::opt<bool> VerifySCEVStrict( 162 "verify-scev-strict", cl::Hidden, 163 cl::desc("Enable stricter verification with -verify-scev is passed")); 164 static cl::opt<bool> 165 VerifySCEVMap("verify-scev-maps", cl::Hidden, 166 cl::desc("Verify no dangling value in ScalarEvolution's " 167 "ExprValueMap (slow)")); 168 169 static cl::opt<bool> VerifyIR( 170 "scev-verify-ir", cl::Hidden, 171 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 172 cl::init(false)); 173 174 static cl::opt<unsigned> MulOpsInlineThreshold( 175 "scev-mulops-inline-threshold", cl::Hidden, 176 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 177 cl::init(32)); 178 179 static cl::opt<unsigned> AddOpsInlineThreshold( 180 "scev-addops-inline-threshold", cl::Hidden, 181 cl::desc("Threshold for inlining addition operands into a SCEV"), 182 cl::init(500)); 183 184 static cl::opt<unsigned> MaxSCEVCompareDepth( 185 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 186 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 187 cl::init(32)); 188 189 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 190 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 191 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 192 cl::init(2)); 193 194 static cl::opt<unsigned> MaxValueCompareDepth( 195 "scalar-evolution-max-value-compare-depth", cl::Hidden, 196 cl::desc("Maximum depth of recursive value complexity comparisons"), 197 cl::init(2)); 198 199 static cl::opt<unsigned> 200 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 201 cl::desc("Maximum depth of recursive arithmetics"), 202 cl::init(32)); 203 204 static cl::opt<unsigned> MaxConstantEvolvingDepth( 205 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 206 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 207 208 static cl::opt<unsigned> 209 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 210 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 211 cl::init(8)); 212 213 static cl::opt<unsigned> 214 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 215 cl::desc("Max coefficients in AddRec during evolving"), 216 cl::init(8)); 217 218 static cl::opt<unsigned> 219 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 220 cl::desc("Size of the expression which is considered huge"), 221 cl::init(4096)); 222 223 static cl::opt<bool> 224 ClassifyExpressions("scalar-evolution-classify-expressions", 225 cl::Hidden, cl::init(true), 226 cl::desc("When printing analysis, include information on every instruction")); 227 228 static cl::opt<bool> UseExpensiveRangeSharpening( 229 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden, 230 cl::init(false), 231 cl::desc("Use more powerful methods of sharpening expression ranges. May " 232 "be costly in terms of compile time")); 233 234 //===----------------------------------------------------------------------===// 235 // SCEV class definitions 236 //===----------------------------------------------------------------------===// 237 238 //===----------------------------------------------------------------------===// 239 // Implementation of the SCEV class. 240 // 241 242 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 243 LLVM_DUMP_METHOD void SCEV::dump() const { 244 print(dbgs()); 245 dbgs() << '\n'; 246 } 247 #endif 248 249 void SCEV::print(raw_ostream &OS) const { 250 switch (getSCEVType()) { 251 case scConstant: 252 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 253 return; 254 case scPtrToInt: { 255 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this); 256 const SCEV *Op = PtrToInt->getOperand(); 257 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to " 258 << *PtrToInt->getType() << ")"; 259 return; 260 } 261 case scTruncate: { 262 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 263 const SCEV *Op = Trunc->getOperand(); 264 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 265 << *Trunc->getType() << ")"; 266 return; 267 } 268 case scZeroExtend: { 269 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 270 const SCEV *Op = ZExt->getOperand(); 271 OS << "(zext " << *Op->getType() << " " << *Op << " to " 272 << *ZExt->getType() << ")"; 273 return; 274 } 275 case scSignExtend: { 276 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 277 const SCEV *Op = SExt->getOperand(); 278 OS << "(sext " << *Op->getType() << " " << *Op << " to " 279 << *SExt->getType() << ")"; 280 return; 281 } 282 case scAddRecExpr: { 283 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 284 OS << "{" << *AR->getOperand(0); 285 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 286 OS << ",+," << *AR->getOperand(i); 287 OS << "}<"; 288 if (AR->hasNoUnsignedWrap()) 289 OS << "nuw><"; 290 if (AR->hasNoSignedWrap()) 291 OS << "nsw><"; 292 if (AR->hasNoSelfWrap() && 293 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 294 OS << "nw><"; 295 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 296 OS << ">"; 297 return; 298 } 299 case scAddExpr: 300 case scMulExpr: 301 case scUMaxExpr: 302 case scSMaxExpr: 303 case scUMinExpr: 304 case scSMinExpr: 305 case scSequentialUMinExpr: { 306 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 307 const char *OpStr = nullptr; 308 switch (NAry->getSCEVType()) { 309 case scAddExpr: OpStr = " + "; break; 310 case scMulExpr: OpStr = " * "; break; 311 case scUMaxExpr: OpStr = " umax "; break; 312 case scSMaxExpr: OpStr = " smax "; break; 313 case scUMinExpr: 314 OpStr = " umin "; 315 break; 316 case scSMinExpr: 317 OpStr = " smin "; 318 break; 319 case scSequentialUMinExpr: 320 OpStr = " umin_seq "; 321 break; 322 default: 323 llvm_unreachable("There are no other nary expression types."); 324 } 325 OS << "("; 326 ListSeparator LS(OpStr); 327 for (const SCEV *Op : NAry->operands()) 328 OS << LS << *Op; 329 OS << ")"; 330 switch (NAry->getSCEVType()) { 331 case scAddExpr: 332 case scMulExpr: 333 if (NAry->hasNoUnsignedWrap()) 334 OS << "<nuw>"; 335 if (NAry->hasNoSignedWrap()) 336 OS << "<nsw>"; 337 break; 338 default: 339 // Nothing to print for other nary expressions. 340 break; 341 } 342 return; 343 } 344 case scUDivExpr: { 345 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 346 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 347 return; 348 } 349 case scUnknown: { 350 const SCEVUnknown *U = cast<SCEVUnknown>(this); 351 Type *AllocTy; 352 if (U->isSizeOf(AllocTy)) { 353 OS << "sizeof(" << *AllocTy << ")"; 354 return; 355 } 356 if (U->isAlignOf(AllocTy)) { 357 OS << "alignof(" << *AllocTy << ")"; 358 return; 359 } 360 361 Type *CTy; 362 Constant *FieldNo; 363 if (U->isOffsetOf(CTy, FieldNo)) { 364 OS << "offsetof(" << *CTy << ", "; 365 FieldNo->printAsOperand(OS, false); 366 OS << ")"; 367 return; 368 } 369 370 // Otherwise just print it normally. 371 U->getValue()->printAsOperand(OS, false); 372 return; 373 } 374 case scCouldNotCompute: 375 OS << "***COULDNOTCOMPUTE***"; 376 return; 377 } 378 llvm_unreachable("Unknown SCEV kind!"); 379 } 380 381 Type *SCEV::getType() const { 382 switch (getSCEVType()) { 383 case scConstant: 384 return cast<SCEVConstant>(this)->getType(); 385 case scPtrToInt: 386 case scTruncate: 387 case scZeroExtend: 388 case scSignExtend: 389 return cast<SCEVCastExpr>(this)->getType(); 390 case scAddRecExpr: 391 return cast<SCEVAddRecExpr>(this)->getType(); 392 case scMulExpr: 393 return cast<SCEVMulExpr>(this)->getType(); 394 case scUMaxExpr: 395 case scSMaxExpr: 396 case scUMinExpr: 397 case scSMinExpr: 398 return cast<SCEVMinMaxExpr>(this)->getType(); 399 case scSequentialUMinExpr: 400 return cast<SCEVSequentialMinMaxExpr>(this)->getType(); 401 case scAddExpr: 402 return cast<SCEVAddExpr>(this)->getType(); 403 case scUDivExpr: 404 return cast<SCEVUDivExpr>(this)->getType(); 405 case scUnknown: 406 return cast<SCEVUnknown>(this)->getType(); 407 case scCouldNotCompute: 408 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 409 } 410 llvm_unreachable("Unknown SCEV kind!"); 411 } 412 413 bool SCEV::isZero() const { 414 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 415 return SC->getValue()->isZero(); 416 return false; 417 } 418 419 bool SCEV::isOne() const { 420 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 421 return SC->getValue()->isOne(); 422 return false; 423 } 424 425 bool SCEV::isAllOnesValue() const { 426 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 427 return SC->getValue()->isMinusOne(); 428 return false; 429 } 430 431 bool SCEV::isNonConstantNegative() const { 432 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 433 if (!Mul) return false; 434 435 // If there is a constant factor, it will be first. 436 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 437 if (!SC) return false; 438 439 // Return true if the value is negative, this matches things like (-42 * V). 440 return SC->getAPInt().isNegative(); 441 } 442 443 SCEVCouldNotCompute::SCEVCouldNotCompute() : 444 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 445 446 bool SCEVCouldNotCompute::classof(const SCEV *S) { 447 return S->getSCEVType() == scCouldNotCompute; 448 } 449 450 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 451 FoldingSetNodeID ID; 452 ID.AddInteger(scConstant); 453 ID.AddPointer(V); 454 void *IP = nullptr; 455 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 456 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 457 UniqueSCEVs.InsertNode(S, IP); 458 return S; 459 } 460 461 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 462 return getConstant(ConstantInt::get(getContext(), Val)); 463 } 464 465 const SCEV * 466 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 467 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 468 return getConstant(ConstantInt::get(ITy, V, isSigned)); 469 } 470 471 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, 472 const SCEV *op, Type *ty) 473 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 474 Operands[0] = op; 475 } 476 477 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, 478 Type *ITy) 479 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) { 480 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && 481 "Must be a non-bit-width-changing pointer-to-integer cast!"); 482 } 483 484 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, 485 SCEVTypes SCEVTy, const SCEV *op, 486 Type *ty) 487 : SCEVCastExpr(ID, SCEVTy, op, ty) {} 488 489 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, 490 Type *ty) 491 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) { 492 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 493 "Cannot truncate non-integer value!"); 494 } 495 496 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 497 const SCEV *op, Type *ty) 498 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) { 499 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 500 "Cannot zero extend non-integer value!"); 501 } 502 503 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 504 const SCEV *op, Type *ty) 505 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) { 506 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 507 "Cannot sign extend non-integer value!"); 508 } 509 510 void SCEVUnknown::deleted() { 511 // Clear this SCEVUnknown from various maps. 512 SE->forgetMemoizedResults(this); 513 514 // Remove this SCEVUnknown from the uniquing map. 515 SE->UniqueSCEVs.RemoveNode(this); 516 517 // Release the value. 518 setValPtr(nullptr); 519 } 520 521 void SCEVUnknown::allUsesReplacedWith(Value *New) { 522 // Remove this SCEVUnknown from the uniquing map. 523 SE->UniqueSCEVs.RemoveNode(this); 524 525 // Update this SCEVUnknown to point to the new value. This is needed 526 // because there may still be outstanding SCEVs which still point to 527 // this SCEVUnknown. 528 setValPtr(New); 529 } 530 531 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 532 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 533 if (VCE->getOpcode() == Instruction::PtrToInt) 534 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 535 if (CE->getOpcode() == Instruction::GetElementPtr && 536 CE->getOperand(0)->isNullValue() && 537 CE->getNumOperands() == 2) 538 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 539 if (CI->isOne()) { 540 AllocTy = cast<GEPOperator>(CE)->getSourceElementType(); 541 return true; 542 } 543 544 return false; 545 } 546 547 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 548 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 549 if (VCE->getOpcode() == Instruction::PtrToInt) 550 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 551 if (CE->getOpcode() == Instruction::GetElementPtr && 552 CE->getOperand(0)->isNullValue()) { 553 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 554 if (StructType *STy = dyn_cast<StructType>(Ty)) 555 if (!STy->isPacked() && 556 CE->getNumOperands() == 3 && 557 CE->getOperand(1)->isNullValue()) { 558 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 559 if (CI->isOne() && 560 STy->getNumElements() == 2 && 561 STy->getElementType(0)->isIntegerTy(1)) { 562 AllocTy = STy->getElementType(1); 563 return true; 564 } 565 } 566 } 567 568 return false; 569 } 570 571 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 572 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 573 if (VCE->getOpcode() == Instruction::PtrToInt) 574 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 575 if (CE->getOpcode() == Instruction::GetElementPtr && 576 CE->getNumOperands() == 3 && 577 CE->getOperand(0)->isNullValue() && 578 CE->getOperand(1)->isNullValue()) { 579 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 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 // If the max analysis depth was reached, return None, assuming we do not know 693 // if they are equivalent for sure. 694 static Optional<int> 695 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV, 696 EquivalenceClasses<const Value *> &EqCacheValue, 697 const LoopInfo *const LI, const SCEV *LHS, 698 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) { 699 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 700 if (LHS == RHS) 701 return 0; 702 703 // Primarily, sort the SCEVs by their getSCEVType(). 704 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 705 if (LType != RType) 706 return (int)LType - (int)RType; 707 708 if (EqCacheSCEV.isEquivalent(LHS, RHS)) 709 return 0; 710 711 if (Depth > MaxSCEVCompareDepth) 712 return None; 713 714 // Aside from the getSCEVType() ordering, the particular ordering 715 // isn't very important except that it's beneficial to be consistent, 716 // so that (a + b) and (b + a) don't end up as different expressions. 717 switch (LType) { 718 case scUnknown: { 719 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 720 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 721 722 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 723 RU->getValue(), Depth + 1); 724 if (X == 0) 725 EqCacheSCEV.unionSets(LHS, RHS); 726 return X; 727 } 728 729 case scConstant: { 730 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 731 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 732 733 // Compare constant values. 734 const APInt &LA = LC->getAPInt(); 735 const APInt &RA = RC->getAPInt(); 736 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 737 if (LBitWidth != RBitWidth) 738 return (int)LBitWidth - (int)RBitWidth; 739 return LA.ult(RA) ? -1 : 1; 740 } 741 742 case scAddRecExpr: { 743 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 744 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 745 746 // There is always a dominance between two recs that are used by one SCEV, 747 // so we can safely sort recs by loop header dominance. We require such 748 // order in getAddExpr. 749 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 750 if (LLoop != RLoop) { 751 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 752 assert(LHead != RHead && "Two loops share the same header?"); 753 if (DT.dominates(LHead, RHead)) 754 return 1; 755 else 756 assert(DT.dominates(RHead, LHead) && 757 "No dominance between recurrences used by one SCEV?"); 758 return -1; 759 } 760 761 // Addrec complexity grows with operand count. 762 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 763 if (LNumOps != RNumOps) 764 return (int)LNumOps - (int)RNumOps; 765 766 // Lexicographically compare. 767 for (unsigned i = 0; i != LNumOps; ++i) { 768 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 769 LA->getOperand(i), RA->getOperand(i), DT, 770 Depth + 1); 771 if (X != 0) 772 return X; 773 } 774 EqCacheSCEV.unionSets(LHS, RHS); 775 return 0; 776 } 777 778 case scAddExpr: 779 case scMulExpr: 780 case scSMaxExpr: 781 case scUMaxExpr: 782 case scSMinExpr: 783 case scUMinExpr: 784 case scSequentialUMinExpr: { 785 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 786 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 787 788 // Lexicographically compare n-ary expressions. 789 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 790 if (LNumOps != RNumOps) 791 return (int)LNumOps - (int)RNumOps; 792 793 for (unsigned i = 0; i != LNumOps; ++i) { 794 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 795 LC->getOperand(i), RC->getOperand(i), DT, 796 Depth + 1); 797 if (X != 0) 798 return X; 799 } 800 EqCacheSCEV.unionSets(LHS, RHS); 801 return 0; 802 } 803 804 case scUDivExpr: { 805 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 806 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 807 808 // Lexicographically compare udiv expressions. 809 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 810 RC->getLHS(), DT, Depth + 1); 811 if (X != 0) 812 return X; 813 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 814 RC->getRHS(), DT, Depth + 1); 815 if (X == 0) 816 EqCacheSCEV.unionSets(LHS, RHS); 817 return X; 818 } 819 820 case scPtrToInt: 821 case scTruncate: 822 case scZeroExtend: 823 case scSignExtend: { 824 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 825 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 826 827 // Compare cast expressions by operand. 828 auto X = 829 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(), 830 RC->getOperand(), DT, Depth + 1); 831 if (X == 0) 832 EqCacheSCEV.unionSets(LHS, RHS); 833 return X; 834 } 835 836 case scCouldNotCompute: 837 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 838 } 839 llvm_unreachable("Unknown SCEV kind!"); 840 } 841 842 /// Given a list of SCEV objects, order them by their complexity, and group 843 /// objects of the same complexity together by value. When this routine is 844 /// finished, we know that any duplicates in the vector are consecutive and that 845 /// complexity is monotonically increasing. 846 /// 847 /// Note that we go take special precautions to ensure that we get deterministic 848 /// results from this routine. In other words, we don't want the results of 849 /// this to depend on where the addresses of various SCEV objects happened to 850 /// land in memory. 851 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 852 LoopInfo *LI, DominatorTree &DT) { 853 if (Ops.size() < 2) return; // Noop 854 855 EquivalenceClasses<const SCEV *> EqCacheSCEV; 856 EquivalenceClasses<const Value *> EqCacheValue; 857 858 // Whether LHS has provably less complexity than RHS. 859 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) { 860 auto Complexity = 861 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT); 862 return Complexity && *Complexity < 0; 863 }; 864 if (Ops.size() == 2) { 865 // This is the common case, which also happens to be trivially simple. 866 // Special case it. 867 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 868 if (IsLessComplex(RHS, LHS)) 869 std::swap(LHS, RHS); 870 return; 871 } 872 873 // Do the rough sort by complexity. 874 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 875 return IsLessComplex(LHS, RHS); 876 }); 877 878 // Now that we are sorted by complexity, group elements of the same 879 // complexity. Note that this is, at worst, N^2, but the vector is likely to 880 // be extremely short in practice. Note that we take this approach because we 881 // do not want to depend on the addresses of the objects we are grouping. 882 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 883 const SCEV *S = Ops[i]; 884 unsigned Complexity = S->getSCEVType(); 885 886 // If there are any objects of the same complexity and same value as this 887 // one, group them. 888 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 889 if (Ops[j] == S) { // Found a duplicate. 890 // Move it to immediately after i'th element. 891 std::swap(Ops[i+1], Ops[j]); 892 ++i; // no need to rescan it. 893 if (i == e-2) return; // Done! 894 } 895 } 896 } 897 } 898 899 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 900 /// least HugeExprThreshold nodes). 901 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 902 return any_of(Ops, [](const SCEV *S) { 903 return S->getExpressionSize() >= HugeExprThreshold; 904 }); 905 } 906 907 //===----------------------------------------------------------------------===// 908 // Simple SCEV method implementations 909 //===----------------------------------------------------------------------===// 910 911 /// Compute BC(It, K). The result has width W. Assume, K > 0. 912 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 913 ScalarEvolution &SE, 914 Type *ResultTy) { 915 // Handle the simplest case efficiently. 916 if (K == 1) 917 return SE.getTruncateOrZeroExtend(It, ResultTy); 918 919 // We are using the following formula for BC(It, K): 920 // 921 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 922 // 923 // Suppose, W is the bitwidth of the return value. We must be prepared for 924 // overflow. Hence, we must assure that the result of our computation is 925 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 926 // safe in modular arithmetic. 927 // 928 // However, this code doesn't use exactly that formula; the formula it uses 929 // is something like the following, where T is the number of factors of 2 in 930 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 931 // exponentiation: 932 // 933 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 934 // 935 // This formula is trivially equivalent to the previous formula. However, 936 // this formula can be implemented much more efficiently. The trick is that 937 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 938 // arithmetic. To do exact division in modular arithmetic, all we have 939 // to do is multiply by the inverse. Therefore, this step can be done at 940 // width W. 941 // 942 // The next issue is how to safely do the division by 2^T. The way this 943 // is done is by doing the multiplication step at a width of at least W + T 944 // bits. This way, the bottom W+T bits of the product are accurate. Then, 945 // when we perform the division by 2^T (which is equivalent to a right shift 946 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 947 // truncated out after the division by 2^T. 948 // 949 // In comparison to just directly using the first formula, this technique 950 // is much more efficient; using the first formula requires W * K bits, 951 // but this formula less than W + K bits. Also, the first formula requires 952 // a division step, whereas this formula only requires multiplies and shifts. 953 // 954 // It doesn't matter whether the subtraction step is done in the calculation 955 // width or the input iteration count's width; if the subtraction overflows, 956 // the result must be zero anyway. We prefer here to do it in the width of 957 // the induction variable because it helps a lot for certain cases; CodeGen 958 // isn't smart enough to ignore the overflow, which leads to much less 959 // efficient code if the width of the subtraction is wider than the native 960 // register width. 961 // 962 // (It's possible to not widen at all by pulling out factors of 2 before 963 // the multiplication; for example, K=2 can be calculated as 964 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 965 // extra arithmetic, so it's not an obvious win, and it gets 966 // much more complicated for K > 3.) 967 968 // Protection from insane SCEVs; this bound is conservative, 969 // but it probably doesn't matter. 970 if (K > 1000) 971 return SE.getCouldNotCompute(); 972 973 unsigned W = SE.getTypeSizeInBits(ResultTy); 974 975 // Calculate K! / 2^T and T; we divide out the factors of two before 976 // multiplying for calculating K! / 2^T to avoid overflow. 977 // Other overflow doesn't matter because we only care about the bottom 978 // W bits of the result. 979 APInt OddFactorial(W, 1); 980 unsigned T = 1; 981 for (unsigned i = 3; i <= K; ++i) { 982 APInt Mult(W, i); 983 unsigned TwoFactors = Mult.countTrailingZeros(); 984 T += TwoFactors; 985 Mult.lshrInPlace(TwoFactors); 986 OddFactorial *= Mult; 987 } 988 989 // We need at least W + T bits for the multiplication step 990 unsigned CalculationBits = W + T; 991 992 // Calculate 2^T, at width T+W. 993 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 994 995 // Calculate the multiplicative inverse of K! / 2^T; 996 // this multiplication factor will perform the exact division by 997 // K! / 2^T. 998 APInt Mod = APInt::getSignedMinValue(W+1); 999 APInt MultiplyFactor = OddFactorial.zext(W+1); 1000 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1001 MultiplyFactor = MultiplyFactor.trunc(W); 1002 1003 // Calculate the product, at width T+W 1004 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1005 CalculationBits); 1006 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1007 for (unsigned i = 1; i != K; ++i) { 1008 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1009 Dividend = SE.getMulExpr(Dividend, 1010 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1011 } 1012 1013 // Divide by 2^T 1014 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1015 1016 // Truncate the result, and divide by K! / 2^T. 1017 1018 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1019 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1020 } 1021 1022 /// Return the value of this chain of recurrences at the specified iteration 1023 /// number. We can evaluate this recurrence by multiplying each element in the 1024 /// chain by the binomial coefficient corresponding to it. In other words, we 1025 /// can evaluate {A,+,B,+,C,+,D} as: 1026 /// 1027 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1028 /// 1029 /// where BC(It, k) stands for binomial coefficient. 1030 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1031 ScalarEvolution &SE) const { 1032 return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE); 1033 } 1034 1035 const SCEV * 1036 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands, 1037 const SCEV *It, ScalarEvolution &SE) { 1038 assert(Operands.size() > 0); 1039 const SCEV *Result = Operands[0]; 1040 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 1041 // The computation is correct in the face of overflow provided that the 1042 // multiplication is performed _after_ the evaluation of the binomial 1043 // coefficient. 1044 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType()); 1045 if (isa<SCEVCouldNotCompute>(Coeff)) 1046 return Coeff; 1047 1048 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff)); 1049 } 1050 return Result; 1051 } 1052 1053 //===----------------------------------------------------------------------===// 1054 // SCEV Expression folder implementations 1055 //===----------------------------------------------------------------------===// 1056 1057 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op, 1058 unsigned Depth) { 1059 assert(Depth <= 1 && 1060 "getLosslessPtrToIntExpr() should self-recurse at most once."); 1061 1062 // We could be called with an integer-typed operands during SCEV rewrites. 1063 // Since the operand is an integer already, just perform zext/trunc/self cast. 1064 if (!Op->getType()->isPointerTy()) 1065 return Op; 1066 1067 // What would be an ID for such a SCEV cast expression? 1068 FoldingSetNodeID ID; 1069 ID.AddInteger(scPtrToInt); 1070 ID.AddPointer(Op); 1071 1072 void *IP = nullptr; 1073 1074 // Is there already an expression for such a cast? 1075 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1076 return S; 1077 1078 // It isn't legal for optimizations to construct new ptrtoint expressions 1079 // for non-integral pointers. 1080 if (getDataLayout().isNonIntegralPointerType(Op->getType())) 1081 return getCouldNotCompute(); 1082 1083 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType()); 1084 1085 // We can only trivially model ptrtoint if SCEV's effective (integer) type 1086 // is sufficiently wide to represent all possible pointer values. 1087 // We could theoretically teach SCEV to truncate wider pointers, but 1088 // that isn't implemented for now. 1089 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) != 1090 getDataLayout().getTypeSizeInBits(IntPtrTy)) 1091 return getCouldNotCompute(); 1092 1093 // If not, is this expression something we can't reduce any further? 1094 if (auto *U = dyn_cast<SCEVUnknown>(Op)) { 1095 // Perform some basic constant folding. If the operand of the ptr2int cast 1096 // is a null pointer, don't create a ptr2int SCEV expression (that will be 1097 // left as-is), but produce a zero constant. 1098 // NOTE: We could handle a more general case, but lack motivational cases. 1099 if (isa<ConstantPointerNull>(U->getValue())) 1100 return getZero(IntPtrTy); 1101 1102 // Create an explicit cast node. 1103 // We can reuse the existing insert position since if we get here, 1104 // we won't have made any changes which would invalidate it. 1105 SCEV *S = new (SCEVAllocator) 1106 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy); 1107 UniqueSCEVs.InsertNode(S, IP); 1108 registerUser(S, Op); 1109 return S; 1110 } 1111 1112 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for " 1113 "non-SCEVUnknown's."); 1114 1115 // Otherwise, we've got some expression that is more complex than just a 1116 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an 1117 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown 1118 // only, and the expressions must otherwise be integer-typed. 1119 // So sink the cast down to the SCEVUnknown's. 1120 1121 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression, 1122 /// which computes a pointer-typed value, and rewrites the whole expression 1123 /// tree so that *all* the computations are done on integers, and the only 1124 /// pointer-typed operands in the expression are SCEVUnknown. 1125 class SCEVPtrToIntSinkingRewriter 1126 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> { 1127 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>; 1128 1129 public: 1130 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {} 1131 1132 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) { 1133 SCEVPtrToIntSinkingRewriter Rewriter(SE); 1134 return Rewriter.visit(Scev); 1135 } 1136 1137 const SCEV *visit(const SCEV *S) { 1138 Type *STy = S->getType(); 1139 // If the expression is not pointer-typed, just keep it as-is. 1140 if (!STy->isPointerTy()) 1141 return S; 1142 // Else, recursively sink the cast down into it. 1143 return Base::visit(S); 1144 } 1145 1146 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) { 1147 SmallVector<const SCEV *, 2> Operands; 1148 bool Changed = false; 1149 for (auto *Op : Expr->operands()) { 1150 Operands.push_back(visit(Op)); 1151 Changed |= Op != Operands.back(); 1152 } 1153 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags()); 1154 } 1155 1156 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) { 1157 SmallVector<const SCEV *, 2> Operands; 1158 bool Changed = false; 1159 for (auto *Op : Expr->operands()) { 1160 Operands.push_back(visit(Op)); 1161 Changed |= Op != Operands.back(); 1162 } 1163 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags()); 1164 } 1165 1166 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 1167 assert(Expr->getType()->isPointerTy() && 1168 "Should only reach pointer-typed SCEVUnknown's."); 1169 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1); 1170 } 1171 }; 1172 1173 // And actually perform the cast sinking. 1174 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this); 1175 assert(IntOp->getType()->isIntegerTy() && 1176 "We must have succeeded in sinking the cast, " 1177 "and ending up with an integer-typed expression!"); 1178 return IntOp; 1179 } 1180 1181 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) { 1182 assert(Ty->isIntegerTy() && "Target type must be an integer type!"); 1183 1184 const SCEV *IntOp = getLosslessPtrToIntExpr(Op); 1185 if (isa<SCEVCouldNotCompute>(IntOp)) 1186 return IntOp; 1187 1188 return getTruncateOrZeroExtend(IntOp, Ty); 1189 } 1190 1191 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1192 unsigned Depth) { 1193 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1194 "This is not a truncating conversion!"); 1195 assert(isSCEVable(Ty) && 1196 "This is not a conversion to a SCEVable type!"); 1197 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!"); 1198 Ty = getEffectiveSCEVType(Ty); 1199 1200 FoldingSetNodeID ID; 1201 ID.AddInteger(scTruncate); 1202 ID.AddPointer(Op); 1203 ID.AddPointer(Ty); 1204 void *IP = nullptr; 1205 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1206 1207 // Fold if the operand is constant. 1208 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1209 return getConstant( 1210 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1211 1212 // trunc(trunc(x)) --> trunc(x) 1213 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1214 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1215 1216 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1217 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1218 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1219 1220 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1221 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1222 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1223 1224 if (Depth > MaxCastDepth) { 1225 SCEV *S = 1226 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1227 UniqueSCEVs.InsertNode(S, IP); 1228 registerUser(S, Op); 1229 return S; 1230 } 1231 1232 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1233 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1234 // if after transforming we have at most one truncate, not counting truncates 1235 // that replace other casts. 1236 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1237 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1238 SmallVector<const SCEV *, 4> Operands; 1239 unsigned numTruncs = 0; 1240 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1241 ++i) { 1242 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1243 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) && 1244 isa<SCEVTruncateExpr>(S)) 1245 numTruncs++; 1246 Operands.push_back(S); 1247 } 1248 if (numTruncs < 2) { 1249 if (isa<SCEVAddExpr>(Op)) 1250 return getAddExpr(Operands); 1251 else if (isa<SCEVMulExpr>(Op)) 1252 return getMulExpr(Operands); 1253 else 1254 llvm_unreachable("Unexpected SCEV type for Op."); 1255 } 1256 // Although we checked in the beginning that ID is not in the cache, it is 1257 // possible that during recursion and different modification ID was inserted 1258 // into the cache. So if we find it, just return it. 1259 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1260 return S; 1261 } 1262 1263 // If the input value is a chrec scev, truncate the chrec's operands. 1264 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1265 SmallVector<const SCEV *, 4> Operands; 1266 for (const SCEV *Op : AddRec->operands()) 1267 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1268 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1269 } 1270 1271 // Return zero if truncating to known zeros. 1272 uint32_t MinTrailingZeros = GetMinTrailingZeros(Op); 1273 if (MinTrailingZeros >= getTypeSizeInBits(Ty)) 1274 return getZero(Ty); 1275 1276 // The cast wasn't folded; create an explicit cast node. We can reuse 1277 // the existing insert position since if we get here, we won't have 1278 // made any changes which would invalidate it. 1279 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1280 Op, Ty); 1281 UniqueSCEVs.InsertNode(S, IP); 1282 registerUser(S, Op); 1283 return S; 1284 } 1285 1286 // Get the limit of a recurrence such that incrementing by Step cannot cause 1287 // signed overflow as long as the value of the recurrence within the 1288 // loop does not exceed this limit before incrementing. 1289 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1290 ICmpInst::Predicate *Pred, 1291 ScalarEvolution *SE) { 1292 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1293 if (SE->isKnownPositive(Step)) { 1294 *Pred = ICmpInst::ICMP_SLT; 1295 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1296 SE->getSignedRangeMax(Step)); 1297 } 1298 if (SE->isKnownNegative(Step)) { 1299 *Pred = ICmpInst::ICMP_SGT; 1300 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1301 SE->getSignedRangeMin(Step)); 1302 } 1303 return nullptr; 1304 } 1305 1306 // Get the limit of a recurrence such that incrementing by Step cannot cause 1307 // unsigned overflow as long as the value of the recurrence within the loop does 1308 // not exceed this limit before incrementing. 1309 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1310 ICmpInst::Predicate *Pred, 1311 ScalarEvolution *SE) { 1312 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1313 *Pred = ICmpInst::ICMP_ULT; 1314 1315 return SE->getConstant(APInt::getMinValue(BitWidth) - 1316 SE->getUnsignedRangeMax(Step)); 1317 } 1318 1319 namespace { 1320 1321 struct ExtendOpTraitsBase { 1322 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1323 unsigned); 1324 }; 1325 1326 // Used to make code generic over signed and unsigned overflow. 1327 template <typename ExtendOp> struct ExtendOpTraits { 1328 // Members present: 1329 // 1330 // static const SCEV::NoWrapFlags WrapType; 1331 // 1332 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1333 // 1334 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1335 // ICmpInst::Predicate *Pred, 1336 // ScalarEvolution *SE); 1337 }; 1338 1339 template <> 1340 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1341 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1342 1343 static const GetExtendExprTy GetExtendExpr; 1344 1345 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1346 ICmpInst::Predicate *Pred, 1347 ScalarEvolution *SE) { 1348 return getSignedOverflowLimitForStep(Step, Pred, SE); 1349 } 1350 }; 1351 1352 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1353 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1354 1355 template <> 1356 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1357 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1358 1359 static const GetExtendExprTy GetExtendExpr; 1360 1361 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1362 ICmpInst::Predicate *Pred, 1363 ScalarEvolution *SE) { 1364 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1365 } 1366 }; 1367 1368 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1369 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1370 1371 } // end anonymous namespace 1372 1373 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1374 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1375 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1376 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1377 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1378 // expression "Step + sext/zext(PreIncAR)" is congruent with 1379 // "sext/zext(PostIncAR)" 1380 template <typename ExtendOpTy> 1381 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1382 ScalarEvolution *SE, unsigned Depth) { 1383 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1384 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1385 1386 const Loop *L = AR->getLoop(); 1387 const SCEV *Start = AR->getStart(); 1388 const SCEV *Step = AR->getStepRecurrence(*SE); 1389 1390 // Check for a simple looking step prior to loop entry. 1391 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1392 if (!SA) 1393 return nullptr; 1394 1395 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1396 // subtraction is expensive. For this purpose, perform a quick and dirty 1397 // difference, by checking for Step in the operand list. 1398 SmallVector<const SCEV *, 4> DiffOps; 1399 for (const SCEV *Op : SA->operands()) 1400 if (Op != Step) 1401 DiffOps.push_back(Op); 1402 1403 if (DiffOps.size() == SA->getNumOperands()) 1404 return nullptr; 1405 1406 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1407 // `Step`: 1408 1409 // 1. NSW/NUW flags on the step increment. 1410 auto PreStartFlags = 1411 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1412 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1413 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1414 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1415 1416 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1417 // "S+X does not sign/unsign-overflow". 1418 // 1419 1420 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1421 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1422 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1423 return PreStart; 1424 1425 // 2. Direct overflow check on the step operation's expression. 1426 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1427 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1428 const SCEV *OperandExtendedStart = 1429 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1430 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1431 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1432 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1433 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1434 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1435 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1436 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType); 1437 } 1438 return PreStart; 1439 } 1440 1441 // 3. Loop precondition. 1442 ICmpInst::Predicate Pred; 1443 const SCEV *OverflowLimit = 1444 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1445 1446 if (OverflowLimit && 1447 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1448 return PreStart; 1449 1450 return nullptr; 1451 } 1452 1453 // Get the normalized zero or sign extended expression for this AddRec's Start. 1454 template <typename ExtendOpTy> 1455 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1456 ScalarEvolution *SE, 1457 unsigned Depth) { 1458 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1459 1460 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1461 if (!PreStart) 1462 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1463 1464 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1465 Depth), 1466 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1467 } 1468 1469 // Try to prove away overflow by looking at "nearby" add recurrences. A 1470 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1471 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1472 // 1473 // Formally: 1474 // 1475 // {S,+,X} == {S-T,+,X} + T 1476 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1477 // 1478 // If ({S-T,+,X} + T) does not overflow ... (1) 1479 // 1480 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1481 // 1482 // If {S-T,+,X} does not overflow ... (2) 1483 // 1484 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1485 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1486 // 1487 // If (S-T)+T does not overflow ... (3) 1488 // 1489 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1490 // == {Ext(S),+,Ext(X)} == LHS 1491 // 1492 // Thus, if (1), (2) and (3) are true for some T, then 1493 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1494 // 1495 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1496 // does not overflow" restricted to the 0th iteration. Therefore we only need 1497 // to check for (1) and (2). 1498 // 1499 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1500 // is `Delta` (defined below). 1501 template <typename ExtendOpTy> 1502 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1503 const SCEV *Step, 1504 const Loop *L) { 1505 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1506 1507 // We restrict `Start` to a constant to prevent SCEV from spending too much 1508 // time here. It is correct (but more expensive) to continue with a 1509 // non-constant `Start` and do a general SCEV subtraction to compute 1510 // `PreStart` below. 1511 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1512 if (!StartC) 1513 return false; 1514 1515 APInt StartAI = StartC->getAPInt(); 1516 1517 for (unsigned Delta : {-2, -1, 1, 2}) { 1518 const SCEV *PreStart = getConstant(StartAI - Delta); 1519 1520 FoldingSetNodeID ID; 1521 ID.AddInteger(scAddRecExpr); 1522 ID.AddPointer(PreStart); 1523 ID.AddPointer(Step); 1524 ID.AddPointer(L); 1525 void *IP = nullptr; 1526 const auto *PreAR = 1527 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1528 1529 // Give up if we don't already have the add recurrence we need because 1530 // actually constructing an add recurrence is relatively expensive. 1531 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1532 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1533 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1534 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1535 DeltaS, &Pred, this); 1536 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1537 return true; 1538 } 1539 } 1540 1541 return false; 1542 } 1543 1544 // Finds an integer D for an expression (C + x + y + ...) such that the top 1545 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1546 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1547 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1548 // the (C + x + y + ...) expression is \p WholeAddExpr. 1549 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1550 const SCEVConstant *ConstantTerm, 1551 const SCEVAddExpr *WholeAddExpr) { 1552 const APInt &C = ConstantTerm->getAPInt(); 1553 const unsigned BitWidth = C.getBitWidth(); 1554 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1555 uint32_t TZ = BitWidth; 1556 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1557 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1558 if (TZ) { 1559 // Set D to be as many least significant bits of C as possible while still 1560 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1561 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1562 } 1563 return APInt(BitWidth, 0); 1564 } 1565 1566 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1567 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1568 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1569 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1570 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1571 const APInt &ConstantStart, 1572 const SCEV *Step) { 1573 const unsigned BitWidth = ConstantStart.getBitWidth(); 1574 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1575 if (TZ) 1576 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1577 : ConstantStart; 1578 return APInt(BitWidth, 0); 1579 } 1580 1581 const SCEV * 1582 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1583 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1584 "This is not an extending conversion!"); 1585 assert(isSCEVable(Ty) && 1586 "This is not a conversion to a SCEVable type!"); 1587 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1588 Ty = getEffectiveSCEVType(Ty); 1589 1590 // Fold if the operand is constant. 1591 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1592 return getConstant( 1593 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1594 1595 // zext(zext(x)) --> zext(x) 1596 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1597 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1598 1599 // Before doing any expensive analysis, check to see if we've already 1600 // computed a SCEV for this Op and Ty. 1601 FoldingSetNodeID ID; 1602 ID.AddInteger(scZeroExtend); 1603 ID.AddPointer(Op); 1604 ID.AddPointer(Ty); 1605 void *IP = nullptr; 1606 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1607 if (Depth > MaxCastDepth) { 1608 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1609 Op, Ty); 1610 UniqueSCEVs.InsertNode(S, IP); 1611 registerUser(S, Op); 1612 return S; 1613 } 1614 1615 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1616 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1617 // It's possible the bits taken off by the truncate were all zero bits. If 1618 // so, we should be able to simplify this further. 1619 const SCEV *X = ST->getOperand(); 1620 ConstantRange CR = getUnsignedRange(X); 1621 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1622 unsigned NewBits = getTypeSizeInBits(Ty); 1623 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1624 CR.zextOrTrunc(NewBits))) 1625 return getTruncateOrZeroExtend(X, Ty, Depth); 1626 } 1627 1628 // If the input value is a chrec scev, and we can prove that the value 1629 // did not overflow the old, smaller, value, we can zero extend all of the 1630 // operands (often constants). This allows analysis of something like 1631 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1632 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1633 if (AR->isAffine()) { 1634 const SCEV *Start = AR->getStart(); 1635 const SCEV *Step = AR->getStepRecurrence(*this); 1636 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1637 const Loop *L = AR->getLoop(); 1638 1639 if (!AR->hasNoUnsignedWrap()) { 1640 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1641 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1642 } 1643 1644 // If we have special knowledge that this addrec won't overflow, 1645 // we don't need to do any further analysis. 1646 if (AR->hasNoUnsignedWrap()) 1647 return getAddRecExpr( 1648 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1649 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1650 1651 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1652 // Note that this serves two purposes: It filters out loops that are 1653 // simply not analyzable, and it covers the case where this code is 1654 // being called from within backedge-taken count analysis, such that 1655 // attempting to ask for the backedge-taken count would likely result 1656 // in infinite recursion. In the later case, the analysis code will 1657 // cope with a conservative value, and it will take care to purge 1658 // that value once it has finished. 1659 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1660 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1661 // Manually compute the final value for AR, checking for overflow. 1662 1663 // Check whether the backedge-taken count can be losslessly casted to 1664 // the addrec's type. The count is always unsigned. 1665 const SCEV *CastedMaxBECount = 1666 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1667 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1668 CastedMaxBECount, MaxBECount->getType(), Depth); 1669 if (MaxBECount == RecastedMaxBECount) { 1670 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1671 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1672 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1673 SCEV::FlagAnyWrap, Depth + 1); 1674 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1675 SCEV::FlagAnyWrap, 1676 Depth + 1), 1677 WideTy, Depth + 1); 1678 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1679 const SCEV *WideMaxBECount = 1680 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1681 const SCEV *OperandExtendedAdd = 1682 getAddExpr(WideStart, 1683 getMulExpr(WideMaxBECount, 1684 getZeroExtendExpr(Step, WideTy, Depth + 1), 1685 SCEV::FlagAnyWrap, Depth + 1), 1686 SCEV::FlagAnyWrap, Depth + 1); 1687 if (ZAdd == OperandExtendedAdd) { 1688 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1689 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1690 // Return the expression with the addrec on the outside. 1691 return getAddRecExpr( 1692 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1693 Depth + 1), 1694 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1695 AR->getNoWrapFlags()); 1696 } 1697 // Similar to above, only this time treat the step value as signed. 1698 // This covers loops that count down. 1699 OperandExtendedAdd = 1700 getAddExpr(WideStart, 1701 getMulExpr(WideMaxBECount, 1702 getSignExtendExpr(Step, WideTy, Depth + 1), 1703 SCEV::FlagAnyWrap, Depth + 1), 1704 SCEV::FlagAnyWrap, Depth + 1); 1705 if (ZAdd == OperandExtendedAdd) { 1706 // Cache knowledge of AR NW, which is propagated to this AddRec. 1707 // Negative step causes unsigned wrap, but it still can't self-wrap. 1708 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1709 // Return the expression with the addrec on the outside. 1710 return getAddRecExpr( 1711 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1712 Depth + 1), 1713 getSignExtendExpr(Step, Ty, Depth + 1), L, 1714 AR->getNoWrapFlags()); 1715 } 1716 } 1717 } 1718 1719 // Normally, in the cases we can prove no-overflow via a 1720 // backedge guarding condition, we can also compute a backedge 1721 // taken count for the loop. The exceptions are assumptions and 1722 // guards present in the loop -- SCEV is not great at exploiting 1723 // these to compute max backedge taken counts, but can still use 1724 // these to prove lack of overflow. Use this fact to avoid 1725 // doing extra work that may not pay off. 1726 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1727 !AC.assumptions().empty()) { 1728 1729 auto NewFlags = proveNoUnsignedWrapViaInduction(AR); 1730 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1731 if (AR->hasNoUnsignedWrap()) { 1732 // Same as nuw case above - duplicated here to avoid a compile time 1733 // issue. It's not clear that the order of checks does matter, but 1734 // it's one of two issue possible causes for a change which was 1735 // reverted. Be conservative for the moment. 1736 return getAddRecExpr( 1737 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1738 Depth + 1), 1739 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1740 AR->getNoWrapFlags()); 1741 } 1742 1743 // For a negative step, we can extend the operands iff doing so only 1744 // traverses values in the range zext([0,UINT_MAX]). 1745 if (isKnownNegative(Step)) { 1746 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1747 getSignedRangeMin(Step)); 1748 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1749 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1750 // Cache knowledge of AR NW, which is propagated to this 1751 // AddRec. Negative step causes unsigned wrap, but it 1752 // still can't self-wrap. 1753 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1754 // Return the expression with the addrec on the outside. 1755 return getAddRecExpr( 1756 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1757 Depth + 1), 1758 getSignExtendExpr(Step, Ty, Depth + 1), L, 1759 AR->getNoWrapFlags()); 1760 } 1761 } 1762 } 1763 1764 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1765 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1766 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1767 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1768 const APInt &C = SC->getAPInt(); 1769 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1770 if (D != 0) { 1771 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1772 const SCEV *SResidual = 1773 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1774 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1775 return getAddExpr(SZExtD, SZExtR, 1776 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1777 Depth + 1); 1778 } 1779 } 1780 1781 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1782 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1783 return getAddRecExpr( 1784 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1785 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1786 } 1787 } 1788 1789 // zext(A % B) --> zext(A) % zext(B) 1790 { 1791 const SCEV *LHS; 1792 const SCEV *RHS; 1793 if (matchURem(Op, LHS, RHS)) 1794 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1795 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1796 } 1797 1798 // zext(A / B) --> zext(A) / zext(B). 1799 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1800 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1801 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1802 1803 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1804 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1805 if (SA->hasNoUnsignedWrap()) { 1806 // If the addition does not unsign overflow then we can, by definition, 1807 // commute the zero extension with the addition operation. 1808 SmallVector<const SCEV *, 4> Ops; 1809 for (const auto *Op : SA->operands()) 1810 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1811 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1812 } 1813 1814 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1815 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1816 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1817 // 1818 // Often address arithmetics contain expressions like 1819 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1820 // This transformation is useful while proving that such expressions are 1821 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1822 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1823 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1824 if (D != 0) { 1825 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1826 const SCEV *SResidual = 1827 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1828 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1829 return getAddExpr(SZExtD, SZExtR, 1830 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1831 Depth + 1); 1832 } 1833 } 1834 } 1835 1836 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1837 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1838 if (SM->hasNoUnsignedWrap()) { 1839 // If the multiply does not unsign overflow then we can, by definition, 1840 // commute the zero extension with the multiply operation. 1841 SmallVector<const SCEV *, 4> Ops; 1842 for (const auto *Op : SM->operands()) 1843 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1844 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1845 } 1846 1847 // zext(2^K * (trunc X to iN)) to iM -> 1848 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1849 // 1850 // Proof: 1851 // 1852 // zext(2^K * (trunc X to iN)) to iM 1853 // = zext((trunc X to iN) << K) to iM 1854 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1855 // (because shl removes the top K bits) 1856 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1857 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1858 // 1859 if (SM->getNumOperands() == 2) 1860 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1861 if (MulLHS->getAPInt().isPowerOf2()) 1862 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1863 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1864 MulLHS->getAPInt().logBase2(); 1865 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1866 return getMulExpr( 1867 getZeroExtendExpr(MulLHS, Ty), 1868 getZeroExtendExpr( 1869 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1870 SCEV::FlagNUW, Depth + 1); 1871 } 1872 } 1873 1874 // The cast wasn't folded; create an explicit cast node. 1875 // Recompute the insert position, as it may have been invalidated. 1876 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1877 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1878 Op, Ty); 1879 UniqueSCEVs.InsertNode(S, IP); 1880 registerUser(S, Op); 1881 return S; 1882 } 1883 1884 const SCEV * 1885 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1886 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1887 "This is not an extending conversion!"); 1888 assert(isSCEVable(Ty) && 1889 "This is not a conversion to a SCEVable type!"); 1890 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1891 Ty = getEffectiveSCEVType(Ty); 1892 1893 // Fold if the operand is constant. 1894 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1895 return getConstant( 1896 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1897 1898 // sext(sext(x)) --> sext(x) 1899 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1900 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1901 1902 // sext(zext(x)) --> zext(x) 1903 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1904 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1905 1906 // Before doing any expensive analysis, check to see if we've already 1907 // computed a SCEV for this Op and Ty. 1908 FoldingSetNodeID ID; 1909 ID.AddInteger(scSignExtend); 1910 ID.AddPointer(Op); 1911 ID.AddPointer(Ty); 1912 void *IP = nullptr; 1913 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1914 // Limit recursion depth. 1915 if (Depth > MaxCastDepth) { 1916 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1917 Op, Ty); 1918 UniqueSCEVs.InsertNode(S, IP); 1919 registerUser(S, Op); 1920 return S; 1921 } 1922 1923 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1924 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1925 // It's possible the bits taken off by the truncate were all sign bits. If 1926 // so, we should be able to simplify this further. 1927 const SCEV *X = ST->getOperand(); 1928 ConstantRange CR = getSignedRange(X); 1929 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1930 unsigned NewBits = getTypeSizeInBits(Ty); 1931 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1932 CR.sextOrTrunc(NewBits))) 1933 return getTruncateOrSignExtend(X, Ty, Depth); 1934 } 1935 1936 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1937 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1938 if (SA->hasNoSignedWrap()) { 1939 // If the addition does not sign overflow then we can, by definition, 1940 // commute the sign extension with the addition operation. 1941 SmallVector<const SCEV *, 4> Ops; 1942 for (const auto *Op : SA->operands()) 1943 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1944 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1945 } 1946 1947 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1948 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1949 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1950 // 1951 // For instance, this will bring two seemingly different expressions: 1952 // 1 + sext(5 + 20 * %x + 24 * %y) and 1953 // sext(6 + 20 * %x + 24 * %y) 1954 // to the same form: 1955 // 2 + sext(4 + 20 * %x + 24 * %y) 1956 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1957 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1958 if (D != 0) { 1959 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1960 const SCEV *SResidual = 1961 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1962 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1963 return getAddExpr(SSExtD, SSExtR, 1964 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1965 Depth + 1); 1966 } 1967 } 1968 } 1969 // If the input value is a chrec scev, and we can prove that the value 1970 // did not overflow the old, smaller, value, we can sign extend all of the 1971 // operands (often constants). This allows analysis of something like 1972 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1973 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1974 if (AR->isAffine()) { 1975 const SCEV *Start = AR->getStart(); 1976 const SCEV *Step = AR->getStepRecurrence(*this); 1977 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1978 const Loop *L = AR->getLoop(); 1979 1980 if (!AR->hasNoSignedWrap()) { 1981 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1982 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1983 } 1984 1985 // If we have special knowledge that this addrec won't overflow, 1986 // we don't need to do any further analysis. 1987 if (AR->hasNoSignedWrap()) 1988 return getAddRecExpr( 1989 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1990 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1991 1992 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1993 // Note that this serves two purposes: It filters out loops that are 1994 // simply not analyzable, and it covers the case where this code is 1995 // being called from within backedge-taken count analysis, such that 1996 // attempting to ask for the backedge-taken count would likely result 1997 // in infinite recursion. In the later case, the analysis code will 1998 // cope with a conservative value, and it will take care to purge 1999 // that value once it has finished. 2000 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 2001 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2002 // Manually compute the final value for AR, checking for 2003 // overflow. 2004 2005 // Check whether the backedge-taken count can be losslessly casted to 2006 // the addrec's type. The count is always unsigned. 2007 const SCEV *CastedMaxBECount = 2008 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2009 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2010 CastedMaxBECount, MaxBECount->getType(), Depth); 2011 if (MaxBECount == RecastedMaxBECount) { 2012 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2013 // Check whether Start+Step*MaxBECount has no signed overflow. 2014 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2015 SCEV::FlagAnyWrap, Depth + 1); 2016 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2017 SCEV::FlagAnyWrap, 2018 Depth + 1), 2019 WideTy, Depth + 1); 2020 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2021 const SCEV *WideMaxBECount = 2022 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2023 const SCEV *OperandExtendedAdd = 2024 getAddExpr(WideStart, 2025 getMulExpr(WideMaxBECount, 2026 getSignExtendExpr(Step, WideTy, Depth + 1), 2027 SCEV::FlagAnyWrap, Depth + 1), 2028 SCEV::FlagAnyWrap, Depth + 1); 2029 if (SAdd == OperandExtendedAdd) { 2030 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2031 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2032 // Return the expression with the addrec on the outside. 2033 return getAddRecExpr( 2034 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2035 Depth + 1), 2036 getSignExtendExpr(Step, Ty, Depth + 1), L, 2037 AR->getNoWrapFlags()); 2038 } 2039 // Similar to above, only this time treat the step value as unsigned. 2040 // This covers loops that count up with an unsigned step. 2041 OperandExtendedAdd = 2042 getAddExpr(WideStart, 2043 getMulExpr(WideMaxBECount, 2044 getZeroExtendExpr(Step, WideTy, Depth + 1), 2045 SCEV::FlagAnyWrap, Depth + 1), 2046 SCEV::FlagAnyWrap, Depth + 1); 2047 if (SAdd == OperandExtendedAdd) { 2048 // If AR wraps around then 2049 // 2050 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2051 // => SAdd != OperandExtendedAdd 2052 // 2053 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2054 // (SAdd == OperandExtendedAdd => AR is NW) 2055 2056 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 2057 2058 // Return the expression with the addrec on the outside. 2059 return getAddRecExpr( 2060 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2061 Depth + 1), 2062 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2063 AR->getNoWrapFlags()); 2064 } 2065 } 2066 } 2067 2068 auto NewFlags = proveNoSignedWrapViaInduction(AR); 2069 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 2070 if (AR->hasNoSignedWrap()) { 2071 // Same as nsw case above - duplicated here to avoid a compile time 2072 // issue. It's not clear that the order of checks does matter, but 2073 // it's one of two issue possible causes for a change which was 2074 // reverted. Be conservative for the moment. 2075 return getAddRecExpr( 2076 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2077 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2078 } 2079 2080 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2081 // if D + (C - D + Step * n) could be proven to not signed wrap 2082 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2083 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2084 const APInt &C = SC->getAPInt(); 2085 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2086 if (D != 0) { 2087 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2088 const SCEV *SResidual = 2089 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2090 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2091 return getAddExpr(SSExtD, SSExtR, 2092 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2093 Depth + 1); 2094 } 2095 } 2096 2097 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2098 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2099 return getAddRecExpr( 2100 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2101 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2102 } 2103 } 2104 2105 // If the input value is provably positive and we could not simplify 2106 // away the sext build a zext instead. 2107 if (isKnownNonNegative(Op)) 2108 return getZeroExtendExpr(Op, Ty, Depth + 1); 2109 2110 // The cast wasn't folded; create an explicit cast node. 2111 // Recompute the insert position, as it may have been invalidated. 2112 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2113 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2114 Op, Ty); 2115 UniqueSCEVs.InsertNode(S, IP); 2116 registerUser(S, { Op }); 2117 return S; 2118 } 2119 2120 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2121 /// unspecified bits out to the given type. 2122 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2123 Type *Ty) { 2124 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2125 "This is not an extending conversion!"); 2126 assert(isSCEVable(Ty) && 2127 "This is not a conversion to a SCEVable type!"); 2128 Ty = getEffectiveSCEVType(Ty); 2129 2130 // Sign-extend negative constants. 2131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2132 if (SC->getAPInt().isNegative()) 2133 return getSignExtendExpr(Op, Ty); 2134 2135 // Peel off a truncate cast. 2136 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2137 const SCEV *NewOp = T->getOperand(); 2138 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2139 return getAnyExtendExpr(NewOp, Ty); 2140 return getTruncateOrNoop(NewOp, Ty); 2141 } 2142 2143 // Next try a zext cast. If the cast is folded, use it. 2144 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2145 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2146 return ZExt; 2147 2148 // Next try a sext cast. If the cast is folded, use it. 2149 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2150 if (!isa<SCEVSignExtendExpr>(SExt)) 2151 return SExt; 2152 2153 // Force the cast to be folded into the operands of an addrec. 2154 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2155 SmallVector<const SCEV *, 4> Ops; 2156 for (const SCEV *Op : AR->operands()) 2157 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2158 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2159 } 2160 2161 // If the expression is obviously signed, use the sext cast value. 2162 if (isa<SCEVSMaxExpr>(Op)) 2163 return SExt; 2164 2165 // Absent any other information, use the zext cast value. 2166 return ZExt; 2167 } 2168 2169 /// Process the given Ops list, which is a list of operands to be added under 2170 /// the given scale, update the given map. This is a helper function for 2171 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2172 /// that would form an add expression like this: 2173 /// 2174 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2175 /// 2176 /// where A and B are constants, update the map with these values: 2177 /// 2178 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2179 /// 2180 /// and add 13 + A*B*29 to AccumulatedConstant. 2181 /// This will allow getAddRecExpr to produce this: 2182 /// 2183 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2184 /// 2185 /// This form often exposes folding opportunities that are hidden in 2186 /// the original operand list. 2187 /// 2188 /// Return true iff it appears that any interesting folding opportunities 2189 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2190 /// the common case where no interesting opportunities are present, and 2191 /// is also used as a check to avoid infinite recursion. 2192 static bool 2193 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2194 SmallVectorImpl<const SCEV *> &NewOps, 2195 APInt &AccumulatedConstant, 2196 const SCEV *const *Ops, size_t NumOperands, 2197 const APInt &Scale, 2198 ScalarEvolution &SE) { 2199 bool Interesting = false; 2200 2201 // Iterate over the add operands. They are sorted, with constants first. 2202 unsigned i = 0; 2203 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2204 ++i; 2205 // Pull a buried constant out to the outside. 2206 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2207 Interesting = true; 2208 AccumulatedConstant += Scale * C->getAPInt(); 2209 } 2210 2211 // Next comes everything else. We're especially interested in multiplies 2212 // here, but they're in the middle, so just visit the rest with one loop. 2213 for (; i != NumOperands; ++i) { 2214 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2215 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2216 APInt NewScale = 2217 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2218 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2219 // A multiplication of a constant with another add; recurse. 2220 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2221 Interesting |= 2222 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2223 Add->op_begin(), Add->getNumOperands(), 2224 NewScale, SE); 2225 } else { 2226 // A multiplication of a constant with some other value. Update 2227 // the map. 2228 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands())); 2229 const SCEV *Key = SE.getMulExpr(MulOps); 2230 auto Pair = M.insert({Key, NewScale}); 2231 if (Pair.second) { 2232 NewOps.push_back(Pair.first->first); 2233 } else { 2234 Pair.first->second += NewScale; 2235 // The map already had an entry for this value, which may indicate 2236 // a folding opportunity. 2237 Interesting = true; 2238 } 2239 } 2240 } else { 2241 // An ordinary operand. Update the map. 2242 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2243 M.insert({Ops[i], Scale}); 2244 if (Pair.second) { 2245 NewOps.push_back(Pair.first->first); 2246 } else { 2247 Pair.first->second += Scale; 2248 // The map already had an entry for this value, which may indicate 2249 // a folding opportunity. 2250 Interesting = true; 2251 } 2252 } 2253 } 2254 2255 return Interesting; 2256 } 2257 2258 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, 2259 const SCEV *LHS, const SCEV *RHS) { 2260 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *, 2261 SCEV::NoWrapFlags, unsigned); 2262 switch (BinOp) { 2263 default: 2264 llvm_unreachable("Unsupported binary op"); 2265 case Instruction::Add: 2266 Operation = &ScalarEvolution::getAddExpr; 2267 break; 2268 case Instruction::Sub: 2269 Operation = &ScalarEvolution::getMinusSCEV; 2270 break; 2271 case Instruction::Mul: 2272 Operation = &ScalarEvolution::getMulExpr; 2273 break; 2274 } 2275 2276 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) = 2277 Signed ? &ScalarEvolution::getSignExtendExpr 2278 : &ScalarEvolution::getZeroExtendExpr; 2279 2280 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS) 2281 auto *NarrowTy = cast<IntegerType>(LHS->getType()); 2282 auto *WideTy = 2283 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2); 2284 2285 const SCEV *A = (this->*Extension)( 2286 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0); 2287 const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0), 2288 (this->*Extension)(RHS, WideTy, 0), 2289 SCEV::FlagAnyWrap, 0); 2290 return A == B; 2291 } 2292 2293 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/> 2294 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp( 2295 const OverflowingBinaryOperator *OBO) { 2296 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap; 2297 2298 if (OBO->hasNoUnsignedWrap()) 2299 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2300 if (OBO->hasNoSignedWrap()) 2301 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2302 2303 bool Deduced = false; 2304 2305 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap()) 2306 return {Flags, Deduced}; 2307 2308 if (OBO->getOpcode() != Instruction::Add && 2309 OBO->getOpcode() != Instruction::Sub && 2310 OBO->getOpcode() != Instruction::Mul) 2311 return {Flags, Deduced}; 2312 2313 const SCEV *LHS = getSCEV(OBO->getOperand(0)); 2314 const SCEV *RHS = getSCEV(OBO->getOperand(1)); 2315 2316 if (!OBO->hasNoUnsignedWrap() && 2317 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2318 /* Signed */ false, LHS, RHS)) { 2319 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2320 Deduced = true; 2321 } 2322 2323 if (!OBO->hasNoSignedWrap() && 2324 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2325 /* Signed */ true, LHS, RHS)) { 2326 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2327 Deduced = true; 2328 } 2329 2330 return {Flags, Deduced}; 2331 } 2332 2333 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2334 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2335 // can't-overflow flags for the operation if possible. 2336 static SCEV::NoWrapFlags 2337 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2338 const ArrayRef<const SCEV *> Ops, 2339 SCEV::NoWrapFlags Flags) { 2340 using namespace std::placeholders; 2341 2342 using OBO = OverflowingBinaryOperator; 2343 2344 bool CanAnalyze = 2345 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2346 (void)CanAnalyze; 2347 assert(CanAnalyze && "don't call from other places!"); 2348 2349 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2350 SCEV::NoWrapFlags SignOrUnsignWrap = 2351 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2352 2353 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2354 auto IsKnownNonNegative = [&](const SCEV *S) { 2355 return SE->isKnownNonNegative(S); 2356 }; 2357 2358 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2359 Flags = 2360 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2361 2362 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2363 2364 if (SignOrUnsignWrap != SignOrUnsignMask && 2365 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2366 isa<SCEVConstant>(Ops[0])) { 2367 2368 auto Opcode = [&] { 2369 switch (Type) { 2370 case scAddExpr: 2371 return Instruction::Add; 2372 case scMulExpr: 2373 return Instruction::Mul; 2374 default: 2375 llvm_unreachable("Unexpected SCEV op."); 2376 } 2377 }(); 2378 2379 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2380 2381 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2382 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2383 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2384 Opcode, C, OBO::NoSignedWrap); 2385 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2386 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2387 } 2388 2389 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2390 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2391 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2392 Opcode, C, OBO::NoUnsignedWrap); 2393 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2394 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2395 } 2396 } 2397 2398 // <0,+,nonnegative><nw> is also nuw 2399 // TODO: Add corresponding nsw case 2400 if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) && 2401 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 && 2402 Ops[0]->isZero() && IsKnownNonNegative(Ops[1])) 2403 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2404 2405 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW 2406 if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && 2407 Ops.size() == 2) { 2408 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0])) 2409 if (UDiv->getOperand(1) == Ops[1]) 2410 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2411 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1])) 2412 if (UDiv->getOperand(1) == Ops[0]) 2413 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2414 } 2415 2416 return Flags; 2417 } 2418 2419 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2420 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2421 } 2422 2423 /// Get a canonical add expression, or something simpler if possible. 2424 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2425 SCEV::NoWrapFlags OrigFlags, 2426 unsigned Depth) { 2427 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2428 "only nuw or nsw allowed"); 2429 assert(!Ops.empty() && "Cannot get empty add!"); 2430 if (Ops.size() == 1) return Ops[0]; 2431 #ifndef NDEBUG 2432 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2433 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2434 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2435 "SCEVAddExpr operand types don't match!"); 2436 unsigned NumPtrs = count_if( 2437 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); }); 2438 assert(NumPtrs <= 1 && "add has at most one pointer operand"); 2439 #endif 2440 2441 // Sort by complexity, this groups all similar expression types together. 2442 GroupByComplexity(Ops, &LI, DT); 2443 2444 // If there are any constants, fold them together. 2445 unsigned Idx = 0; 2446 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2447 ++Idx; 2448 assert(Idx < Ops.size()); 2449 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2450 // We found two constants, fold them together! 2451 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2452 if (Ops.size() == 2) return Ops[0]; 2453 Ops.erase(Ops.begin()+1); // Erase the folded element 2454 LHSC = cast<SCEVConstant>(Ops[0]); 2455 } 2456 2457 // If we are left with a constant zero being added, strip it off. 2458 if (LHSC->getValue()->isZero()) { 2459 Ops.erase(Ops.begin()); 2460 --Idx; 2461 } 2462 2463 if (Ops.size() == 1) return Ops[0]; 2464 } 2465 2466 // Delay expensive flag strengthening until necessary. 2467 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2468 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2469 }; 2470 2471 // Limit recursion calls depth. 2472 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2473 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2474 2475 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) { 2476 // Don't strengthen flags if we have no new information. 2477 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2478 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2479 Add->setNoWrapFlags(ComputeFlags(Ops)); 2480 return S; 2481 } 2482 2483 // Okay, check to see if the same value occurs in the operand list more than 2484 // once. If so, merge them together into an multiply expression. Since we 2485 // sorted the list, these values are required to be adjacent. 2486 Type *Ty = Ops[0]->getType(); 2487 bool FoundMatch = false; 2488 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2489 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2490 // Scan ahead to count how many equal operands there are. 2491 unsigned Count = 2; 2492 while (i+Count != e && Ops[i+Count] == Ops[i]) 2493 ++Count; 2494 // Merge the values into a multiply. 2495 const SCEV *Scale = getConstant(Ty, Count); 2496 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2497 if (Ops.size() == Count) 2498 return Mul; 2499 Ops[i] = Mul; 2500 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2501 --i; e -= Count - 1; 2502 FoundMatch = true; 2503 } 2504 if (FoundMatch) 2505 return getAddExpr(Ops, OrigFlags, Depth + 1); 2506 2507 // Check for truncates. If all the operands are truncated from the same 2508 // type, see if factoring out the truncate would permit the result to be 2509 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2510 // if the contents of the resulting outer trunc fold to something simple. 2511 auto FindTruncSrcType = [&]() -> Type * { 2512 // We're ultimately looking to fold an addrec of truncs and muls of only 2513 // constants and truncs, so if we find any other types of SCEV 2514 // as operands of the addrec then we bail and return nullptr here. 2515 // Otherwise, we return the type of the operand of a trunc that we find. 2516 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2517 return T->getOperand()->getType(); 2518 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2519 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2520 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2521 return T->getOperand()->getType(); 2522 } 2523 return nullptr; 2524 }; 2525 if (auto *SrcType = FindTruncSrcType()) { 2526 SmallVector<const SCEV *, 8> LargeOps; 2527 bool Ok = true; 2528 // Check all the operands to see if they can be represented in the 2529 // source type of the truncate. 2530 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2531 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2532 if (T->getOperand()->getType() != SrcType) { 2533 Ok = false; 2534 break; 2535 } 2536 LargeOps.push_back(T->getOperand()); 2537 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2538 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2539 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2540 SmallVector<const SCEV *, 8> LargeMulOps; 2541 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2542 if (const SCEVTruncateExpr *T = 2543 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2544 if (T->getOperand()->getType() != SrcType) { 2545 Ok = false; 2546 break; 2547 } 2548 LargeMulOps.push_back(T->getOperand()); 2549 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2550 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2551 } else { 2552 Ok = false; 2553 break; 2554 } 2555 } 2556 if (Ok) 2557 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2558 } else { 2559 Ok = false; 2560 break; 2561 } 2562 } 2563 if (Ok) { 2564 // Evaluate the expression in the larger type. 2565 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2566 // If it folds to something simple, use it. Otherwise, don't. 2567 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2568 return getTruncateExpr(Fold, Ty); 2569 } 2570 } 2571 2572 if (Ops.size() == 2) { 2573 // Check if we have an expression of the form ((X + C1) - C2), where C1 and 2574 // C2 can be folded in a way that allows retaining wrapping flags of (X + 2575 // C1). 2576 const SCEV *A = Ops[0]; 2577 const SCEV *B = Ops[1]; 2578 auto *AddExpr = dyn_cast<SCEVAddExpr>(B); 2579 auto *C = dyn_cast<SCEVConstant>(A); 2580 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) { 2581 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt(); 2582 auto C2 = C->getAPInt(); 2583 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap; 2584 2585 APInt ConstAdd = C1 + C2; 2586 auto AddFlags = AddExpr->getNoWrapFlags(); 2587 // Adding a smaller constant is NUW if the original AddExpr was NUW. 2588 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) && 2589 ConstAdd.ule(C1)) { 2590 PreservedFlags = 2591 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW); 2592 } 2593 2594 // Adding a constant with the same sign and small magnitude is NSW, if the 2595 // original AddExpr was NSW. 2596 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) && 2597 C1.isSignBitSet() == ConstAdd.isSignBitSet() && 2598 ConstAdd.abs().ule(C1.abs())) { 2599 PreservedFlags = 2600 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW); 2601 } 2602 2603 if (PreservedFlags != SCEV::FlagAnyWrap) { 2604 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands()); 2605 NewOps[0] = getConstant(ConstAdd); 2606 return getAddExpr(NewOps, PreservedFlags); 2607 } 2608 } 2609 } 2610 2611 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y) 2612 if (Ops.size() == 2) { 2613 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]); 2614 if (Mul && Mul->getNumOperands() == 2 && 2615 Mul->getOperand(0)->isAllOnesValue()) { 2616 const SCEV *X; 2617 const SCEV *Y; 2618 if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) { 2619 return getMulExpr(Y, getUDivExpr(X, Y)); 2620 } 2621 } 2622 } 2623 2624 // Skip past any other cast SCEVs. 2625 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2626 ++Idx; 2627 2628 // If there are add operands they would be next. 2629 if (Idx < Ops.size()) { 2630 bool DeletedAdd = false; 2631 // If the original flags and all inlined SCEVAddExprs are NUW, use the 2632 // common NUW flag for expression after inlining. Other flags cannot be 2633 // preserved, because they may depend on the original order of operations. 2634 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW); 2635 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2636 if (Ops.size() > AddOpsInlineThreshold || 2637 Add->getNumOperands() > AddOpsInlineThreshold) 2638 break; 2639 // If we have an add, expand the add operands onto the end of the operands 2640 // list. 2641 Ops.erase(Ops.begin()+Idx); 2642 Ops.append(Add->op_begin(), Add->op_end()); 2643 DeletedAdd = true; 2644 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags()); 2645 } 2646 2647 // If we deleted at least one add, we added operands to the end of the list, 2648 // and they are not necessarily sorted. Recurse to resort and resimplify 2649 // any operands we just acquired. 2650 if (DeletedAdd) 2651 return getAddExpr(Ops, CommonFlags, Depth + 1); 2652 } 2653 2654 // Skip over the add expression until we get to a multiply. 2655 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2656 ++Idx; 2657 2658 // Check to see if there are any folding opportunities present with 2659 // operands multiplied by constant values. 2660 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2661 uint64_t BitWidth = getTypeSizeInBits(Ty); 2662 DenseMap<const SCEV *, APInt> M; 2663 SmallVector<const SCEV *, 8> NewOps; 2664 APInt AccumulatedConstant(BitWidth, 0); 2665 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2666 Ops.data(), Ops.size(), 2667 APInt(BitWidth, 1), *this)) { 2668 struct APIntCompare { 2669 bool operator()(const APInt &LHS, const APInt &RHS) const { 2670 return LHS.ult(RHS); 2671 } 2672 }; 2673 2674 // Some interesting folding opportunity is present, so its worthwhile to 2675 // re-generate the operands list. Group the operands by constant scale, 2676 // to avoid multiplying by the same constant scale multiple times. 2677 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2678 for (const SCEV *NewOp : NewOps) 2679 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2680 // Re-generate the operands list. 2681 Ops.clear(); 2682 if (AccumulatedConstant != 0) 2683 Ops.push_back(getConstant(AccumulatedConstant)); 2684 for (auto &MulOp : MulOpLists) { 2685 if (MulOp.first == 1) { 2686 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)); 2687 } else if (MulOp.first != 0) { 2688 Ops.push_back(getMulExpr( 2689 getConstant(MulOp.first), 2690 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2691 SCEV::FlagAnyWrap, Depth + 1)); 2692 } 2693 } 2694 if (Ops.empty()) 2695 return getZero(Ty); 2696 if (Ops.size() == 1) 2697 return Ops[0]; 2698 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2699 } 2700 } 2701 2702 // If we are adding something to a multiply expression, make sure the 2703 // something is not already an operand of the multiply. If so, merge it into 2704 // the multiply. 2705 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2706 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2707 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2708 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2709 if (isa<SCEVConstant>(MulOpSCEV)) 2710 continue; 2711 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2712 if (MulOpSCEV == Ops[AddOp]) { 2713 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2714 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2715 if (Mul->getNumOperands() != 2) { 2716 // If the multiply has more than two operands, we must get the 2717 // Y*Z term. 2718 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2719 Mul->op_begin()+MulOp); 2720 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2721 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2722 } 2723 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2724 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2725 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2726 SCEV::FlagAnyWrap, Depth + 1); 2727 if (Ops.size() == 2) return OuterMul; 2728 if (AddOp < Idx) { 2729 Ops.erase(Ops.begin()+AddOp); 2730 Ops.erase(Ops.begin()+Idx-1); 2731 } else { 2732 Ops.erase(Ops.begin()+Idx); 2733 Ops.erase(Ops.begin()+AddOp-1); 2734 } 2735 Ops.push_back(OuterMul); 2736 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2737 } 2738 2739 // Check this multiply against other multiplies being added together. 2740 for (unsigned OtherMulIdx = Idx+1; 2741 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2742 ++OtherMulIdx) { 2743 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2744 // If MulOp occurs in OtherMul, we can fold the two multiplies 2745 // together. 2746 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2747 OMulOp != e; ++OMulOp) 2748 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2749 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2750 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2751 if (Mul->getNumOperands() != 2) { 2752 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2753 Mul->op_begin()+MulOp); 2754 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2755 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2756 } 2757 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2758 if (OtherMul->getNumOperands() != 2) { 2759 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2760 OtherMul->op_begin()+OMulOp); 2761 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2762 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2763 } 2764 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2765 const SCEV *InnerMulSum = 2766 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2767 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2768 SCEV::FlagAnyWrap, Depth + 1); 2769 if (Ops.size() == 2) return OuterMul; 2770 Ops.erase(Ops.begin()+Idx); 2771 Ops.erase(Ops.begin()+OtherMulIdx-1); 2772 Ops.push_back(OuterMul); 2773 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2774 } 2775 } 2776 } 2777 } 2778 2779 // If there are any add recurrences in the operands list, see if any other 2780 // added values are loop invariant. If so, we can fold them into the 2781 // recurrence. 2782 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2783 ++Idx; 2784 2785 // Scan over all recurrences, trying to fold loop invariants into them. 2786 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2787 // Scan all of the other operands to this add and add them to the vector if 2788 // they are loop invariant w.r.t. the recurrence. 2789 SmallVector<const SCEV *, 8> LIOps; 2790 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2791 const Loop *AddRecLoop = AddRec->getLoop(); 2792 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2793 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2794 LIOps.push_back(Ops[i]); 2795 Ops.erase(Ops.begin()+i); 2796 --i; --e; 2797 } 2798 2799 // If we found some loop invariants, fold them into the recurrence. 2800 if (!LIOps.empty()) { 2801 // Compute nowrap flags for the addition of the loop-invariant ops and 2802 // the addrec. Temporarily push it as an operand for that purpose. These 2803 // flags are valid in the scope of the addrec only. 2804 LIOps.push_back(AddRec); 2805 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2806 LIOps.pop_back(); 2807 2808 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2809 LIOps.push_back(AddRec->getStart()); 2810 2811 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2812 2813 // It is not in general safe to propagate flags valid on an add within 2814 // the addrec scope to one outside it. We must prove that the inner 2815 // scope is guaranteed to execute if the outer one does to be able to 2816 // safely propagate. We know the program is undefined if poison is 2817 // produced on the inner scoped addrec. We also know that *for this use* 2818 // the outer scoped add can't overflow (because of the flags we just 2819 // computed for the inner scoped add) without the program being undefined. 2820 // Proving that entry to the outer scope neccesitates entry to the inner 2821 // scope, thus proves the program undefined if the flags would be violated 2822 // in the outer scope. 2823 SCEV::NoWrapFlags AddFlags = Flags; 2824 if (AddFlags != SCEV::FlagAnyWrap) { 2825 auto *DefI = getDefiningScopeBound(LIOps); 2826 auto *ReachI = &*AddRecLoop->getHeader()->begin(); 2827 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI)) 2828 AddFlags = SCEV::FlagAnyWrap; 2829 } 2830 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1); 2831 2832 // Build the new addrec. Propagate the NUW and NSW flags if both the 2833 // outer add and the inner addrec are guaranteed to have no overflow. 2834 // Always propagate NW. 2835 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2836 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2837 2838 // If all of the other operands were loop invariant, we are done. 2839 if (Ops.size() == 1) return NewRec; 2840 2841 // Otherwise, add the folded AddRec by the non-invariant parts. 2842 for (unsigned i = 0;; ++i) 2843 if (Ops[i] == AddRec) { 2844 Ops[i] = NewRec; 2845 break; 2846 } 2847 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2848 } 2849 2850 // Okay, if there weren't any loop invariants to be folded, check to see if 2851 // there are multiple AddRec's with the same loop induction variable being 2852 // added together. If so, we can fold them. 2853 for (unsigned OtherIdx = Idx+1; 2854 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2855 ++OtherIdx) { 2856 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2857 // so that the 1st found AddRecExpr is dominated by all others. 2858 assert(DT.dominates( 2859 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2860 AddRec->getLoop()->getHeader()) && 2861 "AddRecExprs are not sorted in reverse dominance order?"); 2862 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2863 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2864 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2865 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2866 ++OtherIdx) { 2867 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2868 if (OtherAddRec->getLoop() == AddRecLoop) { 2869 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2870 i != e; ++i) { 2871 if (i >= AddRecOps.size()) { 2872 AddRecOps.append(OtherAddRec->op_begin()+i, 2873 OtherAddRec->op_end()); 2874 break; 2875 } 2876 SmallVector<const SCEV *, 2> TwoOps = { 2877 AddRecOps[i], OtherAddRec->getOperand(i)}; 2878 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2879 } 2880 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2881 } 2882 } 2883 // Step size has changed, so we cannot guarantee no self-wraparound. 2884 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2885 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2886 } 2887 } 2888 2889 // Otherwise couldn't fold anything into this recurrence. Move onto the 2890 // next one. 2891 } 2892 2893 // Okay, it looks like we really DO need an add expr. Check to see if we 2894 // already have one, otherwise create a new one. 2895 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2896 } 2897 2898 const SCEV * 2899 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2900 SCEV::NoWrapFlags Flags) { 2901 FoldingSetNodeID ID; 2902 ID.AddInteger(scAddExpr); 2903 for (const SCEV *Op : Ops) 2904 ID.AddPointer(Op); 2905 void *IP = nullptr; 2906 SCEVAddExpr *S = 2907 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2908 if (!S) { 2909 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2910 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2911 S = new (SCEVAllocator) 2912 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2913 UniqueSCEVs.InsertNode(S, IP); 2914 registerUser(S, Ops); 2915 } 2916 S->setNoWrapFlags(Flags); 2917 return S; 2918 } 2919 2920 const SCEV * 2921 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2922 const Loop *L, SCEV::NoWrapFlags Flags) { 2923 FoldingSetNodeID ID; 2924 ID.AddInteger(scAddRecExpr); 2925 for (const SCEV *Op : Ops) 2926 ID.AddPointer(Op); 2927 ID.AddPointer(L); 2928 void *IP = nullptr; 2929 SCEVAddRecExpr *S = 2930 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2931 if (!S) { 2932 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2933 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2934 S = new (SCEVAllocator) 2935 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2936 UniqueSCEVs.InsertNode(S, IP); 2937 LoopUsers[L].push_back(S); 2938 registerUser(S, Ops); 2939 } 2940 setNoWrapFlags(S, Flags); 2941 return S; 2942 } 2943 2944 const SCEV * 2945 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2946 SCEV::NoWrapFlags Flags) { 2947 FoldingSetNodeID ID; 2948 ID.AddInteger(scMulExpr); 2949 for (const SCEV *Op : Ops) 2950 ID.AddPointer(Op); 2951 void *IP = nullptr; 2952 SCEVMulExpr *S = 2953 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2954 if (!S) { 2955 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2956 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2957 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2958 O, Ops.size()); 2959 UniqueSCEVs.InsertNode(S, IP); 2960 registerUser(S, Ops); 2961 } 2962 S->setNoWrapFlags(Flags); 2963 return S; 2964 } 2965 2966 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2967 uint64_t k = i*j; 2968 if (j > 1 && k / j != i) Overflow = true; 2969 return k; 2970 } 2971 2972 /// Compute the result of "n choose k", the binomial coefficient. If an 2973 /// intermediate computation overflows, Overflow will be set and the return will 2974 /// be garbage. Overflow is not cleared on absence of overflow. 2975 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2976 // We use the multiplicative formula: 2977 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2978 // At each iteration, we take the n-th term of the numeral and divide by the 2979 // (k-n)th term of the denominator. This division will always produce an 2980 // integral result, and helps reduce the chance of overflow in the 2981 // intermediate computations. However, we can still overflow even when the 2982 // final result would fit. 2983 2984 if (n == 0 || n == k) return 1; 2985 if (k > n) return 0; 2986 2987 if (k > n/2) 2988 k = n-k; 2989 2990 uint64_t r = 1; 2991 for (uint64_t i = 1; i <= k; ++i) { 2992 r = umul_ov(r, n-(i-1), Overflow); 2993 r /= i; 2994 } 2995 return r; 2996 } 2997 2998 /// Determine if any of the operands in this SCEV are a constant or if 2999 /// any of the add or multiply expressions in this SCEV contain a constant. 3000 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 3001 struct FindConstantInAddMulChain { 3002 bool FoundConstant = false; 3003 3004 bool follow(const SCEV *S) { 3005 FoundConstant |= isa<SCEVConstant>(S); 3006 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 3007 } 3008 3009 bool isDone() const { 3010 return FoundConstant; 3011 } 3012 }; 3013 3014 FindConstantInAddMulChain F; 3015 SCEVTraversal<FindConstantInAddMulChain> ST(F); 3016 ST.visitAll(StartExpr); 3017 return F.FoundConstant; 3018 } 3019 3020 /// Get a canonical multiply expression, or something simpler if possible. 3021 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 3022 SCEV::NoWrapFlags OrigFlags, 3023 unsigned Depth) { 3024 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 3025 "only nuw or nsw allowed"); 3026 assert(!Ops.empty() && "Cannot get empty mul!"); 3027 if (Ops.size() == 1) return Ops[0]; 3028 #ifndef NDEBUG 3029 Type *ETy = Ops[0]->getType(); 3030 assert(!ETy->isPointerTy()); 3031 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3032 assert(Ops[i]->getType() == ETy && 3033 "SCEVMulExpr operand types don't match!"); 3034 #endif 3035 3036 // Sort by complexity, this groups all similar expression types together. 3037 GroupByComplexity(Ops, &LI, DT); 3038 3039 // If there are any constants, fold them together. 3040 unsigned Idx = 0; 3041 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3042 ++Idx; 3043 assert(Idx < Ops.size()); 3044 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3045 // We found two constants, fold them together! 3046 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 3047 if (Ops.size() == 2) return Ops[0]; 3048 Ops.erase(Ops.begin()+1); // Erase the folded element 3049 LHSC = cast<SCEVConstant>(Ops[0]); 3050 } 3051 3052 // If we have a multiply of zero, it will always be zero. 3053 if (LHSC->getValue()->isZero()) 3054 return LHSC; 3055 3056 // If we are left with a constant one being multiplied, strip it off. 3057 if (LHSC->getValue()->isOne()) { 3058 Ops.erase(Ops.begin()); 3059 --Idx; 3060 } 3061 3062 if (Ops.size() == 1) 3063 return Ops[0]; 3064 } 3065 3066 // Delay expensive flag strengthening until necessary. 3067 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 3068 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 3069 }; 3070 3071 // Limit recursion calls depth. 3072 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 3073 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3074 3075 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) { 3076 // Don't strengthen flags if we have no new information. 3077 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 3078 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 3079 Mul->setNoWrapFlags(ComputeFlags(Ops)); 3080 return S; 3081 } 3082 3083 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3084 if (Ops.size() == 2) { 3085 // C1*(C2+V) -> C1*C2 + C1*V 3086 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 3087 // If any of Add's ops are Adds or Muls with a constant, apply this 3088 // transformation as well. 3089 // 3090 // TODO: There are some cases where this transformation is not 3091 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 3092 // this transformation should be narrowed down. 3093 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 3094 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 3095 SCEV::FlagAnyWrap, Depth + 1), 3096 getMulExpr(LHSC, Add->getOperand(1), 3097 SCEV::FlagAnyWrap, Depth + 1), 3098 SCEV::FlagAnyWrap, Depth + 1); 3099 3100 if (Ops[0]->isAllOnesValue()) { 3101 // If we have a mul by -1 of an add, try distributing the -1 among the 3102 // add operands. 3103 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 3104 SmallVector<const SCEV *, 4> NewOps; 3105 bool AnyFolded = false; 3106 for (const SCEV *AddOp : Add->operands()) { 3107 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 3108 Depth + 1); 3109 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 3110 NewOps.push_back(Mul); 3111 } 3112 if (AnyFolded) 3113 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 3114 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 3115 // Negation preserves a recurrence's no self-wrap property. 3116 SmallVector<const SCEV *, 4> Operands; 3117 for (const SCEV *AddRecOp : AddRec->operands()) 3118 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3119 Depth + 1)); 3120 3121 return getAddRecExpr(Operands, AddRec->getLoop(), 3122 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3123 } 3124 } 3125 } 3126 } 3127 3128 // Skip over the add expression until we get to a multiply. 3129 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3130 ++Idx; 3131 3132 // If there are mul operands inline them all into this expression. 3133 if (Idx < Ops.size()) { 3134 bool DeletedMul = false; 3135 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3136 if (Ops.size() > MulOpsInlineThreshold) 3137 break; 3138 // If we have an mul, expand the mul operands onto the end of the 3139 // operands list. 3140 Ops.erase(Ops.begin()+Idx); 3141 Ops.append(Mul->op_begin(), Mul->op_end()); 3142 DeletedMul = true; 3143 } 3144 3145 // If we deleted at least one mul, we added operands to the end of the 3146 // list, and they are not necessarily sorted. Recurse to resort and 3147 // resimplify any operands we just acquired. 3148 if (DeletedMul) 3149 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3150 } 3151 3152 // If there are any add recurrences in the operands list, see if any other 3153 // added values are loop invariant. If so, we can fold them into the 3154 // recurrence. 3155 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3156 ++Idx; 3157 3158 // Scan over all recurrences, trying to fold loop invariants into them. 3159 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3160 // Scan all of the other operands to this mul and add them to the vector 3161 // if they are loop invariant w.r.t. the recurrence. 3162 SmallVector<const SCEV *, 8> LIOps; 3163 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3164 const Loop *AddRecLoop = AddRec->getLoop(); 3165 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3166 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3167 LIOps.push_back(Ops[i]); 3168 Ops.erase(Ops.begin()+i); 3169 --i; --e; 3170 } 3171 3172 // If we found some loop invariants, fold them into the recurrence. 3173 if (!LIOps.empty()) { 3174 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3175 SmallVector<const SCEV *, 4> NewOps; 3176 NewOps.reserve(AddRec->getNumOperands()); 3177 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3178 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3179 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3180 SCEV::FlagAnyWrap, Depth + 1)); 3181 3182 // Build the new addrec. Propagate the NUW and NSW flags if both the 3183 // outer mul and the inner addrec are guaranteed to have no overflow. 3184 // 3185 // No self-wrap cannot be guaranteed after changing the step size, but 3186 // will be inferred if either NUW or NSW is true. 3187 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 3188 const SCEV *NewRec = getAddRecExpr( 3189 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 3190 3191 // If all of the other operands were loop invariant, we are done. 3192 if (Ops.size() == 1) return NewRec; 3193 3194 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3195 for (unsigned i = 0;; ++i) 3196 if (Ops[i] == AddRec) { 3197 Ops[i] = NewRec; 3198 break; 3199 } 3200 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3201 } 3202 3203 // Okay, if there weren't any loop invariants to be folded, check to see 3204 // if there are multiple AddRec's with the same loop induction variable 3205 // being multiplied together. If so, we can fold them. 3206 3207 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3208 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3209 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3210 // ]]],+,...up to x=2n}. 3211 // Note that the arguments to choose() are always integers with values 3212 // known at compile time, never SCEV objects. 3213 // 3214 // The implementation avoids pointless extra computations when the two 3215 // addrec's are of different length (mathematically, it's equivalent to 3216 // an infinite stream of zeros on the right). 3217 bool OpsModified = false; 3218 for (unsigned OtherIdx = Idx+1; 3219 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3220 ++OtherIdx) { 3221 const SCEVAddRecExpr *OtherAddRec = 3222 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3223 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3224 continue; 3225 3226 // Limit max number of arguments to avoid creation of unreasonably big 3227 // SCEVAddRecs with very complex operands. 3228 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3229 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3230 continue; 3231 3232 bool Overflow = false; 3233 Type *Ty = AddRec->getType(); 3234 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3235 SmallVector<const SCEV*, 7> AddRecOps; 3236 for (int x = 0, xe = AddRec->getNumOperands() + 3237 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3238 SmallVector <const SCEV *, 7> SumOps; 3239 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3240 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3241 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3242 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3243 z < ze && !Overflow; ++z) { 3244 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3245 uint64_t Coeff; 3246 if (LargerThan64Bits) 3247 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3248 else 3249 Coeff = Coeff1*Coeff2; 3250 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3251 const SCEV *Term1 = AddRec->getOperand(y-z); 3252 const SCEV *Term2 = OtherAddRec->getOperand(z); 3253 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3254 SCEV::FlagAnyWrap, Depth + 1)); 3255 } 3256 } 3257 if (SumOps.empty()) 3258 SumOps.push_back(getZero(Ty)); 3259 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3260 } 3261 if (!Overflow) { 3262 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3263 SCEV::FlagAnyWrap); 3264 if (Ops.size() == 2) return NewAddRec; 3265 Ops[Idx] = NewAddRec; 3266 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3267 OpsModified = true; 3268 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3269 if (!AddRec) 3270 break; 3271 } 3272 } 3273 if (OpsModified) 3274 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3275 3276 // Otherwise couldn't fold anything into this recurrence. Move onto the 3277 // next one. 3278 } 3279 3280 // Okay, it looks like we really DO need an mul expr. Check to see if we 3281 // already have one, otherwise create a new one. 3282 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3283 } 3284 3285 /// Represents an unsigned remainder expression based on unsigned division. 3286 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3287 const SCEV *RHS) { 3288 assert(getEffectiveSCEVType(LHS->getType()) == 3289 getEffectiveSCEVType(RHS->getType()) && 3290 "SCEVURemExpr operand types don't match!"); 3291 3292 // Short-circuit easy cases 3293 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3294 // If constant is one, the result is trivial 3295 if (RHSC->getValue()->isOne()) 3296 return getZero(LHS->getType()); // X urem 1 --> 0 3297 3298 // If constant is a power of two, fold into a zext(trunc(LHS)). 3299 if (RHSC->getAPInt().isPowerOf2()) { 3300 Type *FullTy = LHS->getType(); 3301 Type *TruncTy = 3302 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3303 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3304 } 3305 } 3306 3307 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3308 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3309 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3310 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3311 } 3312 3313 /// Get a canonical unsigned division expression, or something simpler if 3314 /// possible. 3315 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3316 const SCEV *RHS) { 3317 assert(!LHS->getType()->isPointerTy() && 3318 "SCEVUDivExpr operand can't be pointer!"); 3319 assert(LHS->getType() == RHS->getType() && 3320 "SCEVUDivExpr operand types don't match!"); 3321 3322 FoldingSetNodeID ID; 3323 ID.AddInteger(scUDivExpr); 3324 ID.AddPointer(LHS); 3325 ID.AddPointer(RHS); 3326 void *IP = nullptr; 3327 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3328 return S; 3329 3330 // 0 udiv Y == 0 3331 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) 3332 if (LHSC->getValue()->isZero()) 3333 return LHS; 3334 3335 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3336 if (RHSC->getValue()->isOne()) 3337 return LHS; // X udiv 1 --> x 3338 // If the denominator is zero, the result of the udiv is undefined. Don't 3339 // try to analyze it, because the resolution chosen here may differ from 3340 // the resolution chosen in other parts of the compiler. 3341 if (!RHSC->getValue()->isZero()) { 3342 // Determine if the division can be folded into the operands of 3343 // its operands. 3344 // TODO: Generalize this to non-constants by using known-bits information. 3345 Type *Ty = LHS->getType(); 3346 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3347 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3348 // For non-power-of-two values, effectively round the value up to the 3349 // nearest power of two. 3350 if (!RHSC->getAPInt().isPowerOf2()) 3351 ++MaxShiftAmt; 3352 IntegerType *ExtTy = 3353 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3354 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3355 if (const SCEVConstant *Step = 3356 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3357 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3358 const APInt &StepInt = Step->getAPInt(); 3359 const APInt &DivInt = RHSC->getAPInt(); 3360 if (!StepInt.urem(DivInt) && 3361 getZeroExtendExpr(AR, ExtTy) == 3362 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3363 getZeroExtendExpr(Step, ExtTy), 3364 AR->getLoop(), SCEV::FlagAnyWrap)) { 3365 SmallVector<const SCEV *, 4> Operands; 3366 for (const SCEV *Op : AR->operands()) 3367 Operands.push_back(getUDivExpr(Op, RHS)); 3368 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3369 } 3370 /// Get a canonical UDivExpr for a recurrence. 3371 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3372 // We can currently only fold X%N if X is constant. 3373 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3374 if (StartC && !DivInt.urem(StepInt) && 3375 getZeroExtendExpr(AR, ExtTy) == 3376 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3377 getZeroExtendExpr(Step, ExtTy), 3378 AR->getLoop(), SCEV::FlagAnyWrap)) { 3379 const APInt &StartInt = StartC->getAPInt(); 3380 const APInt &StartRem = StartInt.urem(StepInt); 3381 if (StartRem != 0) { 3382 const SCEV *NewLHS = 3383 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3384 AR->getLoop(), SCEV::FlagNW); 3385 if (LHS != NewLHS) { 3386 LHS = NewLHS; 3387 3388 // Reset the ID to include the new LHS, and check if it is 3389 // already cached. 3390 ID.clear(); 3391 ID.AddInteger(scUDivExpr); 3392 ID.AddPointer(LHS); 3393 ID.AddPointer(RHS); 3394 IP = nullptr; 3395 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3396 return S; 3397 } 3398 } 3399 } 3400 } 3401 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3402 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3403 SmallVector<const SCEV *, 4> Operands; 3404 for (const SCEV *Op : M->operands()) 3405 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3406 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3407 // Find an operand that's safely divisible. 3408 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3409 const SCEV *Op = M->getOperand(i); 3410 const SCEV *Div = getUDivExpr(Op, RHSC); 3411 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3412 Operands = SmallVector<const SCEV *, 4>(M->operands()); 3413 Operands[i] = Div; 3414 return getMulExpr(Operands); 3415 } 3416 } 3417 } 3418 3419 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3420 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3421 if (auto *DivisorConstant = 3422 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3423 bool Overflow = false; 3424 APInt NewRHS = 3425 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3426 if (Overflow) { 3427 return getConstant(RHSC->getType(), 0, false); 3428 } 3429 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3430 } 3431 } 3432 3433 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3434 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3435 SmallVector<const SCEV *, 4> Operands; 3436 for (const SCEV *Op : A->operands()) 3437 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3438 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3439 Operands.clear(); 3440 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3441 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3442 if (isa<SCEVUDivExpr>(Op) || 3443 getMulExpr(Op, RHS) != A->getOperand(i)) 3444 break; 3445 Operands.push_back(Op); 3446 } 3447 if (Operands.size() == A->getNumOperands()) 3448 return getAddExpr(Operands); 3449 } 3450 } 3451 3452 // Fold if both operands are constant. 3453 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3454 Constant *LHSCV = LHSC->getValue(); 3455 Constant *RHSCV = RHSC->getValue(); 3456 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3457 RHSCV))); 3458 } 3459 } 3460 } 3461 3462 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3463 // changes). Make sure we get a new one. 3464 IP = nullptr; 3465 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3466 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3467 LHS, RHS); 3468 UniqueSCEVs.InsertNode(S, IP); 3469 registerUser(S, {LHS, RHS}); 3470 return S; 3471 } 3472 3473 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3474 APInt A = C1->getAPInt().abs(); 3475 APInt B = C2->getAPInt().abs(); 3476 uint32_t ABW = A.getBitWidth(); 3477 uint32_t BBW = B.getBitWidth(); 3478 3479 if (ABW > BBW) 3480 B = B.zext(ABW); 3481 else if (ABW < BBW) 3482 A = A.zext(BBW); 3483 3484 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3485 } 3486 3487 /// Get a canonical unsigned division expression, or something simpler if 3488 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3489 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3490 /// it's not exact because the udiv may be clearing bits. 3491 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3492 const SCEV *RHS) { 3493 // TODO: we could try to find factors in all sorts of things, but for now we 3494 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3495 // end of this file for inspiration. 3496 3497 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3498 if (!Mul || !Mul->hasNoUnsignedWrap()) 3499 return getUDivExpr(LHS, RHS); 3500 3501 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3502 // If the mulexpr multiplies by a constant, then that constant must be the 3503 // first element of the mulexpr. 3504 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3505 if (LHSCst == RHSCst) { 3506 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands())); 3507 return getMulExpr(Operands); 3508 } 3509 3510 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3511 // that there's a factor provided by one of the other terms. We need to 3512 // check. 3513 APInt Factor = gcd(LHSCst, RHSCst); 3514 if (!Factor.isIntN(1)) { 3515 LHSCst = 3516 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3517 RHSCst = 3518 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3519 SmallVector<const SCEV *, 2> Operands; 3520 Operands.push_back(LHSCst); 3521 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3522 LHS = getMulExpr(Operands); 3523 RHS = RHSCst; 3524 Mul = dyn_cast<SCEVMulExpr>(LHS); 3525 if (!Mul) 3526 return getUDivExactExpr(LHS, RHS); 3527 } 3528 } 3529 } 3530 3531 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3532 if (Mul->getOperand(i) == RHS) { 3533 SmallVector<const SCEV *, 2> Operands; 3534 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3535 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3536 return getMulExpr(Operands); 3537 } 3538 } 3539 3540 return getUDivExpr(LHS, RHS); 3541 } 3542 3543 /// Get an add recurrence expression for the specified loop. Simplify the 3544 /// expression as much as possible. 3545 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3546 const Loop *L, 3547 SCEV::NoWrapFlags Flags) { 3548 SmallVector<const SCEV *, 4> Operands; 3549 Operands.push_back(Start); 3550 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3551 if (StepChrec->getLoop() == L) { 3552 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3553 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3554 } 3555 3556 Operands.push_back(Step); 3557 return getAddRecExpr(Operands, L, Flags); 3558 } 3559 3560 /// Get an add recurrence expression for the specified loop. Simplify the 3561 /// expression as much as possible. 3562 const SCEV * 3563 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3564 const Loop *L, SCEV::NoWrapFlags Flags) { 3565 if (Operands.size() == 1) return Operands[0]; 3566 #ifndef NDEBUG 3567 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3568 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 3569 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3570 "SCEVAddRecExpr operand types don't match!"); 3571 assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer"); 3572 } 3573 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3574 assert(isLoopInvariant(Operands[i], L) && 3575 "SCEVAddRecExpr operand is not loop-invariant!"); 3576 #endif 3577 3578 if (Operands.back()->isZero()) { 3579 Operands.pop_back(); 3580 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3581 } 3582 3583 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3584 // use that information to infer NUW and NSW flags. However, computing a 3585 // BE count requires calling getAddRecExpr, so we may not yet have a 3586 // meaningful BE count at this point (and if we don't, we'd be stuck 3587 // with a SCEVCouldNotCompute as the cached BE count). 3588 3589 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3590 3591 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3592 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3593 const Loop *NestedLoop = NestedAR->getLoop(); 3594 if (L->contains(NestedLoop) 3595 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3596 : (!NestedLoop->contains(L) && 3597 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3598 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands()); 3599 Operands[0] = NestedAR->getStart(); 3600 // AddRecs require their operands be loop-invariant with respect to their 3601 // loops. Don't perform this transformation if it would break this 3602 // requirement. 3603 bool AllInvariant = all_of( 3604 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3605 3606 if (AllInvariant) { 3607 // Create a recurrence for the outer loop with the same step size. 3608 // 3609 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3610 // inner recurrence has the same property. 3611 SCEV::NoWrapFlags OuterFlags = 3612 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3613 3614 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3615 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3616 return isLoopInvariant(Op, NestedLoop); 3617 }); 3618 3619 if (AllInvariant) { 3620 // Ok, both add recurrences are valid after the transformation. 3621 // 3622 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3623 // the outer recurrence has the same property. 3624 SCEV::NoWrapFlags InnerFlags = 3625 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3626 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3627 } 3628 } 3629 // Reset Operands to its original state. 3630 Operands[0] = NestedAR; 3631 } 3632 } 3633 3634 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3635 // already have one, otherwise create a new one. 3636 return getOrCreateAddRecExpr(Operands, L, Flags); 3637 } 3638 3639 const SCEV * 3640 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3641 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3642 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3643 // getSCEV(Base)->getType() has the same address space as Base->getType() 3644 // because SCEV::getType() preserves the address space. 3645 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3646 const bool AssumeInBoundsFlags = [&]() { 3647 if (!GEP->isInBounds()) 3648 return false; 3649 3650 // We'd like to propagate flags from the IR to the corresponding SCEV nodes, 3651 // but to do that, we have to ensure that said flag is valid in the entire 3652 // defined scope of the SCEV. 3653 auto *GEPI = dyn_cast<Instruction>(GEP); 3654 // TODO: non-instructions have global scope. We might be able to prove 3655 // some global scope cases 3656 return GEPI && isSCEVExprNeverPoison(GEPI); 3657 }(); 3658 3659 SCEV::NoWrapFlags OffsetWrap = 3660 AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3661 3662 Type *CurTy = GEP->getType(); 3663 bool FirstIter = true; 3664 SmallVector<const SCEV *, 4> Offsets; 3665 for (const SCEV *IndexExpr : IndexExprs) { 3666 // Compute the (potentially symbolic) offset in bytes for this index. 3667 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3668 // For a struct, add the member offset. 3669 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3670 unsigned FieldNo = Index->getZExtValue(); 3671 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3672 Offsets.push_back(FieldOffset); 3673 3674 // Update CurTy to the type of the field at Index. 3675 CurTy = STy->getTypeAtIndex(Index); 3676 } else { 3677 // Update CurTy to its element type. 3678 if (FirstIter) { 3679 assert(isa<PointerType>(CurTy) && 3680 "The first index of a GEP indexes a pointer"); 3681 CurTy = GEP->getSourceElementType(); 3682 FirstIter = false; 3683 } else { 3684 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3685 } 3686 // For an array, add the element offset, explicitly scaled. 3687 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3688 // Getelementptr indices are signed. 3689 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3690 3691 // Multiply the index by the element size to compute the element offset. 3692 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3693 Offsets.push_back(LocalOffset); 3694 } 3695 } 3696 3697 // Handle degenerate case of GEP without offsets. 3698 if (Offsets.empty()) 3699 return BaseExpr; 3700 3701 // Add the offsets together, assuming nsw if inbounds. 3702 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3703 // Add the base address and the offset. We cannot use the nsw flag, as the 3704 // base address is unsigned. However, if we know that the offset is 3705 // non-negative, we can use nuw. 3706 SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset) 3707 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3708 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap); 3709 assert(BaseExpr->getType() == GEPExpr->getType() && 3710 "GEP should not change type mid-flight."); 3711 return GEPExpr; 3712 } 3713 3714 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3715 ArrayRef<const SCEV *> Ops) { 3716 FoldingSetNodeID ID; 3717 ID.AddInteger(SCEVType); 3718 for (const SCEV *Op : Ops) 3719 ID.AddPointer(Op); 3720 void *IP = nullptr; 3721 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3722 } 3723 3724 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3725 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3726 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3727 } 3728 3729 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3730 SmallVectorImpl<const SCEV *> &Ops) { 3731 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!"); 3732 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3733 if (Ops.size() == 1) return Ops[0]; 3734 #ifndef NDEBUG 3735 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3736 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 3737 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3738 "Operand types don't match!"); 3739 assert(Ops[0]->getType()->isPointerTy() == 3740 Ops[i]->getType()->isPointerTy() && 3741 "min/max should be consistently pointerish"); 3742 } 3743 #endif 3744 3745 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3746 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3747 3748 // Sort by complexity, this groups all similar expression types together. 3749 GroupByComplexity(Ops, &LI, DT); 3750 3751 // Check if we have created the same expression before. 3752 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) { 3753 return S; 3754 } 3755 3756 // If there are any constants, fold them together. 3757 unsigned Idx = 0; 3758 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3759 ++Idx; 3760 assert(Idx < Ops.size()); 3761 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3762 if (Kind == scSMaxExpr) 3763 return APIntOps::smax(LHS, RHS); 3764 else if (Kind == scSMinExpr) 3765 return APIntOps::smin(LHS, RHS); 3766 else if (Kind == scUMaxExpr) 3767 return APIntOps::umax(LHS, RHS); 3768 else if (Kind == scUMinExpr) 3769 return APIntOps::umin(LHS, RHS); 3770 llvm_unreachable("Unknown SCEV min/max opcode"); 3771 }; 3772 3773 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3774 // We found two constants, fold them together! 3775 ConstantInt *Fold = ConstantInt::get( 3776 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3777 Ops[0] = getConstant(Fold); 3778 Ops.erase(Ops.begin()+1); // Erase the folded element 3779 if (Ops.size() == 1) return Ops[0]; 3780 LHSC = cast<SCEVConstant>(Ops[0]); 3781 } 3782 3783 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3784 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3785 3786 if (IsMax ? IsMinV : IsMaxV) { 3787 // If we are left with a constant minimum(/maximum)-int, strip it off. 3788 Ops.erase(Ops.begin()); 3789 --Idx; 3790 } else if (IsMax ? IsMaxV : IsMinV) { 3791 // If we have a max(/min) with a constant maximum(/minimum)-int, 3792 // it will always be the extremum. 3793 return LHSC; 3794 } 3795 3796 if (Ops.size() == 1) return Ops[0]; 3797 } 3798 3799 // Find the first operation of the same kind 3800 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3801 ++Idx; 3802 3803 // Check to see if one of the operands is of the same kind. If so, expand its 3804 // operands onto our operand list, and recurse to simplify. 3805 if (Idx < Ops.size()) { 3806 bool DeletedAny = false; 3807 while (Ops[Idx]->getSCEVType() == Kind) { 3808 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3809 Ops.erase(Ops.begin()+Idx); 3810 Ops.append(SMME->op_begin(), SMME->op_end()); 3811 DeletedAny = true; 3812 } 3813 3814 if (DeletedAny) 3815 return getMinMaxExpr(Kind, Ops); 3816 } 3817 3818 // Okay, check to see if the same value occurs in the operand list twice. If 3819 // so, delete one. Since we sorted the list, these values are required to 3820 // be adjacent. 3821 llvm::CmpInst::Predicate GEPred = 3822 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3823 llvm::CmpInst::Predicate LEPred = 3824 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3825 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3826 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3827 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3828 if (Ops[i] == Ops[i + 1] || 3829 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3830 // X op Y op Y --> X op Y 3831 // X op Y --> X, if we know X, Y are ordered appropriately 3832 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3833 --i; 3834 --e; 3835 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3836 Ops[i + 1])) { 3837 // X op Y --> Y, if we know X, Y are ordered appropriately 3838 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3839 --i; 3840 --e; 3841 } 3842 } 3843 3844 if (Ops.size() == 1) return Ops[0]; 3845 3846 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3847 3848 // Okay, it looks like we really DO need an expr. Check to see if we 3849 // already have one, otherwise create a new one. 3850 FoldingSetNodeID ID; 3851 ID.AddInteger(Kind); 3852 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3853 ID.AddPointer(Ops[i]); 3854 void *IP = nullptr; 3855 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3856 if (ExistingSCEV) 3857 return ExistingSCEV; 3858 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3859 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3860 SCEV *S = new (SCEVAllocator) 3861 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3862 3863 UniqueSCEVs.InsertNode(S, IP); 3864 registerUser(S, Ops); 3865 return S; 3866 } 3867 3868 namespace { 3869 3870 class SCEVSequentialMinMaxDeduplicatingVisitor final 3871 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, 3872 Optional<const SCEV *>> { 3873 using RetVal = Optional<const SCEV *>; 3874 using Base = SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, RetVal>; 3875 3876 ScalarEvolution &SE; 3877 const SCEVTypes RootKind; // Must be a sequential min/max expression. 3878 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind. 3879 SmallPtrSet<const SCEV *, 16> SeenOps; 3880 3881 bool canRecurseInto(SCEVTypes Kind) const { 3882 // We can only recurse into the SCEV expression of the same effective type 3883 // as the type of our root SCEV expression. 3884 return RootKind == Kind || NonSequentialRootKind == Kind; 3885 }; 3886 3887 RetVal visitAnyMinMaxExpr(const SCEV *S) { 3888 assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) && 3889 "Only for min/max expressions."); 3890 SCEVTypes Kind = S->getSCEVType(); 3891 3892 if (!canRecurseInto(Kind)) 3893 return S; 3894 3895 auto *NAry = cast<SCEVNAryExpr>(S); 3896 SmallVector<const SCEV *> NewOps; 3897 bool Changed = 3898 visit(Kind, makeArrayRef(NAry->op_begin(), NAry->op_end()), NewOps); 3899 3900 if (!Changed) 3901 return S; 3902 if (NewOps.empty()) 3903 return None; 3904 3905 return isa<SCEVSequentialMinMaxExpr>(S) 3906 ? SE.getSequentialMinMaxExpr(Kind, NewOps) 3907 : SE.getMinMaxExpr(Kind, NewOps); 3908 } 3909 3910 RetVal visit(const SCEV *S) { 3911 // Has the whole operand been seen already? 3912 if (!SeenOps.insert(S).second) 3913 return None; 3914 return Base::visit(S); 3915 } 3916 3917 public: 3918 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE, 3919 SCEVTypes RootKind) 3920 : SE(SE), RootKind(RootKind), 3921 NonSequentialRootKind( 3922 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType( 3923 RootKind)) {} 3924 3925 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps, 3926 SmallVectorImpl<const SCEV *> &NewOps) { 3927 bool Changed = false; 3928 SmallVector<const SCEV *> Ops; 3929 Ops.reserve(OrigOps.size()); 3930 3931 for (const SCEV *Op : OrigOps) { 3932 RetVal NewOp = visit(Op); 3933 if (NewOp != Op) 3934 Changed = true; 3935 if (NewOp) 3936 Ops.emplace_back(*NewOp); 3937 } 3938 3939 if (Changed) 3940 NewOps = std::move(Ops); 3941 return Changed; 3942 } 3943 3944 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; } 3945 3946 RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; } 3947 3948 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; } 3949 3950 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; } 3951 3952 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; } 3953 3954 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; } 3955 3956 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; } 3957 3958 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; } 3959 3960 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 3961 3962 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) { 3963 return visitAnyMinMaxExpr(Expr); 3964 } 3965 3966 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) { 3967 return visitAnyMinMaxExpr(Expr); 3968 } 3969 3970 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) { 3971 return visitAnyMinMaxExpr(Expr); 3972 } 3973 3974 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) { 3975 return visitAnyMinMaxExpr(Expr); 3976 } 3977 3978 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) { 3979 return visitAnyMinMaxExpr(Expr); 3980 } 3981 3982 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; } 3983 3984 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; } 3985 }; 3986 3987 } // namespace 3988 3989 const SCEV * 3990 ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind, 3991 SmallVectorImpl<const SCEV *> &Ops) { 3992 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) && 3993 "Not a SCEVSequentialMinMaxExpr!"); 3994 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3995 if (Ops.size() == 1) 3996 return Ops[0]; 3997 if (Ops.size() == 2 && 3998 any_of(Ops, [](const SCEV *Op) { return isa<SCEVConstant>(Op); })) 3999 return getMinMaxExpr( 4000 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind), 4001 Ops); 4002 #ifndef NDEBUG 4003 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 4004 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 4005 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 4006 "Operand types don't match!"); 4007 assert(Ops[0]->getType()->isPointerTy() == 4008 Ops[i]->getType()->isPointerTy() && 4009 "min/max should be consistently pointerish"); 4010 } 4011 #endif 4012 4013 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative, 4014 // so we can *NOT* do any kind of sorting of the expressions! 4015 4016 // Check if we have created the same expression before. 4017 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) 4018 return S; 4019 4020 // FIXME: there are *some* simplifications that we can do here. 4021 4022 // Keep only the first instance of an operand. 4023 { 4024 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind); 4025 bool Changed = Deduplicator.visit(Kind, Ops, Ops); 4026 if (Changed) 4027 return getSequentialMinMaxExpr(Kind, Ops); 4028 } 4029 4030 // Check to see if one of the operands is of the same kind. If so, expand its 4031 // operands onto our operand list, and recurse to simplify. 4032 { 4033 unsigned Idx = 0; 4034 bool DeletedAny = false; 4035 while (Idx < Ops.size()) { 4036 if (Ops[Idx]->getSCEVType() != Kind) { 4037 ++Idx; 4038 continue; 4039 } 4040 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]); 4041 Ops.erase(Ops.begin() + Idx); 4042 Ops.insert(Ops.begin() + Idx, SMME->op_begin(), SMME->op_end()); 4043 DeletedAny = true; 4044 } 4045 4046 if (DeletedAny) 4047 return getSequentialMinMaxExpr(Kind, Ops); 4048 } 4049 4050 // Okay, it looks like we really DO need an expr. Check to see if we 4051 // already have one, otherwise create a new one. 4052 FoldingSetNodeID ID; 4053 ID.AddInteger(Kind); 4054 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 4055 ID.AddPointer(Ops[i]); 4056 void *IP = nullptr; 4057 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 4058 if (ExistingSCEV) 4059 return ExistingSCEV; 4060 4061 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 4062 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 4063 SCEV *S = new (SCEVAllocator) 4064 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 4065 4066 UniqueSCEVs.InsertNode(S, IP); 4067 registerUser(S, Ops); 4068 return S; 4069 } 4070 4071 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 4072 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 4073 return getSMaxExpr(Ops); 4074 } 4075 4076 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 4077 return getMinMaxExpr(scSMaxExpr, Ops); 4078 } 4079 4080 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 4081 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 4082 return getUMaxExpr(Ops); 4083 } 4084 4085 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 4086 return getMinMaxExpr(scUMaxExpr, Ops); 4087 } 4088 4089 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 4090 const SCEV *RHS) { 4091 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4092 return getSMinExpr(Ops); 4093 } 4094 4095 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 4096 return getMinMaxExpr(scSMinExpr, Ops); 4097 } 4098 4099 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS, 4100 bool Sequential) { 4101 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4102 return getUMinExpr(Ops, Sequential); 4103 } 4104 4105 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops, 4106 bool Sequential) { 4107 return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops) 4108 : getMinMaxExpr(scUMinExpr, Ops); 4109 } 4110 4111 const SCEV * 4112 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 4113 ScalableVectorType *ScalableTy) { 4114 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 4115 Constant *One = ConstantInt::get(IntTy, 1); 4116 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 4117 // Note that the expression we created is the final expression, we don't 4118 // want to simplify it any further Also, if we call a normal getSCEV(), 4119 // we'll end up in an endless recursion. So just create an SCEVUnknown. 4120 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 4121 } 4122 4123 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 4124 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 4125 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 4126 // We can bypass creating a target-independent constant expression and then 4127 // folding it back into a ConstantInt. This is just a compile-time 4128 // optimization. 4129 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 4130 } 4131 4132 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 4133 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 4134 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 4135 // We can bypass creating a target-independent constant expression and then 4136 // folding it back into a ConstantInt. This is just a compile-time 4137 // optimization. 4138 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 4139 } 4140 4141 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 4142 StructType *STy, 4143 unsigned FieldNo) { 4144 // We can bypass creating a target-independent constant expression and then 4145 // folding it back into a ConstantInt. This is just a compile-time 4146 // optimization. 4147 return getConstant( 4148 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 4149 } 4150 4151 const SCEV *ScalarEvolution::getUnknown(Value *V) { 4152 // Don't attempt to do anything other than create a SCEVUnknown object 4153 // here. createSCEV only calls getUnknown after checking for all other 4154 // interesting possibilities, and any other code that calls getUnknown 4155 // is doing so in order to hide a value from SCEV canonicalization. 4156 4157 FoldingSetNodeID ID; 4158 ID.AddInteger(scUnknown); 4159 ID.AddPointer(V); 4160 void *IP = nullptr; 4161 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 4162 assert(cast<SCEVUnknown>(S)->getValue() == V && 4163 "Stale SCEVUnknown in uniquing map!"); 4164 return S; 4165 } 4166 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 4167 FirstUnknown); 4168 FirstUnknown = cast<SCEVUnknown>(S); 4169 UniqueSCEVs.InsertNode(S, IP); 4170 return S; 4171 } 4172 4173 //===----------------------------------------------------------------------===// 4174 // Basic SCEV Analysis and PHI Idiom Recognition Code 4175 // 4176 4177 /// Test if values of the given type are analyzable within the SCEV 4178 /// framework. This primarily includes integer types, and it can optionally 4179 /// include pointer types if the ScalarEvolution class has access to 4180 /// target-specific information. 4181 bool ScalarEvolution::isSCEVable(Type *Ty) const { 4182 // Integers and pointers are always SCEVable. 4183 return Ty->isIntOrPtrTy(); 4184 } 4185 4186 /// Return the size in bits of the specified type, for which isSCEVable must 4187 /// return true. 4188 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 4189 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 4190 if (Ty->isPointerTy()) 4191 return getDataLayout().getIndexTypeSizeInBits(Ty); 4192 return getDataLayout().getTypeSizeInBits(Ty); 4193 } 4194 4195 /// Return a type with the same bitwidth as the given type and which represents 4196 /// how SCEV will treat the given type, for which isSCEVable must return 4197 /// true. For pointer types, this is the pointer index sized integer type. 4198 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 4199 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 4200 4201 if (Ty->isIntegerTy()) 4202 return Ty; 4203 4204 // The only other support type is pointer. 4205 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 4206 return getDataLayout().getIndexType(Ty); 4207 } 4208 4209 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 4210 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 4211 } 4212 4213 bool ScalarEvolution::instructionCouldExistWitthOperands(const SCEV *A, 4214 const SCEV *B) { 4215 /// For a valid use point to exist, the defining scope of one operand 4216 /// must dominate the other. 4217 bool PreciseA, PreciseB; 4218 auto *ScopeA = getDefiningScopeBound({A}, PreciseA); 4219 auto *ScopeB = getDefiningScopeBound({B}, PreciseB); 4220 if (!PreciseA || !PreciseB) 4221 // Can't tell. 4222 return false; 4223 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) || 4224 DT.dominates(ScopeB, ScopeA); 4225 } 4226 4227 4228 const SCEV *ScalarEvolution::getCouldNotCompute() { 4229 return CouldNotCompute.get(); 4230 } 4231 4232 bool ScalarEvolution::checkValidity(const SCEV *S) const { 4233 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 4234 auto *SU = dyn_cast<SCEVUnknown>(S); 4235 return SU && SU->getValue() == nullptr; 4236 }); 4237 4238 return !ContainsNulls; 4239 } 4240 4241 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 4242 HasRecMapType::iterator I = HasRecMap.find(S); 4243 if (I != HasRecMap.end()) 4244 return I->second; 4245 4246 bool FoundAddRec = 4247 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 4248 HasRecMap.insert({S, FoundAddRec}); 4249 return FoundAddRec; 4250 } 4251 4252 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 4253 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 4254 /// offset I, then return {S', I}, else return {\p S, nullptr}. 4255 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 4256 const auto *Add = dyn_cast<SCEVAddExpr>(S); 4257 if (!Add) 4258 return {S, nullptr}; 4259 4260 if (Add->getNumOperands() != 2) 4261 return {S, nullptr}; 4262 4263 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 4264 if (!ConstOp) 4265 return {S, nullptr}; 4266 4267 return {Add->getOperand(1), ConstOp->getValue()}; 4268 } 4269 4270 /// Return the ValueOffsetPair set for \p S. \p S can be represented 4271 /// by the value and offset from any ValueOffsetPair in the set. 4272 ScalarEvolution::ValueOffsetPairSetVector * 4273 ScalarEvolution::getSCEVValues(const SCEV *S) { 4274 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 4275 if (SI == ExprValueMap.end()) 4276 return nullptr; 4277 #ifndef NDEBUG 4278 if (VerifySCEVMap) { 4279 // Check there is no dangling Value in the set returned. 4280 for (const auto &VE : SI->second) 4281 assert(ValueExprMap.count(VE.first)); 4282 } 4283 #endif 4284 return &SI->second; 4285 } 4286 4287 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 4288 /// cannot be used separately. eraseValueFromMap should be used to remove 4289 /// V from ValueExprMap and ExprValueMap at the same time. 4290 void ScalarEvolution::eraseValueFromMap(Value *V) { 4291 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4292 if (I != ValueExprMap.end()) { 4293 const SCEV *S = I->second; 4294 // Remove {V, 0} from the set of ExprValueMap[S] 4295 if (auto *SV = getSCEVValues(S)) 4296 SV->remove({V, nullptr}); 4297 4298 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 4299 const SCEV *Stripped; 4300 ConstantInt *Offset; 4301 std::tie(Stripped, Offset) = splitAddExpr(S); 4302 if (Offset != nullptr) { 4303 if (auto *SV = getSCEVValues(Stripped)) 4304 SV->remove({V, Offset}); 4305 } 4306 ValueExprMap.erase(V); 4307 } 4308 } 4309 4310 void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) { 4311 // A recursive query may have already computed the SCEV. It should be 4312 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily 4313 // inferred nowrap flags. 4314 auto It = ValueExprMap.find_as(V); 4315 if (It == ValueExprMap.end()) { 4316 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4317 ExprValueMap[S].insert({V, nullptr}); 4318 } 4319 } 4320 4321 /// Return an existing SCEV if it exists, otherwise analyze the expression and 4322 /// create a new one. 4323 const SCEV *ScalarEvolution::getSCEV(Value *V) { 4324 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4325 4326 const SCEV *S = getExistingSCEV(V); 4327 if (S == nullptr) { 4328 S = createSCEV(V); 4329 // During PHI resolution, it is possible to create two SCEVs for the same 4330 // V, so it is needed to double check whether V->S is inserted into 4331 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 4332 std::pair<ValueExprMapType::iterator, bool> Pair = 4333 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4334 if (Pair.second) { 4335 ExprValueMap[S].insert({V, nullptr}); 4336 4337 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 4338 // ExprValueMap. 4339 const SCEV *Stripped = S; 4340 ConstantInt *Offset = nullptr; 4341 std::tie(Stripped, Offset) = splitAddExpr(S); 4342 // If stripped is SCEVUnknown, don't bother to save 4343 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 4344 // increase the complexity of the expansion code. 4345 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 4346 // because it may generate add/sub instead of GEP in SCEV expansion. 4347 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 4348 !isa<GetElementPtrInst>(V)) 4349 ExprValueMap[Stripped].insert({V, Offset}); 4350 } 4351 } 4352 return S; 4353 } 4354 4355 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 4356 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4357 4358 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4359 if (I != ValueExprMap.end()) { 4360 const SCEV *S = I->second; 4361 assert(checkValidity(S) && 4362 "existing SCEV has not been properly invalidated"); 4363 return S; 4364 } 4365 return nullptr; 4366 } 4367 4368 /// Return a SCEV corresponding to -V = -1*V 4369 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4370 SCEV::NoWrapFlags Flags) { 4371 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4372 return getConstant( 4373 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4374 4375 Type *Ty = V->getType(); 4376 Ty = getEffectiveSCEVType(Ty); 4377 return getMulExpr(V, getMinusOne(Ty), Flags); 4378 } 4379 4380 /// If Expr computes ~A, return A else return nullptr 4381 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4382 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4383 if (!Add || Add->getNumOperands() != 2 || 4384 !Add->getOperand(0)->isAllOnesValue()) 4385 return nullptr; 4386 4387 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4388 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4389 !AddRHS->getOperand(0)->isAllOnesValue()) 4390 return nullptr; 4391 4392 return AddRHS->getOperand(1); 4393 } 4394 4395 /// Return a SCEV corresponding to ~V = -1-V 4396 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4397 assert(!V->getType()->isPointerTy() && "Can't negate pointer"); 4398 4399 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4400 return getConstant( 4401 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4402 4403 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4404 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4405 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4406 SmallVector<const SCEV *, 2> MatchedOperands; 4407 for (const SCEV *Operand : MME->operands()) { 4408 const SCEV *Matched = MatchNotExpr(Operand); 4409 if (!Matched) 4410 return (const SCEV *)nullptr; 4411 MatchedOperands.push_back(Matched); 4412 } 4413 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 4414 MatchedOperands); 4415 }; 4416 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4417 return Replaced; 4418 } 4419 4420 Type *Ty = V->getType(); 4421 Ty = getEffectiveSCEVType(Ty); 4422 return getMinusSCEV(getMinusOne(Ty), V); 4423 } 4424 4425 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) { 4426 assert(P->getType()->isPointerTy()); 4427 4428 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) { 4429 // The base of an AddRec is the first operand. 4430 SmallVector<const SCEV *> Ops{AddRec->operands()}; 4431 Ops[0] = removePointerBase(Ops[0]); 4432 // Don't try to transfer nowrap flags for now. We could in some cases 4433 // (for example, if pointer operand of the AddRec is a SCEVUnknown). 4434 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap); 4435 } 4436 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) { 4437 // The base of an Add is the pointer operand. 4438 SmallVector<const SCEV *> Ops{Add->operands()}; 4439 const SCEV **PtrOp = nullptr; 4440 for (const SCEV *&AddOp : Ops) { 4441 if (AddOp->getType()->isPointerTy()) { 4442 assert(!PtrOp && "Cannot have multiple pointer ops"); 4443 PtrOp = &AddOp; 4444 } 4445 } 4446 *PtrOp = removePointerBase(*PtrOp); 4447 // Don't try to transfer nowrap flags for now. We could in some cases 4448 // (for example, if the pointer operand of the Add is a SCEVUnknown). 4449 return getAddExpr(Ops); 4450 } 4451 // Any other expression must be a pointer base. 4452 return getZero(P->getType()); 4453 } 4454 4455 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4456 SCEV::NoWrapFlags Flags, 4457 unsigned Depth) { 4458 // Fast path: X - X --> 0. 4459 if (LHS == RHS) 4460 return getZero(LHS->getType()); 4461 4462 // If we subtract two pointers with different pointer bases, bail. 4463 // Eventually, we're going to add an assertion to getMulExpr that we 4464 // can't multiply by a pointer. 4465 if (RHS->getType()->isPointerTy()) { 4466 if (!LHS->getType()->isPointerTy() || 4467 getPointerBase(LHS) != getPointerBase(RHS)) 4468 return getCouldNotCompute(); 4469 LHS = removePointerBase(LHS); 4470 RHS = removePointerBase(RHS); 4471 } 4472 4473 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4474 // makes it so that we cannot make much use of NUW. 4475 auto AddFlags = SCEV::FlagAnyWrap; 4476 const bool RHSIsNotMinSigned = 4477 !getSignedRangeMin(RHS).isMinSignedValue(); 4478 if (hasFlags(Flags, SCEV::FlagNSW)) { 4479 // Let M be the minimum representable signed value. Then (-1)*RHS 4480 // signed-wraps if and only if RHS is M. That can happen even for 4481 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4482 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4483 // (-1)*RHS, we need to prove that RHS != M. 4484 // 4485 // If LHS is non-negative and we know that LHS - RHS does not 4486 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4487 // either by proving that RHS > M or that LHS >= 0. 4488 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4489 AddFlags = SCEV::FlagNSW; 4490 } 4491 } 4492 4493 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4494 // RHS is NSW and LHS >= 0. 4495 // 4496 // The difficulty here is that the NSW flag may have been proven 4497 // relative to a loop that is to be found in a recurrence in LHS and 4498 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4499 // larger scope than intended. 4500 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4501 4502 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4503 } 4504 4505 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4506 unsigned Depth) { 4507 Type *SrcTy = V->getType(); 4508 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4509 "Cannot truncate or zero extend with non-integer arguments!"); 4510 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4511 return V; // No conversion 4512 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4513 return getTruncateExpr(V, Ty, Depth); 4514 return getZeroExtendExpr(V, Ty, Depth); 4515 } 4516 4517 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4518 unsigned Depth) { 4519 Type *SrcTy = V->getType(); 4520 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4521 "Cannot truncate or zero extend with non-integer arguments!"); 4522 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4523 return V; // No conversion 4524 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4525 return getTruncateExpr(V, Ty, Depth); 4526 return getSignExtendExpr(V, Ty, Depth); 4527 } 4528 4529 const SCEV * 4530 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4531 Type *SrcTy = V->getType(); 4532 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4533 "Cannot noop or zero extend with non-integer arguments!"); 4534 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4535 "getNoopOrZeroExtend cannot truncate!"); 4536 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4537 return V; // No conversion 4538 return getZeroExtendExpr(V, Ty); 4539 } 4540 4541 const SCEV * 4542 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4543 Type *SrcTy = V->getType(); 4544 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4545 "Cannot noop or sign extend with non-integer arguments!"); 4546 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4547 "getNoopOrSignExtend cannot truncate!"); 4548 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4549 return V; // No conversion 4550 return getSignExtendExpr(V, Ty); 4551 } 4552 4553 const SCEV * 4554 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4555 Type *SrcTy = V->getType(); 4556 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4557 "Cannot noop or any extend with non-integer arguments!"); 4558 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4559 "getNoopOrAnyExtend cannot truncate!"); 4560 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4561 return V; // No conversion 4562 return getAnyExtendExpr(V, Ty); 4563 } 4564 4565 const SCEV * 4566 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4567 Type *SrcTy = V->getType(); 4568 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4569 "Cannot truncate or noop with non-integer arguments!"); 4570 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4571 "getTruncateOrNoop cannot extend!"); 4572 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4573 return V; // No conversion 4574 return getTruncateExpr(V, Ty); 4575 } 4576 4577 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4578 const SCEV *RHS) { 4579 const SCEV *PromotedLHS = LHS; 4580 const SCEV *PromotedRHS = RHS; 4581 4582 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4583 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4584 else 4585 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4586 4587 return getUMaxExpr(PromotedLHS, PromotedRHS); 4588 } 4589 4590 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4591 const SCEV *RHS, 4592 bool Sequential) { 4593 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4594 return getUMinFromMismatchedTypes(Ops, Sequential); 4595 } 4596 4597 const SCEV * 4598 ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops, 4599 bool Sequential) { 4600 assert(!Ops.empty() && "At least one operand must be!"); 4601 // Trivial case. 4602 if (Ops.size() == 1) 4603 return Ops[0]; 4604 4605 // Find the max type first. 4606 Type *MaxType = nullptr; 4607 for (auto *S : Ops) 4608 if (MaxType) 4609 MaxType = getWiderType(MaxType, S->getType()); 4610 else 4611 MaxType = S->getType(); 4612 assert(MaxType && "Failed to find maximum type!"); 4613 4614 // Extend all ops to max type. 4615 SmallVector<const SCEV *, 2> PromotedOps; 4616 for (auto *S : Ops) 4617 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4618 4619 // Generate umin. 4620 return getUMinExpr(PromotedOps, Sequential); 4621 } 4622 4623 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4624 // A pointer operand may evaluate to a nonpointer expression, such as null. 4625 if (!V->getType()->isPointerTy()) 4626 return V; 4627 4628 while (true) { 4629 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 4630 V = AddRec->getStart(); 4631 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) { 4632 const SCEV *PtrOp = nullptr; 4633 for (const SCEV *AddOp : Add->operands()) { 4634 if (AddOp->getType()->isPointerTy()) { 4635 assert(!PtrOp && "Cannot have multiple pointer ops"); 4636 PtrOp = AddOp; 4637 } 4638 } 4639 assert(PtrOp && "Must have pointer op"); 4640 V = PtrOp; 4641 } else // Not something we can look further into. 4642 return V; 4643 } 4644 } 4645 4646 /// Push users of the given Instruction onto the given Worklist. 4647 static void PushDefUseChildren(Instruction *I, 4648 SmallVectorImpl<Instruction *> &Worklist, 4649 SmallPtrSetImpl<Instruction *> &Visited) { 4650 // Push the def-use children onto the Worklist stack. 4651 for (User *U : I->users()) { 4652 auto *UserInsn = cast<Instruction>(U); 4653 if (Visited.insert(UserInsn).second) 4654 Worklist.push_back(UserInsn); 4655 } 4656 } 4657 4658 namespace { 4659 4660 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4661 /// expression in case its Loop is L. If it is not L then 4662 /// if IgnoreOtherLoops is true then use AddRec itself 4663 /// otherwise rewrite cannot be done. 4664 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4665 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4666 public: 4667 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4668 bool IgnoreOtherLoops = true) { 4669 SCEVInitRewriter Rewriter(L, SE); 4670 const SCEV *Result = Rewriter.visit(S); 4671 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4672 return SE.getCouldNotCompute(); 4673 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4674 ? SE.getCouldNotCompute() 4675 : Result; 4676 } 4677 4678 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4679 if (!SE.isLoopInvariant(Expr, L)) 4680 SeenLoopVariantSCEVUnknown = true; 4681 return Expr; 4682 } 4683 4684 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4685 // Only re-write AddRecExprs for this loop. 4686 if (Expr->getLoop() == L) 4687 return Expr->getStart(); 4688 SeenOtherLoops = true; 4689 return Expr; 4690 } 4691 4692 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4693 4694 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4695 4696 private: 4697 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4698 : SCEVRewriteVisitor(SE), L(L) {} 4699 4700 const Loop *L; 4701 bool SeenLoopVariantSCEVUnknown = false; 4702 bool SeenOtherLoops = false; 4703 }; 4704 4705 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4706 /// increment expression in case its Loop is L. If it is not L then 4707 /// use AddRec itself. 4708 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4709 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4710 public: 4711 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4712 SCEVPostIncRewriter Rewriter(L, SE); 4713 const SCEV *Result = Rewriter.visit(S); 4714 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4715 ? SE.getCouldNotCompute() 4716 : Result; 4717 } 4718 4719 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4720 if (!SE.isLoopInvariant(Expr, L)) 4721 SeenLoopVariantSCEVUnknown = true; 4722 return Expr; 4723 } 4724 4725 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4726 // Only re-write AddRecExprs for this loop. 4727 if (Expr->getLoop() == L) 4728 return Expr->getPostIncExpr(SE); 4729 SeenOtherLoops = true; 4730 return Expr; 4731 } 4732 4733 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4734 4735 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4736 4737 private: 4738 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4739 : SCEVRewriteVisitor(SE), L(L) {} 4740 4741 const Loop *L; 4742 bool SeenLoopVariantSCEVUnknown = false; 4743 bool SeenOtherLoops = false; 4744 }; 4745 4746 /// This class evaluates the compare condition by matching it against the 4747 /// condition of loop latch. If there is a match we assume a true value 4748 /// for the condition while building SCEV nodes. 4749 class SCEVBackedgeConditionFolder 4750 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4751 public: 4752 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4753 ScalarEvolution &SE) { 4754 bool IsPosBECond = false; 4755 Value *BECond = nullptr; 4756 if (BasicBlock *Latch = L->getLoopLatch()) { 4757 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4758 if (BI && BI->isConditional()) { 4759 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4760 "Both outgoing branches should not target same header!"); 4761 BECond = BI->getCondition(); 4762 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4763 } else { 4764 return S; 4765 } 4766 } 4767 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4768 return Rewriter.visit(S); 4769 } 4770 4771 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4772 const SCEV *Result = Expr; 4773 bool InvariantF = SE.isLoopInvariant(Expr, L); 4774 4775 if (!InvariantF) { 4776 Instruction *I = cast<Instruction>(Expr->getValue()); 4777 switch (I->getOpcode()) { 4778 case Instruction::Select: { 4779 SelectInst *SI = cast<SelectInst>(I); 4780 Optional<const SCEV *> Res = 4781 compareWithBackedgeCondition(SI->getCondition()); 4782 if (Res.hasValue()) { 4783 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4784 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4785 } 4786 break; 4787 } 4788 default: { 4789 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4790 if (Res.hasValue()) 4791 Result = Res.getValue(); 4792 break; 4793 } 4794 } 4795 } 4796 return Result; 4797 } 4798 4799 private: 4800 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4801 bool IsPosBECond, ScalarEvolution &SE) 4802 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4803 IsPositiveBECond(IsPosBECond) {} 4804 4805 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4806 4807 const Loop *L; 4808 /// Loop back condition. 4809 Value *BackedgeCond = nullptr; 4810 /// Set to true if loop back is on positive branch condition. 4811 bool IsPositiveBECond; 4812 }; 4813 4814 Optional<const SCEV *> 4815 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4816 4817 // If value matches the backedge condition for loop latch, 4818 // then return a constant evolution node based on loopback 4819 // branch taken. 4820 if (BackedgeCond == IC) 4821 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4822 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4823 return None; 4824 } 4825 4826 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4827 public: 4828 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4829 ScalarEvolution &SE) { 4830 SCEVShiftRewriter Rewriter(L, SE); 4831 const SCEV *Result = Rewriter.visit(S); 4832 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4833 } 4834 4835 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4836 // Only allow AddRecExprs for this loop. 4837 if (!SE.isLoopInvariant(Expr, L)) 4838 Valid = false; 4839 return Expr; 4840 } 4841 4842 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4843 if (Expr->getLoop() == L && Expr->isAffine()) 4844 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4845 Valid = false; 4846 return Expr; 4847 } 4848 4849 bool isValid() { return Valid; } 4850 4851 private: 4852 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4853 : SCEVRewriteVisitor(SE), L(L) {} 4854 4855 const Loop *L; 4856 bool Valid = true; 4857 }; 4858 4859 } // end anonymous namespace 4860 4861 SCEV::NoWrapFlags 4862 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4863 if (!AR->isAffine()) 4864 return SCEV::FlagAnyWrap; 4865 4866 using OBO = OverflowingBinaryOperator; 4867 4868 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4869 4870 if (!AR->hasNoSignedWrap()) { 4871 ConstantRange AddRecRange = getSignedRange(AR); 4872 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4873 4874 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4875 Instruction::Add, IncRange, OBO::NoSignedWrap); 4876 if (NSWRegion.contains(AddRecRange)) 4877 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4878 } 4879 4880 if (!AR->hasNoUnsignedWrap()) { 4881 ConstantRange AddRecRange = getUnsignedRange(AR); 4882 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4883 4884 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4885 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4886 if (NUWRegion.contains(AddRecRange)) 4887 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4888 } 4889 4890 return Result; 4891 } 4892 4893 SCEV::NoWrapFlags 4894 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4895 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4896 4897 if (AR->hasNoSignedWrap()) 4898 return Result; 4899 4900 if (!AR->isAffine()) 4901 return Result; 4902 4903 const SCEV *Step = AR->getStepRecurrence(*this); 4904 const Loop *L = AR->getLoop(); 4905 4906 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4907 // Note that this serves two purposes: It filters out loops that are 4908 // simply not analyzable, and it covers the case where this code is 4909 // being called from within backedge-taken count analysis, such that 4910 // attempting to ask for the backedge-taken count would likely result 4911 // in infinite recursion. In the later case, the analysis code will 4912 // cope with a conservative value, and it will take care to purge 4913 // that value once it has finished. 4914 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4915 4916 // Normally, in the cases we can prove no-overflow via a 4917 // backedge guarding condition, we can also compute a backedge 4918 // taken count for the loop. The exceptions are assumptions and 4919 // guards present in the loop -- SCEV is not great at exploiting 4920 // these to compute max backedge taken counts, but can still use 4921 // these to prove lack of overflow. Use this fact to avoid 4922 // doing extra work that may not pay off. 4923 4924 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4925 AC.assumptions().empty()) 4926 return Result; 4927 4928 // If the backedge is guarded by a comparison with the pre-inc value the 4929 // addrec is safe. Also, if the entry is guarded by a comparison with the 4930 // start value and the backedge is guarded by a comparison with the post-inc 4931 // value, the addrec is safe. 4932 ICmpInst::Predicate Pred; 4933 const SCEV *OverflowLimit = 4934 getSignedOverflowLimitForStep(Step, &Pred, this); 4935 if (OverflowLimit && 4936 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4937 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4938 Result = setFlags(Result, SCEV::FlagNSW); 4939 } 4940 return Result; 4941 } 4942 SCEV::NoWrapFlags 4943 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4944 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4945 4946 if (AR->hasNoUnsignedWrap()) 4947 return Result; 4948 4949 if (!AR->isAffine()) 4950 return Result; 4951 4952 const SCEV *Step = AR->getStepRecurrence(*this); 4953 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4954 const Loop *L = AR->getLoop(); 4955 4956 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4957 // Note that this serves two purposes: It filters out loops that are 4958 // simply not analyzable, and it covers the case where this code is 4959 // being called from within backedge-taken count analysis, such that 4960 // attempting to ask for the backedge-taken count would likely result 4961 // in infinite recursion. In the later case, the analysis code will 4962 // cope with a conservative value, and it will take care to purge 4963 // that value once it has finished. 4964 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4965 4966 // Normally, in the cases we can prove no-overflow via a 4967 // backedge guarding condition, we can also compute a backedge 4968 // taken count for the loop. The exceptions are assumptions and 4969 // guards present in the loop -- SCEV is not great at exploiting 4970 // these to compute max backedge taken counts, but can still use 4971 // these to prove lack of overflow. Use this fact to avoid 4972 // doing extra work that may not pay off. 4973 4974 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4975 AC.assumptions().empty()) 4976 return Result; 4977 4978 // If the backedge is guarded by a comparison with the pre-inc value the 4979 // addrec is safe. Also, if the entry is guarded by a comparison with the 4980 // start value and the backedge is guarded by a comparison with the post-inc 4981 // value, the addrec is safe. 4982 if (isKnownPositive(Step)) { 4983 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 4984 getUnsignedRangeMax(Step)); 4985 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 4986 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 4987 Result = setFlags(Result, SCEV::FlagNUW); 4988 } 4989 } 4990 4991 return Result; 4992 } 4993 4994 namespace { 4995 4996 /// Represents an abstract binary operation. This may exist as a 4997 /// normal instruction or constant expression, or may have been 4998 /// derived from an expression tree. 4999 struct BinaryOp { 5000 unsigned Opcode; 5001 Value *LHS; 5002 Value *RHS; 5003 bool IsNSW = false; 5004 bool IsNUW = false; 5005 5006 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 5007 /// constant expression. 5008 Operator *Op = nullptr; 5009 5010 explicit BinaryOp(Operator *Op) 5011 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 5012 Op(Op) { 5013 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 5014 IsNSW = OBO->hasNoSignedWrap(); 5015 IsNUW = OBO->hasNoUnsignedWrap(); 5016 } 5017 } 5018 5019 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 5020 bool IsNUW = false) 5021 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 5022 }; 5023 5024 } // end anonymous namespace 5025 5026 /// Try to map \p V into a BinaryOp, and return \c None on failure. 5027 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 5028 auto *Op = dyn_cast<Operator>(V); 5029 if (!Op) 5030 return None; 5031 5032 // Implementation detail: all the cleverness here should happen without 5033 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 5034 // SCEV expressions when possible, and we should not break that. 5035 5036 switch (Op->getOpcode()) { 5037 case Instruction::Add: 5038 case Instruction::Sub: 5039 case Instruction::Mul: 5040 case Instruction::UDiv: 5041 case Instruction::URem: 5042 case Instruction::And: 5043 case Instruction::Or: 5044 case Instruction::AShr: 5045 case Instruction::Shl: 5046 return BinaryOp(Op); 5047 5048 case Instruction::Xor: 5049 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 5050 // If the RHS of the xor is a signmask, then this is just an add. 5051 // Instcombine turns add of signmask into xor as a strength reduction step. 5052 if (RHSC->getValue().isSignMask()) 5053 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 5054 return BinaryOp(Op); 5055 5056 case Instruction::LShr: 5057 // Turn logical shift right of a constant into a unsigned divide. 5058 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 5059 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 5060 5061 // If the shift count is not less than the bitwidth, the result of 5062 // the shift is undefined. Don't try to analyze it, because the 5063 // resolution chosen here may differ from the resolution chosen in 5064 // other parts of the compiler. 5065 if (SA->getValue().ult(BitWidth)) { 5066 Constant *X = 5067 ConstantInt::get(SA->getContext(), 5068 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5069 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 5070 } 5071 } 5072 return BinaryOp(Op); 5073 5074 case Instruction::ExtractValue: { 5075 auto *EVI = cast<ExtractValueInst>(Op); 5076 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 5077 break; 5078 5079 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 5080 if (!WO) 5081 break; 5082 5083 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 5084 bool Signed = WO->isSigned(); 5085 // TODO: Should add nuw/nsw flags for mul as well. 5086 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 5087 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 5088 5089 // Now that we know that all uses of the arithmetic-result component of 5090 // CI are guarded by the overflow check, we can go ahead and pretend 5091 // that the arithmetic is non-overflowing. 5092 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 5093 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 5094 } 5095 5096 default: 5097 break; 5098 } 5099 5100 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 5101 // semantics as a Sub, return a binary sub expression. 5102 if (auto *II = dyn_cast<IntrinsicInst>(V)) 5103 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 5104 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 5105 5106 return None; 5107 } 5108 5109 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 5110 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 5111 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 5112 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 5113 /// follows one of the following patterns: 5114 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 5115 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 5116 /// If the SCEV expression of \p Op conforms with one of the expected patterns 5117 /// we return the type of the truncation operation, and indicate whether the 5118 /// truncated type should be treated as signed/unsigned by setting 5119 /// \p Signed to true/false, respectively. 5120 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 5121 bool &Signed, ScalarEvolution &SE) { 5122 // The case where Op == SymbolicPHI (that is, with no type conversions on 5123 // the way) is handled by the regular add recurrence creating logic and 5124 // would have already been triggered in createAddRecForPHI. Reaching it here 5125 // means that createAddRecFromPHI had failed for this PHI before (e.g., 5126 // because one of the other operands of the SCEVAddExpr updating this PHI is 5127 // not invariant). 5128 // 5129 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 5130 // this case predicates that allow us to prove that Op == SymbolicPHI will 5131 // be added. 5132 if (Op == SymbolicPHI) 5133 return nullptr; 5134 5135 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 5136 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 5137 if (SourceBits != NewBits) 5138 return nullptr; 5139 5140 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 5141 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 5142 if (!SExt && !ZExt) 5143 return nullptr; 5144 const SCEVTruncateExpr *Trunc = 5145 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 5146 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 5147 if (!Trunc) 5148 return nullptr; 5149 const SCEV *X = Trunc->getOperand(); 5150 if (X != SymbolicPHI) 5151 return nullptr; 5152 Signed = SExt != nullptr; 5153 return Trunc->getType(); 5154 } 5155 5156 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 5157 if (!PN->getType()->isIntegerTy()) 5158 return nullptr; 5159 const Loop *L = LI.getLoopFor(PN->getParent()); 5160 if (!L || L->getHeader() != PN->getParent()) 5161 return nullptr; 5162 return L; 5163 } 5164 5165 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 5166 // computation that updates the phi follows the following pattern: 5167 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 5168 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 5169 // If so, try to see if it can be rewritten as an AddRecExpr under some 5170 // Predicates. If successful, return them as a pair. Also cache the results 5171 // of the analysis. 5172 // 5173 // Example usage scenario: 5174 // Say the Rewriter is called for the following SCEV: 5175 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 5176 // where: 5177 // %X = phi i64 (%Start, %BEValue) 5178 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 5179 // and call this function with %SymbolicPHI = %X. 5180 // 5181 // The analysis will find that the value coming around the backedge has 5182 // the following SCEV: 5183 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 5184 // Upon concluding that this matches the desired pattern, the function 5185 // will return the pair {NewAddRec, SmallPredsVec} where: 5186 // NewAddRec = {%Start,+,%Step} 5187 // SmallPredsVec = {P1, P2, P3} as follows: 5188 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 5189 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 5190 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 5191 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 5192 // under the predicates {P1,P2,P3}. 5193 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 5194 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 5195 // 5196 // TODO's: 5197 // 5198 // 1) Extend the Induction descriptor to also support inductions that involve 5199 // casts: When needed (namely, when we are called in the context of the 5200 // vectorizer induction analysis), a Set of cast instructions will be 5201 // populated by this method, and provided back to isInductionPHI. This is 5202 // needed to allow the vectorizer to properly record them to be ignored by 5203 // the cost model and to avoid vectorizing them (otherwise these casts, 5204 // which are redundant under the runtime overflow checks, will be 5205 // vectorized, which can be costly). 5206 // 5207 // 2) Support additional induction/PHISCEV patterns: We also want to support 5208 // inductions where the sext-trunc / zext-trunc operations (partly) occur 5209 // after the induction update operation (the induction increment): 5210 // 5211 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 5212 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 5213 // 5214 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 5215 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 5216 // 5217 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 5218 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5219 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 5220 SmallVector<const SCEVPredicate *, 3> Predicates; 5221 5222 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 5223 // return an AddRec expression under some predicate. 5224 5225 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5226 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5227 assert(L && "Expecting an integer loop header phi"); 5228 5229 // The loop may have multiple entrances or multiple exits; we can analyze 5230 // this phi as an addrec if it has a unique entry value and a unique 5231 // backedge value. 5232 Value *BEValueV = nullptr, *StartValueV = nullptr; 5233 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5234 Value *V = PN->getIncomingValue(i); 5235 if (L->contains(PN->getIncomingBlock(i))) { 5236 if (!BEValueV) { 5237 BEValueV = V; 5238 } else if (BEValueV != V) { 5239 BEValueV = nullptr; 5240 break; 5241 } 5242 } else if (!StartValueV) { 5243 StartValueV = V; 5244 } else if (StartValueV != V) { 5245 StartValueV = nullptr; 5246 break; 5247 } 5248 } 5249 if (!BEValueV || !StartValueV) 5250 return None; 5251 5252 const SCEV *BEValue = getSCEV(BEValueV); 5253 5254 // If the value coming around the backedge is an add with the symbolic 5255 // value we just inserted, possibly with casts that we can ignore under 5256 // an appropriate runtime guard, then we found a simple induction variable! 5257 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 5258 if (!Add) 5259 return None; 5260 5261 // If there is a single occurrence of the symbolic value, possibly 5262 // casted, replace it with a recurrence. 5263 unsigned FoundIndex = Add->getNumOperands(); 5264 Type *TruncTy = nullptr; 5265 bool Signed; 5266 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5267 if ((TruncTy = 5268 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 5269 if (FoundIndex == e) { 5270 FoundIndex = i; 5271 break; 5272 } 5273 5274 if (FoundIndex == Add->getNumOperands()) 5275 return None; 5276 5277 // Create an add with everything but the specified operand. 5278 SmallVector<const SCEV *, 8> Ops; 5279 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5280 if (i != FoundIndex) 5281 Ops.push_back(Add->getOperand(i)); 5282 const SCEV *Accum = getAddExpr(Ops); 5283 5284 // The runtime checks will not be valid if the step amount is 5285 // varying inside the loop. 5286 if (!isLoopInvariant(Accum, L)) 5287 return None; 5288 5289 // *** Part2: Create the predicates 5290 5291 // Analysis was successful: we have a phi-with-cast pattern for which we 5292 // can return an AddRec expression under the following predicates: 5293 // 5294 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 5295 // fits within the truncated type (does not overflow) for i = 0 to n-1. 5296 // P2: An Equal predicate that guarantees that 5297 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 5298 // P3: An Equal predicate that guarantees that 5299 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 5300 // 5301 // As we next prove, the above predicates guarantee that: 5302 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 5303 // 5304 // 5305 // More formally, we want to prove that: 5306 // Expr(i+1) = Start + (i+1) * Accum 5307 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5308 // 5309 // Given that: 5310 // 1) Expr(0) = Start 5311 // 2) Expr(1) = Start + Accum 5312 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 5313 // 3) Induction hypothesis (step i): 5314 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 5315 // 5316 // Proof: 5317 // Expr(i+1) = 5318 // = Start + (i+1)*Accum 5319 // = (Start + i*Accum) + Accum 5320 // = Expr(i) + Accum 5321 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 5322 // :: from step i 5323 // 5324 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 5325 // 5326 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 5327 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 5328 // + Accum :: from P3 5329 // 5330 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 5331 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 5332 // 5333 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 5334 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5335 // 5336 // By induction, the same applies to all iterations 1<=i<n: 5337 // 5338 5339 // Create a truncated addrec for which we will add a no overflow check (P1). 5340 const SCEV *StartVal = getSCEV(StartValueV); 5341 const SCEV *PHISCEV = 5342 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 5343 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 5344 5345 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 5346 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 5347 // will be constant. 5348 // 5349 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 5350 // add P1. 5351 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 5352 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 5353 Signed ? SCEVWrapPredicate::IncrementNSSW 5354 : SCEVWrapPredicate::IncrementNUSW; 5355 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 5356 Predicates.push_back(AddRecPred); 5357 } 5358 5359 // Create the Equal Predicates P2,P3: 5360 5361 // It is possible that the predicates P2 and/or P3 are computable at 5362 // compile time due to StartVal and/or Accum being constants. 5363 // If either one is, then we can check that now and escape if either P2 5364 // or P3 is false. 5365 5366 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 5367 // for each of StartVal and Accum 5368 auto getExtendedExpr = [&](const SCEV *Expr, 5369 bool CreateSignExtend) -> const SCEV * { 5370 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 5371 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 5372 const SCEV *ExtendedExpr = 5373 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 5374 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 5375 return ExtendedExpr; 5376 }; 5377 5378 // Given: 5379 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 5380 // = getExtendedExpr(Expr) 5381 // Determine whether the predicate P: Expr == ExtendedExpr 5382 // is known to be false at compile time 5383 auto PredIsKnownFalse = [&](const SCEV *Expr, 5384 const SCEV *ExtendedExpr) -> bool { 5385 return Expr != ExtendedExpr && 5386 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 5387 }; 5388 5389 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 5390 if (PredIsKnownFalse(StartVal, StartExtended)) { 5391 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 5392 return None; 5393 } 5394 5395 // The Step is always Signed (because the overflow checks are either 5396 // NSSW or NUSW) 5397 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 5398 if (PredIsKnownFalse(Accum, AccumExtended)) { 5399 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 5400 return None; 5401 } 5402 5403 auto AppendPredicate = [&](const SCEV *Expr, 5404 const SCEV *ExtendedExpr) -> void { 5405 if (Expr != ExtendedExpr && 5406 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 5407 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 5408 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 5409 Predicates.push_back(Pred); 5410 } 5411 }; 5412 5413 AppendPredicate(StartVal, StartExtended); 5414 AppendPredicate(Accum, AccumExtended); 5415 5416 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 5417 // which the casts had been folded away. The caller can rewrite SymbolicPHI 5418 // into NewAR if it will also add the runtime overflow checks specified in 5419 // Predicates. 5420 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 5421 5422 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 5423 std::make_pair(NewAR, Predicates); 5424 // Remember the result of the analysis for this SCEV at this locayyytion. 5425 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 5426 return PredRewrite; 5427 } 5428 5429 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5430 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5431 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5432 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5433 if (!L) 5434 return None; 5435 5436 // Check to see if we already analyzed this PHI. 5437 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5438 if (I != PredicatedSCEVRewrites.end()) { 5439 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5440 I->second; 5441 // Analysis was done before and failed to create an AddRec: 5442 if (Rewrite.first == SymbolicPHI) 5443 return None; 5444 // Analysis was done before and succeeded to create an AddRec under 5445 // a predicate: 5446 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5447 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5448 return Rewrite; 5449 } 5450 5451 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5452 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5453 5454 // Record in the cache that the analysis failed 5455 if (!Rewrite) { 5456 SmallVector<const SCEVPredicate *, 3> Predicates; 5457 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5458 return None; 5459 } 5460 5461 return Rewrite; 5462 } 5463 5464 // FIXME: This utility is currently required because the Rewriter currently 5465 // does not rewrite this expression: 5466 // {0, +, (sext ix (trunc iy to ix) to iy)} 5467 // into {0, +, %step}, 5468 // even when the following Equal predicate exists: 5469 // "%step == (sext ix (trunc iy to ix) to iy)". 5470 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5471 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5472 if (AR1 == AR2) 5473 return true; 5474 5475 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5476 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 5477 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 5478 return false; 5479 return true; 5480 }; 5481 5482 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5483 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5484 return false; 5485 return true; 5486 } 5487 5488 /// A helper function for createAddRecFromPHI to handle simple cases. 5489 /// 5490 /// This function tries to find an AddRec expression for the simplest (yet most 5491 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5492 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5493 /// technique for finding the AddRec expression. 5494 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5495 Value *BEValueV, 5496 Value *StartValueV) { 5497 const Loop *L = LI.getLoopFor(PN->getParent()); 5498 assert(L && L->getHeader() == PN->getParent()); 5499 assert(BEValueV && StartValueV); 5500 5501 auto BO = MatchBinaryOp(BEValueV, DT); 5502 if (!BO) 5503 return nullptr; 5504 5505 if (BO->Opcode != Instruction::Add) 5506 return nullptr; 5507 5508 const SCEV *Accum = nullptr; 5509 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5510 Accum = getSCEV(BO->RHS); 5511 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5512 Accum = getSCEV(BO->LHS); 5513 5514 if (!Accum) 5515 return nullptr; 5516 5517 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5518 if (BO->IsNUW) 5519 Flags = setFlags(Flags, SCEV::FlagNUW); 5520 if (BO->IsNSW) 5521 Flags = setFlags(Flags, SCEV::FlagNSW); 5522 5523 const SCEV *StartVal = getSCEV(StartValueV); 5524 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5525 insertValueToMap(PN, PHISCEV); 5526 5527 // We can add Flags to the post-inc expression only if we 5528 // know that it is *undefined behavior* for BEValueV to 5529 // overflow. 5530 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) { 5531 assert(isLoopInvariant(Accum, L) && 5532 "Accum is defined outside L, but is not invariant?"); 5533 if (isAddRecNeverPoison(BEInst, L)) 5534 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5535 } 5536 5537 return PHISCEV; 5538 } 5539 5540 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5541 const Loop *L = LI.getLoopFor(PN->getParent()); 5542 if (!L || L->getHeader() != PN->getParent()) 5543 return nullptr; 5544 5545 // The loop may have multiple entrances or multiple exits; we can analyze 5546 // this phi as an addrec if it has a unique entry value and a unique 5547 // backedge value. 5548 Value *BEValueV = nullptr, *StartValueV = nullptr; 5549 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5550 Value *V = PN->getIncomingValue(i); 5551 if (L->contains(PN->getIncomingBlock(i))) { 5552 if (!BEValueV) { 5553 BEValueV = V; 5554 } else if (BEValueV != V) { 5555 BEValueV = nullptr; 5556 break; 5557 } 5558 } else if (!StartValueV) { 5559 StartValueV = V; 5560 } else if (StartValueV != V) { 5561 StartValueV = nullptr; 5562 break; 5563 } 5564 } 5565 if (!BEValueV || !StartValueV) 5566 return nullptr; 5567 5568 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5569 "PHI node already processed?"); 5570 5571 // First, try to find AddRec expression without creating a fictituos symbolic 5572 // value for PN. 5573 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5574 return S; 5575 5576 // Handle PHI node value symbolically. 5577 const SCEV *SymbolicName = getUnknown(PN); 5578 insertValueToMap(PN, SymbolicName); 5579 5580 // Using this symbolic name for the PHI, analyze the value coming around 5581 // the back-edge. 5582 const SCEV *BEValue = getSCEV(BEValueV); 5583 5584 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5585 // has a special value for the first iteration of the loop. 5586 5587 // If the value coming around the backedge is an add with the symbolic 5588 // value we just inserted, then we found a simple induction variable! 5589 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5590 // If there is a single occurrence of the symbolic value, replace it 5591 // with a recurrence. 5592 unsigned FoundIndex = Add->getNumOperands(); 5593 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5594 if (Add->getOperand(i) == SymbolicName) 5595 if (FoundIndex == e) { 5596 FoundIndex = i; 5597 break; 5598 } 5599 5600 if (FoundIndex != Add->getNumOperands()) { 5601 // Create an add with everything but the specified operand. 5602 SmallVector<const SCEV *, 8> Ops; 5603 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5604 if (i != FoundIndex) 5605 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5606 L, *this)); 5607 const SCEV *Accum = getAddExpr(Ops); 5608 5609 // This is not a valid addrec if the step amount is varying each 5610 // loop iteration, but is not itself an addrec in this loop. 5611 if (isLoopInvariant(Accum, L) || 5612 (isa<SCEVAddRecExpr>(Accum) && 5613 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5614 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5615 5616 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5617 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5618 if (BO->IsNUW) 5619 Flags = setFlags(Flags, SCEV::FlagNUW); 5620 if (BO->IsNSW) 5621 Flags = setFlags(Flags, SCEV::FlagNSW); 5622 } 5623 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5624 // If the increment is an inbounds GEP, then we know the address 5625 // space cannot be wrapped around. We cannot make any guarantee 5626 // about signed or unsigned overflow because pointers are 5627 // unsigned but we may have a negative index from the base 5628 // pointer. We can guarantee that no unsigned wrap occurs if the 5629 // indices form a positive value. 5630 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5631 Flags = setFlags(Flags, SCEV::FlagNW); 5632 5633 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5634 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5635 Flags = setFlags(Flags, SCEV::FlagNUW); 5636 } 5637 5638 // We cannot transfer nuw and nsw flags from subtraction 5639 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5640 // for instance. 5641 } 5642 5643 const SCEV *StartVal = getSCEV(StartValueV); 5644 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5645 5646 // Okay, for the entire analysis of this edge we assumed the PHI 5647 // to be symbolic. We now need to go back and purge all of the 5648 // entries for the scalars that use the symbolic expression. 5649 forgetMemoizedResults(SymbolicName); 5650 insertValueToMap(PN, PHISCEV); 5651 5652 // We can add Flags to the post-inc expression only if we 5653 // know that it is *undefined behavior* for BEValueV to 5654 // overflow. 5655 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5656 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5657 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5658 5659 return PHISCEV; 5660 } 5661 } 5662 } else { 5663 // Otherwise, this could be a loop like this: 5664 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5665 // In this case, j = {1,+,1} and BEValue is j. 5666 // Because the other in-value of i (0) fits the evolution of BEValue 5667 // i really is an addrec evolution. 5668 // 5669 // We can generalize this saying that i is the shifted value of BEValue 5670 // by one iteration: 5671 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5672 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5673 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5674 if (Shifted != getCouldNotCompute() && 5675 Start != getCouldNotCompute()) { 5676 const SCEV *StartVal = getSCEV(StartValueV); 5677 if (Start == StartVal) { 5678 // Okay, for the entire analysis of this edge we assumed the PHI 5679 // to be symbolic. We now need to go back and purge all of the 5680 // entries for the scalars that use the symbolic expression. 5681 forgetMemoizedResults(SymbolicName); 5682 insertValueToMap(PN, Shifted); 5683 return Shifted; 5684 } 5685 } 5686 } 5687 5688 // Remove the temporary PHI node SCEV that has been inserted while intending 5689 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5690 // as it will prevent later (possibly simpler) SCEV expressions to be added 5691 // to the ValueExprMap. 5692 eraseValueFromMap(PN); 5693 5694 return nullptr; 5695 } 5696 5697 // Checks if the SCEV S is available at BB. S is considered available at BB 5698 // if S can be materialized at BB without introducing a fault. 5699 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5700 BasicBlock *BB) { 5701 struct CheckAvailable { 5702 bool TraversalDone = false; 5703 bool Available = true; 5704 5705 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5706 BasicBlock *BB = nullptr; 5707 DominatorTree &DT; 5708 5709 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5710 : L(L), BB(BB), DT(DT) {} 5711 5712 bool setUnavailable() { 5713 TraversalDone = true; 5714 Available = false; 5715 return false; 5716 } 5717 5718 bool follow(const SCEV *S) { 5719 switch (S->getSCEVType()) { 5720 case scConstant: 5721 case scPtrToInt: 5722 case scTruncate: 5723 case scZeroExtend: 5724 case scSignExtend: 5725 case scAddExpr: 5726 case scMulExpr: 5727 case scUMaxExpr: 5728 case scSMaxExpr: 5729 case scUMinExpr: 5730 case scSMinExpr: 5731 case scSequentialUMinExpr: 5732 // These expressions are available if their operand(s) is/are. 5733 return true; 5734 5735 case scAddRecExpr: { 5736 // We allow add recurrences that are on the loop BB is in, or some 5737 // outer loop. This guarantees availability because the value of the 5738 // add recurrence at BB is simply the "current" value of the induction 5739 // variable. We can relax this in the future; for instance an add 5740 // recurrence on a sibling dominating loop is also available at BB. 5741 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5742 if (L && (ARLoop == L || ARLoop->contains(L))) 5743 return true; 5744 5745 return setUnavailable(); 5746 } 5747 5748 case scUnknown: { 5749 // For SCEVUnknown, we check for simple dominance. 5750 const auto *SU = cast<SCEVUnknown>(S); 5751 Value *V = SU->getValue(); 5752 5753 if (isa<Argument>(V)) 5754 return false; 5755 5756 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5757 return false; 5758 5759 return setUnavailable(); 5760 } 5761 5762 case scUDivExpr: 5763 case scCouldNotCompute: 5764 // We do not try to smart about these at all. 5765 return setUnavailable(); 5766 } 5767 llvm_unreachable("Unknown SCEV kind!"); 5768 } 5769 5770 bool isDone() { return TraversalDone; } 5771 }; 5772 5773 CheckAvailable CA(L, BB, DT); 5774 SCEVTraversal<CheckAvailable> ST(CA); 5775 5776 ST.visitAll(S); 5777 return CA.Available; 5778 } 5779 5780 // Try to match a control flow sequence that branches out at BI and merges back 5781 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5782 // match. 5783 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5784 Value *&C, Value *&LHS, Value *&RHS) { 5785 C = BI->getCondition(); 5786 5787 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5788 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5789 5790 if (!LeftEdge.isSingleEdge()) 5791 return false; 5792 5793 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5794 5795 Use &LeftUse = Merge->getOperandUse(0); 5796 Use &RightUse = Merge->getOperandUse(1); 5797 5798 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5799 LHS = LeftUse; 5800 RHS = RightUse; 5801 return true; 5802 } 5803 5804 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5805 LHS = RightUse; 5806 RHS = LeftUse; 5807 return true; 5808 } 5809 5810 return false; 5811 } 5812 5813 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5814 auto IsReachable = 5815 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5816 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5817 const Loop *L = LI.getLoopFor(PN->getParent()); 5818 5819 // We don't want to break LCSSA, even in a SCEV expression tree. 5820 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5821 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5822 return nullptr; 5823 5824 // Try to match 5825 // 5826 // br %cond, label %left, label %right 5827 // left: 5828 // br label %merge 5829 // right: 5830 // br label %merge 5831 // merge: 5832 // V = phi [ %x, %left ], [ %y, %right ] 5833 // 5834 // as "select %cond, %x, %y" 5835 5836 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5837 assert(IDom && "At least the entry block should dominate PN"); 5838 5839 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5840 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5841 5842 if (BI && BI->isConditional() && 5843 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5844 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5845 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5846 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5847 } 5848 5849 return nullptr; 5850 } 5851 5852 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5853 if (const SCEV *S = createAddRecFromPHI(PN)) 5854 return S; 5855 5856 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5857 return S; 5858 5859 // If the PHI has a single incoming value, follow that value, unless the 5860 // PHI's incoming blocks are in a different loop, in which case doing so 5861 // risks breaking LCSSA form. Instcombine would normally zap these, but 5862 // it doesn't have DominatorTree information, so it may miss cases. 5863 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5864 if (LI.replacementPreservesLCSSAForm(PN, V)) 5865 return getSCEV(V); 5866 5867 // If it's not a loop phi, we can't handle it yet. 5868 return getUnknown(PN); 5869 } 5870 5871 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5872 Value *Cond, 5873 Value *TrueVal, 5874 Value *FalseVal) { 5875 // Handle "constant" branch or select. This can occur for instance when a 5876 // loop pass transforms an inner loop and moves on to process the outer loop. 5877 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5878 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5879 5880 // Try to match some simple smax or umax patterns. 5881 auto *ICI = dyn_cast<ICmpInst>(Cond); 5882 if (!ICI) 5883 return getUnknown(I); 5884 5885 Value *LHS = ICI->getOperand(0); 5886 Value *RHS = ICI->getOperand(1); 5887 5888 switch (ICI->getPredicate()) { 5889 case ICmpInst::ICMP_SLT: 5890 case ICmpInst::ICMP_SLE: 5891 case ICmpInst::ICMP_ULT: 5892 case ICmpInst::ICMP_ULE: 5893 std::swap(LHS, RHS); 5894 LLVM_FALLTHROUGH; 5895 case ICmpInst::ICMP_SGT: 5896 case ICmpInst::ICMP_SGE: 5897 case ICmpInst::ICMP_UGT: 5898 case ICmpInst::ICMP_UGE: 5899 // a > b ? a+x : b+x -> max(a, b)+x 5900 // a > b ? b+x : a+x -> min(a, b)+x 5901 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5902 bool Signed = ICI->isSigned(); 5903 const SCEV *LA = getSCEV(TrueVal); 5904 const SCEV *RA = getSCEV(FalseVal); 5905 const SCEV *LS = getSCEV(LHS); 5906 const SCEV *RS = getSCEV(RHS); 5907 if (LA->getType()->isPointerTy()) { 5908 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA. 5909 // Need to make sure we can't produce weird expressions involving 5910 // negated pointers. 5911 if (LA == LS && RA == RS) 5912 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS); 5913 if (LA == RS && RA == LS) 5914 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS); 5915 } 5916 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * { 5917 if (Op->getType()->isPointerTy()) { 5918 Op = getLosslessPtrToIntExpr(Op); 5919 if (isa<SCEVCouldNotCompute>(Op)) 5920 return Op; 5921 } 5922 if (Signed) 5923 Op = getNoopOrSignExtend(Op, I->getType()); 5924 else 5925 Op = getNoopOrZeroExtend(Op, I->getType()); 5926 return Op; 5927 }; 5928 LS = CoerceOperand(LS); 5929 RS = CoerceOperand(RS); 5930 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS)) 5931 break; 5932 const SCEV *LDiff = getMinusSCEV(LA, LS); 5933 const SCEV *RDiff = getMinusSCEV(RA, RS); 5934 if (LDiff == RDiff) 5935 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS), 5936 LDiff); 5937 LDiff = getMinusSCEV(LA, RS); 5938 RDiff = getMinusSCEV(RA, LS); 5939 if (LDiff == RDiff) 5940 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS), 5941 LDiff); 5942 } 5943 break; 5944 case ICmpInst::ICMP_NE: 5945 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5946 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5947 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5948 const SCEV *One = getOne(I->getType()); 5949 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5950 const SCEV *LA = getSCEV(TrueVal); 5951 const SCEV *RA = getSCEV(FalseVal); 5952 const SCEV *LDiff = getMinusSCEV(LA, LS); 5953 const SCEV *RDiff = getMinusSCEV(RA, One); 5954 if (LDiff == RDiff) 5955 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5956 } 5957 break; 5958 case ICmpInst::ICMP_EQ: 5959 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5960 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5961 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5962 const SCEV *One = getOne(I->getType()); 5963 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5964 const SCEV *LA = getSCEV(TrueVal); 5965 const SCEV *RA = getSCEV(FalseVal); 5966 const SCEV *LDiff = getMinusSCEV(LA, One); 5967 const SCEV *RDiff = getMinusSCEV(RA, LS); 5968 if (LDiff == RDiff) 5969 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5970 } 5971 break; 5972 default: 5973 break; 5974 } 5975 5976 return getUnknown(I); 5977 } 5978 5979 /// Expand GEP instructions into add and multiply operations. This allows them 5980 /// to be analyzed by regular SCEV code. 5981 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5982 // Don't attempt to analyze GEPs over unsized objects. 5983 if (!GEP->getSourceElementType()->isSized()) 5984 return getUnknown(GEP); 5985 5986 SmallVector<const SCEV *, 4> IndexExprs; 5987 for (Value *Index : GEP->indices()) 5988 IndexExprs.push_back(getSCEV(Index)); 5989 return getGEPExpr(GEP, IndexExprs); 5990 } 5991 5992 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5993 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5994 return C->getAPInt().countTrailingZeros(); 5995 5996 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5997 return GetMinTrailingZeros(I->getOperand()); 5998 5999 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 6000 return std::min(GetMinTrailingZeros(T->getOperand()), 6001 (uint32_t)getTypeSizeInBits(T->getType())); 6002 6003 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 6004 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 6005 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 6006 ? getTypeSizeInBits(E->getType()) 6007 : OpRes; 6008 } 6009 6010 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 6011 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 6012 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 6013 ? getTypeSizeInBits(E->getType()) 6014 : OpRes; 6015 } 6016 6017 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 6018 // The result is the min of all operands results. 6019 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 6020 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 6021 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 6022 return MinOpRes; 6023 } 6024 6025 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 6026 // The result is the sum of all operands results. 6027 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 6028 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 6029 for (unsigned i = 1, e = M->getNumOperands(); 6030 SumOpRes != BitWidth && i != e; ++i) 6031 SumOpRes = 6032 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 6033 return SumOpRes; 6034 } 6035 6036 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 6037 // The result is the min of all operands results. 6038 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 6039 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 6040 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 6041 return MinOpRes; 6042 } 6043 6044 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 6045 // The result is the min of all operands results. 6046 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 6047 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 6048 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 6049 return MinOpRes; 6050 } 6051 6052 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 6053 // The result is the min of all operands results. 6054 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 6055 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 6056 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 6057 return MinOpRes; 6058 } 6059 6060 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6061 // For a SCEVUnknown, ask ValueTracking. 6062 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 6063 return Known.countMinTrailingZeros(); 6064 } 6065 6066 // SCEVUDivExpr 6067 return 0; 6068 } 6069 6070 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 6071 auto I = MinTrailingZerosCache.find(S); 6072 if (I != MinTrailingZerosCache.end()) 6073 return I->second; 6074 6075 uint32_t Result = GetMinTrailingZerosImpl(S); 6076 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 6077 assert(InsertPair.second && "Should insert a new key"); 6078 return InsertPair.first->second; 6079 } 6080 6081 /// Helper method to assign a range to V from metadata present in the IR. 6082 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 6083 if (Instruction *I = dyn_cast<Instruction>(V)) 6084 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 6085 return getConstantRangeFromMetadata(*MD); 6086 6087 return None; 6088 } 6089 6090 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 6091 SCEV::NoWrapFlags Flags) { 6092 if (AddRec->getNoWrapFlags(Flags) != Flags) { 6093 AddRec->setNoWrapFlags(Flags); 6094 UnsignedRanges.erase(AddRec); 6095 SignedRanges.erase(AddRec); 6096 } 6097 } 6098 6099 ConstantRange ScalarEvolution:: 6100 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 6101 const DataLayout &DL = getDataLayout(); 6102 6103 unsigned BitWidth = getTypeSizeInBits(U->getType()); 6104 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 6105 6106 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 6107 // use information about the trip count to improve our available range. Note 6108 // that the trip count independent cases are already handled by known bits. 6109 // WARNING: The definition of recurrence used here is subtly different than 6110 // the one used by AddRec (and thus most of this file). Step is allowed to 6111 // be arbitrarily loop varying here, where AddRec allows only loop invariant 6112 // and other addrecs in the same loop (for non-affine addrecs). The code 6113 // below intentionally handles the case where step is not loop invariant. 6114 auto *P = dyn_cast<PHINode>(U->getValue()); 6115 if (!P) 6116 return FullSet; 6117 6118 // Make sure that no Phi input comes from an unreachable block. Otherwise, 6119 // even the values that are not available in these blocks may come from them, 6120 // and this leads to false-positive recurrence test. 6121 for (auto *Pred : predecessors(P->getParent())) 6122 if (!DT.isReachableFromEntry(Pred)) 6123 return FullSet; 6124 6125 BinaryOperator *BO; 6126 Value *Start, *Step; 6127 if (!matchSimpleRecurrence(P, BO, Start, Step)) 6128 return FullSet; 6129 6130 // If we found a recurrence in reachable code, we must be in a loop. Note 6131 // that BO might be in some subloop of L, and that's completely okay. 6132 auto *L = LI.getLoopFor(P->getParent()); 6133 assert(L && L->getHeader() == P->getParent()); 6134 if (!L->contains(BO->getParent())) 6135 // NOTE: This bailout should be an assert instead. However, asserting 6136 // the condition here exposes a case where LoopFusion is querying SCEV 6137 // with malformed loop information during the midst of the transform. 6138 // There doesn't appear to be an obvious fix, so for the moment bailout 6139 // until the caller issue can be fixed. PR49566 tracks the bug. 6140 return FullSet; 6141 6142 // TODO: Extend to other opcodes such as mul, and div 6143 switch (BO->getOpcode()) { 6144 default: 6145 return FullSet; 6146 case Instruction::AShr: 6147 case Instruction::LShr: 6148 case Instruction::Shl: 6149 break; 6150 }; 6151 6152 if (BO->getOperand(0) != P) 6153 // TODO: Handle the power function forms some day. 6154 return FullSet; 6155 6156 unsigned TC = getSmallConstantMaxTripCount(L); 6157 if (!TC || TC >= BitWidth) 6158 return FullSet; 6159 6160 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 6161 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 6162 assert(KnownStart.getBitWidth() == BitWidth && 6163 KnownStep.getBitWidth() == BitWidth); 6164 6165 // Compute total shift amount, being careful of overflow and bitwidths. 6166 auto MaxShiftAmt = KnownStep.getMaxValue(); 6167 APInt TCAP(BitWidth, TC-1); 6168 bool Overflow = false; 6169 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 6170 if (Overflow) 6171 return FullSet; 6172 6173 switch (BO->getOpcode()) { 6174 default: 6175 llvm_unreachable("filtered out above"); 6176 case Instruction::AShr: { 6177 // For each ashr, three cases: 6178 // shift = 0 => unchanged value 6179 // saturation => 0 or -1 6180 // other => a value closer to zero (of the same sign) 6181 // Thus, the end value is closer to zero than the start. 6182 auto KnownEnd = KnownBits::ashr(KnownStart, 6183 KnownBits::makeConstant(TotalShift)); 6184 if (KnownStart.isNonNegative()) 6185 // Analogous to lshr (simply not yet canonicalized) 6186 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 6187 KnownStart.getMaxValue() + 1); 6188 if (KnownStart.isNegative()) 6189 // End >=u Start && End <=s Start 6190 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 6191 KnownEnd.getMaxValue() + 1); 6192 break; 6193 } 6194 case Instruction::LShr: { 6195 // For each lshr, three cases: 6196 // shift = 0 => unchanged value 6197 // saturation => 0 6198 // other => a smaller positive number 6199 // Thus, the low end of the unsigned range is the last value produced. 6200 auto KnownEnd = KnownBits::lshr(KnownStart, 6201 KnownBits::makeConstant(TotalShift)); 6202 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 6203 KnownStart.getMaxValue() + 1); 6204 } 6205 case Instruction::Shl: { 6206 // Iff no bits are shifted out, value increases on every shift. 6207 auto KnownEnd = KnownBits::shl(KnownStart, 6208 KnownBits::makeConstant(TotalShift)); 6209 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 6210 return ConstantRange(KnownStart.getMinValue(), 6211 KnownEnd.getMaxValue() + 1); 6212 break; 6213 } 6214 }; 6215 return FullSet; 6216 } 6217 6218 /// Determine the range for a particular SCEV. If SignHint is 6219 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 6220 /// with a "cleaner" unsigned (resp. signed) representation. 6221 const ConstantRange & 6222 ScalarEvolution::getRangeRef(const SCEV *S, 6223 ScalarEvolution::RangeSignHint SignHint) { 6224 DenseMap<const SCEV *, ConstantRange> &Cache = 6225 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 6226 : SignedRanges; 6227 ConstantRange::PreferredRangeType RangeType = 6228 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 6229 ? ConstantRange::Unsigned : ConstantRange::Signed; 6230 6231 // See if we've computed this range already. 6232 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 6233 if (I != Cache.end()) 6234 return I->second; 6235 6236 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 6237 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 6238 6239 unsigned BitWidth = getTypeSizeInBits(S->getType()); 6240 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 6241 using OBO = OverflowingBinaryOperator; 6242 6243 // If the value has known zeros, the maximum value will have those known zeros 6244 // as well. 6245 uint32_t TZ = GetMinTrailingZeros(S); 6246 if (TZ != 0) { 6247 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 6248 ConservativeResult = 6249 ConstantRange(APInt::getMinValue(BitWidth), 6250 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 6251 else 6252 ConservativeResult = ConstantRange( 6253 APInt::getSignedMinValue(BitWidth), 6254 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 6255 } 6256 6257 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 6258 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 6259 unsigned WrapType = OBO::AnyWrap; 6260 if (Add->hasNoSignedWrap()) 6261 WrapType |= OBO::NoSignedWrap; 6262 if (Add->hasNoUnsignedWrap()) 6263 WrapType |= OBO::NoUnsignedWrap; 6264 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 6265 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 6266 WrapType, RangeType); 6267 return setRange(Add, SignHint, 6268 ConservativeResult.intersectWith(X, RangeType)); 6269 } 6270 6271 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 6272 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 6273 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 6274 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 6275 return setRange(Mul, SignHint, 6276 ConservativeResult.intersectWith(X, RangeType)); 6277 } 6278 6279 if (isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) { 6280 Intrinsic::ID ID; 6281 switch (S->getSCEVType()) { 6282 case scUMaxExpr: 6283 ID = Intrinsic::umax; 6284 break; 6285 case scSMaxExpr: 6286 ID = Intrinsic::smax; 6287 break; 6288 case scUMinExpr: 6289 case scSequentialUMinExpr: 6290 ID = Intrinsic::umin; 6291 break; 6292 case scSMinExpr: 6293 ID = Intrinsic::smin; 6294 break; 6295 default: 6296 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr."); 6297 } 6298 6299 const auto *NAry = cast<SCEVNAryExpr>(S); 6300 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint); 6301 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i) 6302 X = X.intrinsic(ID, {X, getRangeRef(NAry->getOperand(i), SignHint)}); 6303 return setRange(S, SignHint, 6304 ConservativeResult.intersectWith(X, RangeType)); 6305 } 6306 6307 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 6308 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 6309 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 6310 return setRange(UDiv, SignHint, 6311 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 6312 } 6313 6314 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 6315 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 6316 return setRange(ZExt, SignHint, 6317 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 6318 RangeType)); 6319 } 6320 6321 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 6322 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 6323 return setRange(SExt, SignHint, 6324 ConservativeResult.intersectWith(X.signExtend(BitWidth), 6325 RangeType)); 6326 } 6327 6328 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 6329 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 6330 return setRange(PtrToInt, SignHint, X); 6331 } 6332 6333 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 6334 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 6335 return setRange(Trunc, SignHint, 6336 ConservativeResult.intersectWith(X.truncate(BitWidth), 6337 RangeType)); 6338 } 6339 6340 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 6341 // If there's no unsigned wrap, the value will never be less than its 6342 // initial value. 6343 if (AddRec->hasNoUnsignedWrap()) { 6344 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 6345 if (!UnsignedMinValue.isZero()) 6346 ConservativeResult = ConservativeResult.intersectWith( 6347 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 6348 } 6349 6350 // If there's no signed wrap, and all the operands except initial value have 6351 // the same sign or zero, the value won't ever be: 6352 // 1: smaller than initial value if operands are non negative, 6353 // 2: bigger than initial value if operands are non positive. 6354 // For both cases, value can not cross signed min/max boundary. 6355 if (AddRec->hasNoSignedWrap()) { 6356 bool AllNonNeg = true; 6357 bool AllNonPos = true; 6358 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 6359 if (!isKnownNonNegative(AddRec->getOperand(i))) 6360 AllNonNeg = false; 6361 if (!isKnownNonPositive(AddRec->getOperand(i))) 6362 AllNonPos = false; 6363 } 6364 if (AllNonNeg) 6365 ConservativeResult = ConservativeResult.intersectWith( 6366 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 6367 APInt::getSignedMinValue(BitWidth)), 6368 RangeType); 6369 else if (AllNonPos) 6370 ConservativeResult = ConservativeResult.intersectWith( 6371 ConstantRange::getNonEmpty( 6372 APInt::getSignedMinValue(BitWidth), 6373 getSignedRangeMax(AddRec->getStart()) + 1), 6374 RangeType); 6375 } 6376 6377 // TODO: non-affine addrec 6378 if (AddRec->isAffine()) { 6379 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 6380 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 6381 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 6382 auto RangeFromAffine = getRangeForAffineAR( 6383 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6384 BitWidth); 6385 ConservativeResult = 6386 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 6387 6388 auto RangeFromFactoring = getRangeViaFactoring( 6389 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6390 BitWidth); 6391 ConservativeResult = 6392 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 6393 } 6394 6395 // Now try symbolic BE count and more powerful methods. 6396 if (UseExpensiveRangeSharpening) { 6397 const SCEV *SymbolicMaxBECount = 6398 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 6399 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 6400 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6401 AddRec->hasNoSelfWrap()) { 6402 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 6403 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 6404 ConservativeResult = 6405 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 6406 } 6407 } 6408 } 6409 6410 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 6411 } 6412 6413 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6414 6415 // Check if the IR explicitly contains !range metadata. 6416 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 6417 if (MDRange.hasValue()) 6418 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 6419 RangeType); 6420 6421 // Use facts about recurrences in the underlying IR. Note that add 6422 // recurrences are AddRecExprs and thus don't hit this path. This 6423 // primarily handles shift recurrences. 6424 auto CR = getRangeForUnknownRecurrence(U); 6425 ConservativeResult = ConservativeResult.intersectWith(CR); 6426 6427 // See if ValueTracking can give us a useful range. 6428 const DataLayout &DL = getDataLayout(); 6429 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6430 if (Known.getBitWidth() != BitWidth) 6431 Known = Known.zextOrTrunc(BitWidth); 6432 6433 // ValueTracking may be able to compute a tighter result for the number of 6434 // sign bits than for the value of those sign bits. 6435 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6436 if (U->getType()->isPointerTy()) { 6437 // If the pointer size is larger than the index size type, this can cause 6438 // NS to be larger than BitWidth. So compensate for this. 6439 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6440 int ptrIdxDiff = ptrSize - BitWidth; 6441 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6442 NS -= ptrIdxDiff; 6443 } 6444 6445 if (NS > 1) { 6446 // If we know any of the sign bits, we know all of the sign bits. 6447 if (!Known.Zero.getHiBits(NS).isZero()) 6448 Known.Zero.setHighBits(NS); 6449 if (!Known.One.getHiBits(NS).isZero()) 6450 Known.One.setHighBits(NS); 6451 } 6452 6453 if (Known.getMinValue() != Known.getMaxValue() + 1) 6454 ConservativeResult = ConservativeResult.intersectWith( 6455 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6456 RangeType); 6457 if (NS > 1) 6458 ConservativeResult = ConservativeResult.intersectWith( 6459 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6460 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6461 RangeType); 6462 6463 // A range of Phi is a subset of union of all ranges of its input. 6464 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 6465 // Make sure that we do not run over cycled Phis. 6466 if (PendingPhiRanges.insert(Phi).second) { 6467 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 6468 for (auto &Op : Phi->operands()) { 6469 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 6470 RangeFromOps = RangeFromOps.unionWith(OpRange); 6471 // No point to continue if we already have a full set. 6472 if (RangeFromOps.isFullSet()) 6473 break; 6474 } 6475 ConservativeResult = 6476 ConservativeResult.intersectWith(RangeFromOps, RangeType); 6477 bool Erased = PendingPhiRanges.erase(Phi); 6478 assert(Erased && "Failed to erase Phi properly?"); 6479 (void) Erased; 6480 } 6481 } 6482 6483 return setRange(U, SignHint, std::move(ConservativeResult)); 6484 } 6485 6486 return setRange(S, SignHint, std::move(ConservativeResult)); 6487 } 6488 6489 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6490 // values that the expression can take. Initially, the expression has a value 6491 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6492 // argument defines if we treat Step as signed or unsigned. 6493 static ConstantRange getRangeForAffineARHelper(APInt Step, 6494 const ConstantRange &StartRange, 6495 const APInt &MaxBECount, 6496 unsigned BitWidth, bool Signed) { 6497 // If either Step or MaxBECount is 0, then the expression won't change, and we 6498 // just need to return the initial range. 6499 if (Step == 0 || MaxBECount == 0) 6500 return StartRange; 6501 6502 // If we don't know anything about the initial value (i.e. StartRange is 6503 // FullRange), then we don't know anything about the final range either. 6504 // Return FullRange. 6505 if (StartRange.isFullSet()) 6506 return ConstantRange::getFull(BitWidth); 6507 6508 // If Step is signed and negative, then we use its absolute value, but we also 6509 // note that we're moving in the opposite direction. 6510 bool Descending = Signed && Step.isNegative(); 6511 6512 if (Signed) 6513 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6514 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6515 // This equations hold true due to the well-defined wrap-around behavior of 6516 // APInt. 6517 Step = Step.abs(); 6518 6519 // Check if Offset is more than full span of BitWidth. If it is, the 6520 // expression is guaranteed to overflow. 6521 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6522 return ConstantRange::getFull(BitWidth); 6523 6524 // Offset is by how much the expression can change. Checks above guarantee no 6525 // overflow here. 6526 APInt Offset = Step * MaxBECount; 6527 6528 // Minimum value of the final range will match the minimal value of StartRange 6529 // if the expression is increasing and will be decreased by Offset otherwise. 6530 // Maximum value of the final range will match the maximal value of StartRange 6531 // if the expression is decreasing and will be increased by Offset otherwise. 6532 APInt StartLower = StartRange.getLower(); 6533 APInt StartUpper = StartRange.getUpper() - 1; 6534 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6535 : (StartUpper + std::move(Offset)); 6536 6537 // It's possible that the new minimum/maximum value will fall into the initial 6538 // range (due to wrap around). This means that the expression can take any 6539 // value in this bitwidth, and we have to return full range. 6540 if (StartRange.contains(MovedBoundary)) 6541 return ConstantRange::getFull(BitWidth); 6542 6543 APInt NewLower = 6544 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6545 APInt NewUpper = 6546 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6547 NewUpper += 1; 6548 6549 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6550 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6551 } 6552 6553 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6554 const SCEV *Step, 6555 const SCEV *MaxBECount, 6556 unsigned BitWidth) { 6557 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6558 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6559 "Precondition!"); 6560 6561 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6562 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6563 6564 // First, consider step signed. 6565 ConstantRange StartSRange = getSignedRange(Start); 6566 ConstantRange StepSRange = getSignedRange(Step); 6567 6568 // If Step can be both positive and negative, we need to find ranges for the 6569 // maximum absolute step values in both directions and union them. 6570 ConstantRange SR = 6571 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6572 MaxBECountValue, BitWidth, /* Signed = */ true); 6573 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6574 StartSRange, MaxBECountValue, 6575 BitWidth, /* Signed = */ true)); 6576 6577 // Next, consider step unsigned. 6578 ConstantRange UR = getRangeForAffineARHelper( 6579 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6580 MaxBECountValue, BitWidth, /* Signed = */ false); 6581 6582 // Finally, intersect signed and unsigned ranges. 6583 return SR.intersectWith(UR, ConstantRange::Smallest); 6584 } 6585 6586 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6587 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6588 ScalarEvolution::RangeSignHint SignHint) { 6589 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6590 assert(AddRec->hasNoSelfWrap() && 6591 "This only works for non-self-wrapping AddRecs!"); 6592 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6593 const SCEV *Step = AddRec->getStepRecurrence(*this); 6594 // Only deal with constant step to save compile time. 6595 if (!isa<SCEVConstant>(Step)) 6596 return ConstantRange::getFull(BitWidth); 6597 // Let's make sure that we can prove that we do not self-wrap during 6598 // MaxBECount iterations. We need this because MaxBECount is a maximum 6599 // iteration count estimate, and we might infer nw from some exit for which we 6600 // do not know max exit count (or any other side reasoning). 6601 // TODO: Turn into assert at some point. 6602 if (getTypeSizeInBits(MaxBECount->getType()) > 6603 getTypeSizeInBits(AddRec->getType())) 6604 return ConstantRange::getFull(BitWidth); 6605 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6606 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6607 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6608 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6609 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6610 MaxItersWithoutWrap)) 6611 return ConstantRange::getFull(BitWidth); 6612 6613 ICmpInst::Predicate LEPred = 6614 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6615 ICmpInst::Predicate GEPred = 6616 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6617 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6618 6619 // We know that there is no self-wrap. Let's take Start and End values and 6620 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6621 // the iteration. They either lie inside the range [Min(Start, End), 6622 // Max(Start, End)] or outside it: 6623 // 6624 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6625 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6626 // 6627 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6628 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6629 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6630 // Start <= End and step is positive, or Start >= End and step is negative. 6631 const SCEV *Start = AddRec->getStart(); 6632 ConstantRange StartRange = getRangeRef(Start, SignHint); 6633 ConstantRange EndRange = getRangeRef(End, SignHint); 6634 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6635 // If they already cover full iteration space, we will know nothing useful 6636 // even if we prove what we want to prove. 6637 if (RangeBetween.isFullSet()) 6638 return RangeBetween; 6639 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6640 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6641 : RangeBetween.isWrappedSet(); 6642 if (IsWrappedSet) 6643 return ConstantRange::getFull(BitWidth); 6644 6645 if (isKnownPositive(Step) && 6646 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6647 return RangeBetween; 6648 else if (isKnownNegative(Step) && 6649 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6650 return RangeBetween; 6651 return ConstantRange::getFull(BitWidth); 6652 } 6653 6654 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6655 const SCEV *Step, 6656 const SCEV *MaxBECount, 6657 unsigned BitWidth) { 6658 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6659 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6660 6661 struct SelectPattern { 6662 Value *Condition = nullptr; 6663 APInt TrueValue; 6664 APInt FalseValue; 6665 6666 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6667 const SCEV *S) { 6668 Optional<unsigned> CastOp; 6669 APInt Offset(BitWidth, 0); 6670 6671 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6672 "Should be!"); 6673 6674 // Peel off a constant offset: 6675 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6676 // In the future we could consider being smarter here and handle 6677 // {Start+Step,+,Step} too. 6678 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6679 return; 6680 6681 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6682 S = SA->getOperand(1); 6683 } 6684 6685 // Peel off a cast operation 6686 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6687 CastOp = SCast->getSCEVType(); 6688 S = SCast->getOperand(); 6689 } 6690 6691 using namespace llvm::PatternMatch; 6692 6693 auto *SU = dyn_cast<SCEVUnknown>(S); 6694 const APInt *TrueVal, *FalseVal; 6695 if (!SU || 6696 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6697 m_APInt(FalseVal)))) { 6698 Condition = nullptr; 6699 return; 6700 } 6701 6702 TrueValue = *TrueVal; 6703 FalseValue = *FalseVal; 6704 6705 // Re-apply the cast we peeled off earlier 6706 if (CastOp.hasValue()) 6707 switch (*CastOp) { 6708 default: 6709 llvm_unreachable("Unknown SCEV cast type!"); 6710 6711 case scTruncate: 6712 TrueValue = TrueValue.trunc(BitWidth); 6713 FalseValue = FalseValue.trunc(BitWidth); 6714 break; 6715 case scZeroExtend: 6716 TrueValue = TrueValue.zext(BitWidth); 6717 FalseValue = FalseValue.zext(BitWidth); 6718 break; 6719 case scSignExtend: 6720 TrueValue = TrueValue.sext(BitWidth); 6721 FalseValue = FalseValue.sext(BitWidth); 6722 break; 6723 } 6724 6725 // Re-apply the constant offset we peeled off earlier 6726 TrueValue += Offset; 6727 FalseValue += Offset; 6728 } 6729 6730 bool isRecognized() { return Condition != nullptr; } 6731 }; 6732 6733 SelectPattern StartPattern(*this, BitWidth, Start); 6734 if (!StartPattern.isRecognized()) 6735 return ConstantRange::getFull(BitWidth); 6736 6737 SelectPattern StepPattern(*this, BitWidth, Step); 6738 if (!StepPattern.isRecognized()) 6739 return ConstantRange::getFull(BitWidth); 6740 6741 if (StartPattern.Condition != StepPattern.Condition) { 6742 // We don't handle this case today; but we could, by considering four 6743 // possibilities below instead of two. I'm not sure if there are cases where 6744 // that will help over what getRange already does, though. 6745 return ConstantRange::getFull(BitWidth); 6746 } 6747 6748 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6749 // construct arbitrary general SCEV expressions here. This function is called 6750 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6751 // say) can end up caching a suboptimal value. 6752 6753 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6754 // C2352 and C2512 (otherwise it isn't needed). 6755 6756 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6757 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6758 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6759 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6760 6761 ConstantRange TrueRange = 6762 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6763 ConstantRange FalseRange = 6764 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6765 6766 return TrueRange.unionWith(FalseRange); 6767 } 6768 6769 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6770 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6771 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6772 6773 // Return early if there are no flags to propagate to the SCEV. 6774 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6775 if (BinOp->hasNoUnsignedWrap()) 6776 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6777 if (BinOp->hasNoSignedWrap()) 6778 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6779 if (Flags == SCEV::FlagAnyWrap) 6780 return SCEV::FlagAnyWrap; 6781 6782 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6783 } 6784 6785 const Instruction * 6786 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) { 6787 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) 6788 return &*AddRec->getLoop()->getHeader()->begin(); 6789 if (auto *U = dyn_cast<SCEVUnknown>(S)) 6790 if (auto *I = dyn_cast<Instruction>(U->getValue())) 6791 return I; 6792 return nullptr; 6793 } 6794 6795 /// Fills \p Ops with unique operands of \p S, if it has operands. If not, 6796 /// \p Ops remains unmodified. 6797 static void collectUniqueOps(const SCEV *S, 6798 SmallVectorImpl<const SCEV *> &Ops) { 6799 SmallPtrSet<const SCEV *, 4> Unique; 6800 auto InsertUnique = [&](const SCEV *S) { 6801 if (Unique.insert(S).second) 6802 Ops.push_back(S); 6803 }; 6804 if (auto *S2 = dyn_cast<SCEVCastExpr>(S)) 6805 for (auto *Op : S2->operands()) 6806 InsertUnique(Op); 6807 else if (auto *S2 = dyn_cast<SCEVNAryExpr>(S)) 6808 for (auto *Op : S2->operands()) 6809 InsertUnique(Op); 6810 else if (auto *S2 = dyn_cast<SCEVUDivExpr>(S)) 6811 for (auto *Op : S2->operands()) 6812 InsertUnique(Op); 6813 } 6814 6815 const Instruction * 6816 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops, 6817 bool &Precise) { 6818 Precise = true; 6819 // Do a bounded search of the def relation of the requested SCEVs. 6820 SmallSet<const SCEV *, 16> Visited; 6821 SmallVector<const SCEV *> Worklist; 6822 auto pushOp = [&](const SCEV *S) { 6823 if (!Visited.insert(S).second) 6824 return; 6825 // Threshold of 30 here is arbitrary. 6826 if (Visited.size() > 30) { 6827 Precise = false; 6828 return; 6829 } 6830 Worklist.push_back(S); 6831 }; 6832 6833 for (auto *S : Ops) 6834 pushOp(S); 6835 6836 const Instruction *Bound = nullptr; 6837 while (!Worklist.empty()) { 6838 auto *S = Worklist.pop_back_val(); 6839 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) { 6840 if (!Bound || DT.dominates(Bound, DefI)) 6841 Bound = DefI; 6842 } else { 6843 SmallVector<const SCEV *, 4> Ops; 6844 collectUniqueOps(S, Ops); 6845 for (auto *Op : Ops) 6846 pushOp(Op); 6847 } 6848 } 6849 return Bound ? Bound : &*F.getEntryBlock().begin(); 6850 } 6851 6852 const Instruction * 6853 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) { 6854 bool Discard; 6855 return getDefiningScopeBound(Ops, Discard); 6856 } 6857 6858 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A, 6859 const Instruction *B) { 6860 if (A->getParent() == B->getParent() && 6861 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 6862 B->getIterator())) 6863 return true; 6864 6865 auto *BLoop = LI.getLoopFor(B->getParent()); 6866 if (BLoop && BLoop->getHeader() == B->getParent() && 6867 BLoop->getLoopPreheader() == A->getParent() && 6868 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 6869 A->getParent()->end()) && 6870 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(), 6871 B->getIterator())) 6872 return true; 6873 return false; 6874 } 6875 6876 6877 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6878 // Only proceed if we can prove that I does not yield poison. 6879 if (!programUndefinedIfPoison(I)) 6880 return false; 6881 6882 // At this point we know that if I is executed, then it does not wrap 6883 // according to at least one of NSW or NUW. If I is not executed, then we do 6884 // not know if the calculation that I represents would wrap. Multiple 6885 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6886 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6887 // derived from other instructions that map to the same SCEV. We cannot make 6888 // that guarantee for cases where I is not executed. So we need to find a 6889 // upper bound on the defining scope for the SCEV, and prove that I is 6890 // executed every time we enter that scope. When the bounding scope is a 6891 // loop (the common case), this is equivalent to proving I executes on every 6892 // iteration of that loop. 6893 SmallVector<const SCEV *> SCEVOps; 6894 for (const Use &Op : I->operands()) { 6895 // I could be an extractvalue from a call to an overflow intrinsic. 6896 // TODO: We can do better here in some cases. 6897 if (isSCEVable(Op->getType())) 6898 SCEVOps.push_back(getSCEV(Op)); 6899 } 6900 auto *DefI = getDefiningScopeBound(SCEVOps); 6901 return isGuaranteedToTransferExecutionTo(DefI, I); 6902 } 6903 6904 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6905 // If we know that \c I can never be poison period, then that's enough. 6906 if (isSCEVExprNeverPoison(I)) 6907 return true; 6908 6909 // For an add recurrence specifically, we assume that infinite loops without 6910 // side effects are undefined behavior, and then reason as follows: 6911 // 6912 // If the add recurrence is poison in any iteration, it is poison on all 6913 // future iterations (since incrementing poison yields poison). If the result 6914 // of the add recurrence is fed into the loop latch condition and the loop 6915 // does not contain any throws or exiting blocks other than the latch, we now 6916 // have the ability to "choose" whether the backedge is taken or not (by 6917 // choosing a sufficiently evil value for the poison feeding into the branch) 6918 // for every iteration including and after the one in which \p I first became 6919 // poison. There are two possibilities (let's call the iteration in which \p 6920 // I first became poison as K): 6921 // 6922 // 1. In the set of iterations including and after K, the loop body executes 6923 // no side effects. In this case executing the backege an infinte number 6924 // of times will yield undefined behavior. 6925 // 6926 // 2. In the set of iterations including and after K, the loop body executes 6927 // at least one side effect. In this case, that specific instance of side 6928 // effect is control dependent on poison, which also yields undefined 6929 // behavior. 6930 6931 auto *ExitingBB = L->getExitingBlock(); 6932 auto *LatchBB = L->getLoopLatch(); 6933 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6934 return false; 6935 6936 SmallPtrSet<const Instruction *, 16> Pushed; 6937 SmallVector<const Instruction *, 8> PoisonStack; 6938 6939 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6940 // things that are known to be poison under that assumption go on the 6941 // PoisonStack. 6942 Pushed.insert(I); 6943 PoisonStack.push_back(I); 6944 6945 bool LatchControlDependentOnPoison = false; 6946 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6947 const Instruction *Poison = PoisonStack.pop_back_val(); 6948 6949 for (auto *PoisonUser : Poison->users()) { 6950 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6951 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6952 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6953 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6954 assert(BI->isConditional() && "Only possibility!"); 6955 if (BI->getParent() == LatchBB) { 6956 LatchControlDependentOnPoison = true; 6957 break; 6958 } 6959 } 6960 } 6961 } 6962 6963 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6964 } 6965 6966 ScalarEvolution::LoopProperties 6967 ScalarEvolution::getLoopProperties(const Loop *L) { 6968 using LoopProperties = ScalarEvolution::LoopProperties; 6969 6970 auto Itr = LoopPropertiesCache.find(L); 6971 if (Itr == LoopPropertiesCache.end()) { 6972 auto HasSideEffects = [](Instruction *I) { 6973 if (auto *SI = dyn_cast<StoreInst>(I)) 6974 return !SI->isSimple(); 6975 6976 return I->mayThrow() || I->mayWriteToMemory(); 6977 }; 6978 6979 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6980 /*HasNoSideEffects*/ true}; 6981 6982 for (auto *BB : L->getBlocks()) 6983 for (auto &I : *BB) { 6984 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6985 LP.HasNoAbnormalExits = false; 6986 if (HasSideEffects(&I)) 6987 LP.HasNoSideEffects = false; 6988 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6989 break; // We're already as pessimistic as we can get. 6990 } 6991 6992 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6993 assert(InsertPair.second && "We just checked!"); 6994 Itr = InsertPair.first; 6995 } 6996 6997 return Itr->second; 6998 } 6999 7000 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) { 7001 // A mustprogress loop without side effects must be finite. 7002 // TODO: The check used here is very conservative. It's only *specific* 7003 // side effects which are well defined in infinite loops. 7004 return isMustProgress(L) && loopHasNoSideEffects(L); 7005 } 7006 7007 const SCEV *ScalarEvolution::createSCEV(Value *V) { 7008 if (!isSCEVable(V->getType())) 7009 return getUnknown(V); 7010 7011 if (Instruction *I = dyn_cast<Instruction>(V)) { 7012 // Don't attempt to analyze instructions in blocks that aren't 7013 // reachable. Such instructions don't matter, and they aren't required 7014 // to obey basic rules for definitions dominating uses which this 7015 // analysis depends on. 7016 if (!DT.isReachableFromEntry(I->getParent())) 7017 return getUnknown(UndefValue::get(V->getType())); 7018 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 7019 return getConstant(CI); 7020 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 7021 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 7022 else if (!isa<ConstantExpr>(V)) 7023 return getUnknown(V); 7024 7025 Operator *U = cast<Operator>(V); 7026 if (auto BO = MatchBinaryOp(U, DT)) { 7027 switch (BO->Opcode) { 7028 case Instruction::Add: { 7029 // The simple thing to do would be to just call getSCEV on both operands 7030 // and call getAddExpr with the result. However if we're looking at a 7031 // bunch of things all added together, this can be quite inefficient, 7032 // because it leads to N-1 getAddExpr calls for N ultimate operands. 7033 // Instead, gather up all the operands and make a single getAddExpr call. 7034 // LLVM IR canonical form means we need only traverse the left operands. 7035 SmallVector<const SCEV *, 4> AddOps; 7036 do { 7037 if (BO->Op) { 7038 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 7039 AddOps.push_back(OpSCEV); 7040 break; 7041 } 7042 7043 // If a NUW or NSW flag can be applied to the SCEV for this 7044 // addition, then compute the SCEV for this addition by itself 7045 // with a separate call to getAddExpr. We need to do that 7046 // instead of pushing the operands of the addition onto AddOps, 7047 // since the flags are only known to apply to this particular 7048 // addition - they may not apply to other additions that can be 7049 // formed with operands from AddOps. 7050 const SCEV *RHS = getSCEV(BO->RHS); 7051 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 7052 if (Flags != SCEV::FlagAnyWrap) { 7053 const SCEV *LHS = getSCEV(BO->LHS); 7054 if (BO->Opcode == Instruction::Sub) 7055 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 7056 else 7057 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 7058 break; 7059 } 7060 } 7061 7062 if (BO->Opcode == Instruction::Sub) 7063 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 7064 else 7065 AddOps.push_back(getSCEV(BO->RHS)); 7066 7067 auto NewBO = MatchBinaryOp(BO->LHS, DT); 7068 if (!NewBO || (NewBO->Opcode != Instruction::Add && 7069 NewBO->Opcode != Instruction::Sub)) { 7070 AddOps.push_back(getSCEV(BO->LHS)); 7071 break; 7072 } 7073 BO = NewBO; 7074 } while (true); 7075 7076 return getAddExpr(AddOps); 7077 } 7078 7079 case Instruction::Mul: { 7080 SmallVector<const SCEV *, 4> MulOps; 7081 do { 7082 if (BO->Op) { 7083 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 7084 MulOps.push_back(OpSCEV); 7085 break; 7086 } 7087 7088 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 7089 if (Flags != SCEV::FlagAnyWrap) { 7090 MulOps.push_back( 7091 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 7092 break; 7093 } 7094 } 7095 7096 MulOps.push_back(getSCEV(BO->RHS)); 7097 auto NewBO = MatchBinaryOp(BO->LHS, DT); 7098 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 7099 MulOps.push_back(getSCEV(BO->LHS)); 7100 break; 7101 } 7102 BO = NewBO; 7103 } while (true); 7104 7105 return getMulExpr(MulOps); 7106 } 7107 case Instruction::UDiv: 7108 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7109 case Instruction::URem: 7110 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7111 case Instruction::Sub: { 7112 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 7113 if (BO->Op) 7114 Flags = getNoWrapFlagsFromUB(BO->Op); 7115 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 7116 } 7117 case Instruction::And: 7118 // For an expression like x&255 that merely masks off the high bits, 7119 // use zext(trunc(x)) as the SCEV expression. 7120 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 7121 if (CI->isZero()) 7122 return getSCEV(BO->RHS); 7123 if (CI->isMinusOne()) 7124 return getSCEV(BO->LHS); 7125 const APInt &A = CI->getValue(); 7126 7127 // Instcombine's ShrinkDemandedConstant may strip bits out of 7128 // constants, obscuring what would otherwise be a low-bits mask. 7129 // Use computeKnownBits to compute what ShrinkDemandedConstant 7130 // knew about to reconstruct a low-bits mask value. 7131 unsigned LZ = A.countLeadingZeros(); 7132 unsigned TZ = A.countTrailingZeros(); 7133 unsigned BitWidth = A.getBitWidth(); 7134 KnownBits Known(BitWidth); 7135 computeKnownBits(BO->LHS, Known, getDataLayout(), 7136 0, &AC, nullptr, &DT); 7137 7138 APInt EffectiveMask = 7139 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 7140 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 7141 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 7142 const SCEV *LHS = getSCEV(BO->LHS); 7143 const SCEV *ShiftedLHS = nullptr; 7144 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 7145 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 7146 // For an expression like (x * 8) & 8, simplify the multiply. 7147 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 7148 unsigned GCD = std::min(MulZeros, TZ); 7149 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 7150 SmallVector<const SCEV*, 4> MulOps; 7151 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 7152 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 7153 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 7154 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 7155 } 7156 } 7157 if (!ShiftedLHS) 7158 ShiftedLHS = getUDivExpr(LHS, MulCount); 7159 return getMulExpr( 7160 getZeroExtendExpr( 7161 getTruncateExpr(ShiftedLHS, 7162 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 7163 BO->LHS->getType()), 7164 MulCount); 7165 } 7166 } 7167 break; 7168 7169 case Instruction::Or: 7170 // If the RHS of the Or is a constant, we may have something like: 7171 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 7172 // optimizations will transparently handle this case. 7173 // 7174 // In order for this transformation to be safe, the LHS must be of the 7175 // form X*(2^n) and the Or constant must be less than 2^n. 7176 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 7177 const SCEV *LHS = getSCEV(BO->LHS); 7178 const APInt &CIVal = CI->getValue(); 7179 if (GetMinTrailingZeros(LHS) >= 7180 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 7181 // Build a plain add SCEV. 7182 return getAddExpr(LHS, getSCEV(CI), 7183 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 7184 } 7185 } 7186 break; 7187 7188 case Instruction::Xor: 7189 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 7190 // If the RHS of xor is -1, then this is a not operation. 7191 if (CI->isMinusOne()) 7192 return getNotSCEV(getSCEV(BO->LHS)); 7193 7194 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 7195 // This is a variant of the check for xor with -1, and it handles 7196 // the case where instcombine has trimmed non-demanded bits out 7197 // of an xor with -1. 7198 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 7199 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 7200 if (LBO->getOpcode() == Instruction::And && 7201 LCI->getValue() == CI->getValue()) 7202 if (const SCEVZeroExtendExpr *Z = 7203 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 7204 Type *UTy = BO->LHS->getType(); 7205 const SCEV *Z0 = Z->getOperand(); 7206 Type *Z0Ty = Z0->getType(); 7207 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 7208 7209 // If C is a low-bits mask, the zero extend is serving to 7210 // mask off the high bits. Complement the operand and 7211 // re-apply the zext. 7212 if (CI->getValue().isMask(Z0TySize)) 7213 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 7214 7215 // If C is a single bit, it may be in the sign-bit position 7216 // before the zero-extend. In this case, represent the xor 7217 // using an add, which is equivalent, and re-apply the zext. 7218 APInt Trunc = CI->getValue().trunc(Z0TySize); 7219 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 7220 Trunc.isSignMask()) 7221 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 7222 UTy); 7223 } 7224 } 7225 break; 7226 7227 case Instruction::Shl: 7228 // Turn shift left of a constant amount into a multiply. 7229 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 7230 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 7231 7232 // If the shift count is not less than the bitwidth, the result of 7233 // the shift is undefined. Don't try to analyze it, because the 7234 // resolution chosen here may differ from the resolution chosen in 7235 // other parts of the compiler. 7236 if (SA->getValue().uge(BitWidth)) 7237 break; 7238 7239 // We can safely preserve the nuw flag in all cases. It's also safe to 7240 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 7241 // requires special handling. It can be preserved as long as we're not 7242 // left shifting by bitwidth - 1. 7243 auto Flags = SCEV::FlagAnyWrap; 7244 if (BO->Op) { 7245 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 7246 if ((MulFlags & SCEV::FlagNSW) && 7247 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 7248 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 7249 if (MulFlags & SCEV::FlagNUW) 7250 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 7251 } 7252 7253 Constant *X = ConstantInt::get( 7254 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 7255 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 7256 } 7257 break; 7258 7259 case Instruction::AShr: { 7260 // AShr X, C, where C is a constant. 7261 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 7262 if (!CI) 7263 break; 7264 7265 Type *OuterTy = BO->LHS->getType(); 7266 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 7267 // If the shift count is not less than the bitwidth, the result of 7268 // the shift is undefined. Don't try to analyze it, because the 7269 // resolution chosen here may differ from the resolution chosen in 7270 // other parts of the compiler. 7271 if (CI->getValue().uge(BitWidth)) 7272 break; 7273 7274 if (CI->isZero()) 7275 return getSCEV(BO->LHS); // shift by zero --> noop 7276 7277 uint64_t AShrAmt = CI->getZExtValue(); 7278 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 7279 7280 Operator *L = dyn_cast<Operator>(BO->LHS); 7281 if (L && L->getOpcode() == Instruction::Shl) { 7282 // X = Shl A, n 7283 // Y = AShr X, m 7284 // Both n and m are constant. 7285 7286 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 7287 if (L->getOperand(1) == BO->RHS) 7288 // For a two-shift sext-inreg, i.e. n = m, 7289 // use sext(trunc(x)) as the SCEV expression. 7290 return getSignExtendExpr( 7291 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 7292 7293 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 7294 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 7295 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 7296 if (ShlAmt > AShrAmt) { 7297 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 7298 // expression. We already checked that ShlAmt < BitWidth, so 7299 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 7300 // ShlAmt - AShrAmt < Amt. 7301 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 7302 ShlAmt - AShrAmt); 7303 return getSignExtendExpr( 7304 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 7305 getConstant(Mul)), OuterTy); 7306 } 7307 } 7308 } 7309 break; 7310 } 7311 } 7312 } 7313 7314 switch (U->getOpcode()) { 7315 case Instruction::Trunc: 7316 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 7317 7318 case Instruction::ZExt: 7319 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7320 7321 case Instruction::SExt: 7322 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 7323 // The NSW flag of a subtract does not always survive the conversion to 7324 // A + (-1)*B. By pushing sign extension onto its operands we are much 7325 // more likely to preserve NSW and allow later AddRec optimisations. 7326 // 7327 // NOTE: This is effectively duplicating this logic from getSignExtend: 7328 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 7329 // but by that point the NSW information has potentially been lost. 7330 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 7331 Type *Ty = U->getType(); 7332 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 7333 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 7334 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 7335 } 7336 } 7337 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7338 7339 case Instruction::BitCast: 7340 // BitCasts are no-op casts so we just eliminate the cast. 7341 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 7342 return getSCEV(U->getOperand(0)); 7343 break; 7344 7345 case Instruction::PtrToInt: { 7346 // Pointer to integer cast is straight-forward, so do model it. 7347 const SCEV *Op = getSCEV(U->getOperand(0)); 7348 Type *DstIntTy = U->getType(); 7349 // But only if effective SCEV (integer) type is wide enough to represent 7350 // all possible pointer values. 7351 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 7352 if (isa<SCEVCouldNotCompute>(IntOp)) 7353 return getUnknown(V); 7354 return IntOp; 7355 } 7356 case Instruction::IntToPtr: 7357 // Just don't deal with inttoptr casts. 7358 return getUnknown(V); 7359 7360 case Instruction::SDiv: 7361 // If both operands are non-negative, this is just an udiv. 7362 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7363 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7364 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7365 break; 7366 7367 case Instruction::SRem: 7368 // If both operands are non-negative, this is just an urem. 7369 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7370 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7371 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7372 break; 7373 7374 case Instruction::GetElementPtr: 7375 return createNodeForGEP(cast<GEPOperator>(U)); 7376 7377 case Instruction::PHI: 7378 return createNodeForPHI(cast<PHINode>(U)); 7379 7380 case Instruction::Select: 7381 // U can also be a select constant expr, which let fall through. Since 7382 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 7383 // constant expressions cannot have instructions as operands, we'd have 7384 // returned getUnknown for a select constant expressions anyway. 7385 if (isa<Instruction>(U)) 7386 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 7387 U->getOperand(1), U->getOperand(2)); 7388 break; 7389 7390 case Instruction::Call: 7391 case Instruction::Invoke: 7392 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 7393 return getSCEV(RV); 7394 7395 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 7396 switch (II->getIntrinsicID()) { 7397 case Intrinsic::abs: 7398 return getAbsExpr( 7399 getSCEV(II->getArgOperand(0)), 7400 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 7401 case Intrinsic::umax: 7402 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 7403 getSCEV(II->getArgOperand(1))); 7404 case Intrinsic::umin: 7405 return getUMinExpr(getSCEV(II->getArgOperand(0)), 7406 getSCEV(II->getArgOperand(1))); 7407 case Intrinsic::smax: 7408 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 7409 getSCEV(II->getArgOperand(1))); 7410 case Intrinsic::smin: 7411 return getSMinExpr(getSCEV(II->getArgOperand(0)), 7412 getSCEV(II->getArgOperand(1))); 7413 case Intrinsic::usub_sat: { 7414 const SCEV *X = getSCEV(II->getArgOperand(0)); 7415 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7416 const SCEV *ClampedY = getUMinExpr(X, Y); 7417 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 7418 } 7419 case Intrinsic::uadd_sat: { 7420 const SCEV *X = getSCEV(II->getArgOperand(0)); 7421 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7422 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 7423 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 7424 } 7425 case Intrinsic::start_loop_iterations: 7426 // A start_loop_iterations is just equivalent to the first operand for 7427 // SCEV purposes. 7428 return getSCEV(II->getArgOperand(0)); 7429 default: 7430 break; 7431 } 7432 } 7433 break; 7434 } 7435 7436 return getUnknown(V); 7437 } 7438 7439 //===----------------------------------------------------------------------===// 7440 // Iteration Count Computation Code 7441 // 7442 7443 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount, 7444 bool Extend) { 7445 if (isa<SCEVCouldNotCompute>(ExitCount)) 7446 return getCouldNotCompute(); 7447 7448 auto *ExitCountType = ExitCount->getType(); 7449 assert(ExitCountType->isIntegerTy()); 7450 7451 if (!Extend) 7452 return getAddExpr(ExitCount, getOne(ExitCountType)); 7453 7454 auto *WiderType = Type::getIntNTy(ExitCountType->getContext(), 7455 1 + ExitCountType->getScalarSizeInBits()); 7456 return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType), 7457 getOne(WiderType)); 7458 } 7459 7460 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 7461 if (!ExitCount) 7462 return 0; 7463 7464 ConstantInt *ExitConst = ExitCount->getValue(); 7465 7466 // Guard against huge trip counts. 7467 if (ExitConst->getValue().getActiveBits() > 32) 7468 return 0; 7469 7470 // In case of integer overflow, this returns 0, which is correct. 7471 return ((unsigned)ExitConst->getZExtValue()) + 1; 7472 } 7473 7474 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 7475 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 7476 return getConstantTripCount(ExitCount); 7477 } 7478 7479 unsigned 7480 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 7481 const BasicBlock *ExitingBlock) { 7482 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7483 assert(L->isLoopExiting(ExitingBlock) && 7484 "Exiting block must actually branch out of the loop!"); 7485 const SCEVConstant *ExitCount = 7486 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 7487 return getConstantTripCount(ExitCount); 7488 } 7489 7490 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 7491 const auto *MaxExitCount = 7492 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 7493 return getConstantTripCount(MaxExitCount); 7494 } 7495 7496 const SCEV *ScalarEvolution::getConstantMaxTripCountFromArray(const Loop *L) { 7497 // We can't infer from Array in Irregular Loop. 7498 // FIXME: It's hard to infer loop bound from array operated in Nested Loop. 7499 if (!L->isLoopSimplifyForm() || !L->isInnermost()) 7500 return getCouldNotCompute(); 7501 7502 // FIXME: To make the scene more typical, we only analysis loops that have 7503 // one exiting block and that block must be the latch. To make it easier to 7504 // capture loops that have memory access and memory access will be executed 7505 // in each iteration. 7506 const BasicBlock *LoopLatch = L->getLoopLatch(); 7507 assert(LoopLatch && "See defination of simplify form loop."); 7508 if (L->getExitingBlock() != LoopLatch) 7509 return getCouldNotCompute(); 7510 7511 const DataLayout &DL = getDataLayout(); 7512 SmallVector<const SCEV *> InferCountColl; 7513 for (auto *BB : L->getBlocks()) { 7514 // Go here, we can know that Loop is a single exiting and simplified form 7515 // loop. Make sure that infer from Memory Operation in those BBs must be 7516 // executed in loop. First step, we can make sure that max execution time 7517 // of MemAccessBB in loop represents latch max excution time. 7518 // If MemAccessBB does not dom Latch, skip. 7519 // Entry 7520 // │ 7521 // ┌─────▼─────┐ 7522 // │Loop Header◄─────┐ 7523 // └──┬──────┬─┘ │ 7524 // │ │ │ 7525 // ┌────────▼──┐ ┌─▼─────┐ │ 7526 // │MemAccessBB│ │OtherBB│ │ 7527 // └────────┬──┘ └─┬─────┘ │ 7528 // │ │ │ 7529 // ┌─▼──────▼─┐ │ 7530 // │Loop Latch├─────┘ 7531 // └────┬─────┘ 7532 // ▼ 7533 // Exit 7534 if (!DT.dominates(BB, LoopLatch)) 7535 continue; 7536 7537 for (Instruction &Inst : *BB) { 7538 // Find Memory Operation Instruction. 7539 auto *GEP = getLoadStorePointerOperand(&Inst); 7540 if (!GEP) 7541 continue; 7542 7543 auto *ElemSize = dyn_cast<SCEVConstant>(getElementSize(&Inst)); 7544 // Do not infer from scalar type, eg."ElemSize = sizeof()". 7545 if (!ElemSize) 7546 continue; 7547 7548 // Use a existing polynomial recurrence on the trip count. 7549 auto *AddRec = dyn_cast<SCEVAddRecExpr>(getSCEV(GEP)); 7550 if (!AddRec) 7551 continue; 7552 auto *ArrBase = dyn_cast<SCEVUnknown>(getPointerBase(AddRec)); 7553 auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*this)); 7554 if (!ArrBase || !Step) 7555 continue; 7556 assert(isLoopInvariant(ArrBase, L) && "See addrec definition"); 7557 7558 // Only handle { %array + step }, 7559 // FIXME: {(SCEVAddRecExpr) + step } could not be analysed here. 7560 if (AddRec->getStart() != ArrBase) 7561 continue; 7562 7563 // Memory operation pattern which have gaps. 7564 // Or repeat memory opreation. 7565 // And index of GEP wraps arround. 7566 if (Step->getAPInt().getActiveBits() > 32 || 7567 Step->getAPInt().getZExtValue() != 7568 ElemSize->getAPInt().getZExtValue() || 7569 Step->isZero() || Step->getAPInt().isNegative()) 7570 continue; 7571 7572 // Only infer from stack array which has certain size. 7573 // Make sure alloca instruction is not excuted in loop. 7574 AllocaInst *AllocateInst = dyn_cast<AllocaInst>(ArrBase->getValue()); 7575 if (!AllocateInst || L->contains(AllocateInst->getParent())) 7576 continue; 7577 7578 // Make sure only handle normal array. 7579 auto *Ty = dyn_cast<ArrayType>(AllocateInst->getAllocatedType()); 7580 auto *ArrSize = dyn_cast<ConstantInt>(AllocateInst->getArraySize()); 7581 if (!Ty || !ArrSize || !ArrSize->isOne()) 7582 continue; 7583 // Also make sure step was increased the same with sizeof allocated 7584 // element type. 7585 const PointerType *GEPT = dyn_cast<PointerType>(GEP->getType()); 7586 if (Ty->getElementType() != GEPT->getElementType()) 7587 continue; 7588 7589 // FIXME: Since gep indices are silently zext to the indexing type, 7590 // we will have a narrow gep index which wraps around rather than 7591 // increasing strictly, we shoule ensure that step is increasing 7592 // strictly by the loop iteration. 7593 // Now we can infer a max execution time by MemLength/StepLength. 7594 const SCEV *MemSize = 7595 getConstant(Step->getType(), DL.getTypeAllocSize(Ty)); 7596 auto *MaxExeCount = 7597 dyn_cast<SCEVConstant>(getUDivCeilSCEV(MemSize, Step)); 7598 if (!MaxExeCount || MaxExeCount->getAPInt().getActiveBits() > 32) 7599 continue; 7600 7601 // If the loop reaches the maximum number of executions, we can not 7602 // access bytes starting outside the statically allocated size without 7603 // being immediate UB. But it is allowed to enter loop header one more 7604 // time. 7605 auto *InferCount = dyn_cast<SCEVConstant>( 7606 getAddExpr(MaxExeCount, getOne(MaxExeCount->getType()))); 7607 // Discard the maximum number of execution times under 32bits. 7608 if (!InferCount || InferCount->getAPInt().getActiveBits() > 32) 7609 continue; 7610 7611 InferCountColl.push_back(InferCount); 7612 } 7613 } 7614 7615 if (InferCountColl.size() == 0) 7616 return getCouldNotCompute(); 7617 7618 return getUMinFromMismatchedTypes(InferCountColl); 7619 } 7620 7621 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 7622 SmallVector<BasicBlock *, 8> ExitingBlocks; 7623 L->getExitingBlocks(ExitingBlocks); 7624 7625 Optional<unsigned> Res = None; 7626 for (auto *ExitingBB : ExitingBlocks) { 7627 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 7628 if (!Res) 7629 Res = Multiple; 7630 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 7631 } 7632 return Res.getValueOr(1); 7633 } 7634 7635 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7636 const SCEV *ExitCount) { 7637 if (ExitCount == getCouldNotCompute()) 7638 return 1; 7639 7640 // Get the trip count 7641 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7642 7643 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7644 if (!TC) 7645 // Attempt to factor more general cases. Returns the greatest power of 7646 // two divisor. If overflow happens, the trip count expression is still 7647 // divisible by the greatest power of 2 divisor returned. 7648 return 1U << std::min((uint32_t)31, 7649 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7650 7651 ConstantInt *Result = TC->getValue(); 7652 7653 // Guard against huge trip counts (this requires checking 7654 // for zero to handle the case where the trip count == -1 and the 7655 // addition wraps). 7656 if (!Result || Result->getValue().getActiveBits() > 32 || 7657 Result->getValue().getActiveBits() == 0) 7658 return 1; 7659 7660 return (unsigned)Result->getZExtValue(); 7661 } 7662 7663 /// Returns the largest constant divisor of the trip count of this loop as a 7664 /// normal unsigned value, if possible. This means that the actual trip count is 7665 /// always a multiple of the returned value (don't forget the trip count could 7666 /// very well be zero as well!). 7667 /// 7668 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7669 /// multiple of a constant (which is also the case if the trip count is simply 7670 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7671 /// if the trip count is very large (>= 2^32). 7672 /// 7673 /// As explained in the comments for getSmallConstantTripCount, this assumes 7674 /// that control exits the loop via ExitingBlock. 7675 unsigned 7676 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7677 const BasicBlock *ExitingBlock) { 7678 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7679 assert(L->isLoopExiting(ExitingBlock) && 7680 "Exiting block must actually branch out of the loop!"); 7681 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7682 return getSmallConstantTripMultiple(L, ExitCount); 7683 } 7684 7685 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7686 const BasicBlock *ExitingBlock, 7687 ExitCountKind Kind) { 7688 switch (Kind) { 7689 case Exact: 7690 case SymbolicMaximum: 7691 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7692 case ConstantMaximum: 7693 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7694 }; 7695 llvm_unreachable("Invalid ExitCountKind!"); 7696 } 7697 7698 const SCEV * 7699 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7700 SCEVUnionPredicate &Preds) { 7701 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7702 } 7703 7704 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7705 ExitCountKind Kind) { 7706 switch (Kind) { 7707 case Exact: 7708 return getBackedgeTakenInfo(L).getExact(L, this); 7709 case ConstantMaximum: 7710 return getBackedgeTakenInfo(L).getConstantMax(this); 7711 case SymbolicMaximum: 7712 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7713 }; 7714 llvm_unreachable("Invalid ExitCountKind!"); 7715 } 7716 7717 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7718 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7719 } 7720 7721 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7722 static void PushLoopPHIs(const Loop *L, 7723 SmallVectorImpl<Instruction *> &Worklist, 7724 SmallPtrSetImpl<Instruction *> &Visited) { 7725 BasicBlock *Header = L->getHeader(); 7726 7727 // Push all Loop-header PHIs onto the Worklist stack. 7728 for (PHINode &PN : Header->phis()) 7729 if (Visited.insert(&PN).second) 7730 Worklist.push_back(&PN); 7731 } 7732 7733 const ScalarEvolution::BackedgeTakenInfo & 7734 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7735 auto &BTI = getBackedgeTakenInfo(L); 7736 if (BTI.hasFullInfo()) 7737 return BTI; 7738 7739 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7740 7741 if (!Pair.second) 7742 return Pair.first->second; 7743 7744 BackedgeTakenInfo Result = 7745 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7746 7747 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7748 } 7749 7750 ScalarEvolution::BackedgeTakenInfo & 7751 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7752 // Initially insert an invalid entry for this loop. If the insertion 7753 // succeeds, proceed to actually compute a backedge-taken count and 7754 // update the value. The temporary CouldNotCompute value tells SCEV 7755 // code elsewhere that it shouldn't attempt to request a new 7756 // backedge-taken count, which could result in infinite recursion. 7757 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7758 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7759 if (!Pair.second) 7760 return Pair.first->second; 7761 7762 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7763 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7764 // must be cleared in this scope. 7765 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7766 7767 // In product build, there are no usage of statistic. 7768 (void)NumTripCountsComputed; 7769 (void)NumTripCountsNotComputed; 7770 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7771 const SCEV *BEExact = Result.getExact(L, this); 7772 if (BEExact != getCouldNotCompute()) { 7773 assert(isLoopInvariant(BEExact, L) && 7774 isLoopInvariant(Result.getConstantMax(this), L) && 7775 "Computed backedge-taken count isn't loop invariant for loop!"); 7776 ++NumTripCountsComputed; 7777 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7778 isa<PHINode>(L->getHeader()->begin())) { 7779 // Only count loops that have phi nodes as not being computable. 7780 ++NumTripCountsNotComputed; 7781 } 7782 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7783 7784 // Now that we know more about the trip count for this loop, forget any 7785 // existing SCEV values for PHI nodes in this loop since they are only 7786 // conservative estimates made without the benefit of trip count 7787 // information. This invalidation is not necessary for correctness, and is 7788 // only done to produce more precise results. 7789 if (Result.hasAnyInfo()) { 7790 // Invalidate any expression using an addrec in this loop. 7791 SmallVector<const SCEV *, 8> ToForget; 7792 auto LoopUsersIt = LoopUsers.find(L); 7793 if (LoopUsersIt != LoopUsers.end()) 7794 append_range(ToForget, LoopUsersIt->second); 7795 forgetMemoizedResults(ToForget); 7796 7797 // Invalidate constant-evolved loop header phis. 7798 for (PHINode &PN : L->getHeader()->phis()) 7799 ConstantEvolutionLoopExitValue.erase(&PN); 7800 } 7801 7802 // Re-lookup the insert position, since the call to 7803 // computeBackedgeTakenCount above could result in a 7804 // recusive call to getBackedgeTakenInfo (on a different 7805 // loop), which would invalidate the iterator computed 7806 // earlier. 7807 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7808 } 7809 7810 void ScalarEvolution::forgetAllLoops() { 7811 // This method is intended to forget all info about loops. It should 7812 // invalidate caches as if the following happened: 7813 // - The trip counts of all loops have changed arbitrarily 7814 // - Every llvm::Value has been updated in place to produce a different 7815 // result. 7816 BackedgeTakenCounts.clear(); 7817 PredicatedBackedgeTakenCounts.clear(); 7818 BECountUsers.clear(); 7819 LoopPropertiesCache.clear(); 7820 ConstantEvolutionLoopExitValue.clear(); 7821 ValueExprMap.clear(); 7822 ValuesAtScopes.clear(); 7823 ValuesAtScopesUsers.clear(); 7824 LoopDispositions.clear(); 7825 BlockDispositions.clear(); 7826 UnsignedRanges.clear(); 7827 SignedRanges.clear(); 7828 ExprValueMap.clear(); 7829 HasRecMap.clear(); 7830 MinTrailingZerosCache.clear(); 7831 PredicatedSCEVRewrites.clear(); 7832 } 7833 7834 void ScalarEvolution::forgetLoop(const Loop *L) { 7835 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7836 SmallVector<Instruction *, 32> Worklist; 7837 SmallPtrSet<Instruction *, 16> Visited; 7838 SmallVector<const SCEV *, 16> ToForget; 7839 7840 // Iterate over all the loops and sub-loops to drop SCEV information. 7841 while (!LoopWorklist.empty()) { 7842 auto *CurrL = LoopWorklist.pop_back_val(); 7843 7844 // Drop any stored trip count value. 7845 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false); 7846 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true); 7847 7848 // Drop information about predicated SCEV rewrites for this loop. 7849 for (auto I = PredicatedSCEVRewrites.begin(); 7850 I != PredicatedSCEVRewrites.end();) { 7851 std::pair<const SCEV *, const Loop *> Entry = I->first; 7852 if (Entry.second == CurrL) 7853 PredicatedSCEVRewrites.erase(I++); 7854 else 7855 ++I; 7856 } 7857 7858 auto LoopUsersItr = LoopUsers.find(CurrL); 7859 if (LoopUsersItr != LoopUsers.end()) { 7860 ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(), 7861 LoopUsersItr->second.end()); 7862 LoopUsers.erase(LoopUsersItr); 7863 } 7864 7865 // Drop information about expressions based on loop-header PHIs. 7866 PushLoopPHIs(CurrL, Worklist, Visited); 7867 7868 while (!Worklist.empty()) { 7869 Instruction *I = Worklist.pop_back_val(); 7870 7871 ValueExprMapType::iterator It = 7872 ValueExprMap.find_as(static_cast<Value *>(I)); 7873 if (It != ValueExprMap.end()) { 7874 eraseValueFromMap(It->first); 7875 ToForget.push_back(It->second); 7876 if (PHINode *PN = dyn_cast<PHINode>(I)) 7877 ConstantEvolutionLoopExitValue.erase(PN); 7878 } 7879 7880 PushDefUseChildren(I, Worklist, Visited); 7881 } 7882 7883 LoopPropertiesCache.erase(CurrL); 7884 // Forget all contained loops too, to avoid dangling entries in the 7885 // ValuesAtScopes map. 7886 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7887 } 7888 forgetMemoizedResults(ToForget); 7889 } 7890 7891 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7892 while (Loop *Parent = L->getParentLoop()) 7893 L = Parent; 7894 forgetLoop(L); 7895 } 7896 7897 void ScalarEvolution::forgetValue(Value *V) { 7898 Instruction *I = dyn_cast<Instruction>(V); 7899 if (!I) return; 7900 7901 // Drop information about expressions based on loop-header PHIs. 7902 SmallVector<Instruction *, 16> Worklist; 7903 SmallPtrSet<Instruction *, 8> Visited; 7904 SmallVector<const SCEV *, 8> ToForget; 7905 Worklist.push_back(I); 7906 Visited.insert(I); 7907 7908 while (!Worklist.empty()) { 7909 I = Worklist.pop_back_val(); 7910 ValueExprMapType::iterator It = 7911 ValueExprMap.find_as(static_cast<Value *>(I)); 7912 if (It != ValueExprMap.end()) { 7913 eraseValueFromMap(It->first); 7914 ToForget.push_back(It->second); 7915 if (PHINode *PN = dyn_cast<PHINode>(I)) 7916 ConstantEvolutionLoopExitValue.erase(PN); 7917 } 7918 7919 PushDefUseChildren(I, Worklist, Visited); 7920 } 7921 forgetMemoizedResults(ToForget); 7922 } 7923 7924 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7925 LoopDispositions.clear(); 7926 } 7927 7928 /// Get the exact loop backedge taken count considering all loop exits. A 7929 /// computable result can only be returned for loops with all exiting blocks 7930 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7931 /// is never skipped. This is a valid assumption as long as the loop exits via 7932 /// that test. For precise results, it is the caller's responsibility to specify 7933 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7934 const SCEV * 7935 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7936 SCEVUnionPredicate *Preds) const { 7937 // If any exits were not computable, the loop is not computable. 7938 if (!isComplete() || ExitNotTaken.empty()) 7939 return SE->getCouldNotCompute(); 7940 7941 const BasicBlock *Latch = L->getLoopLatch(); 7942 // All exiting blocks we have collected must dominate the only backedge. 7943 if (!Latch) 7944 return SE->getCouldNotCompute(); 7945 7946 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7947 // count is simply a minimum out of all these calculated exit counts. 7948 SmallVector<const SCEV *, 2> Ops; 7949 for (auto &ENT : ExitNotTaken) { 7950 const SCEV *BECount = ENT.ExactNotTaken; 7951 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7952 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7953 "We should only have known counts for exiting blocks that dominate " 7954 "latch!"); 7955 7956 Ops.push_back(BECount); 7957 7958 if (Preds && !ENT.hasAlwaysTruePredicate()) 7959 Preds->add(ENT.Predicate.get()); 7960 7961 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7962 "Predicate should be always true!"); 7963 } 7964 7965 return SE->getUMinFromMismatchedTypes(Ops); 7966 } 7967 7968 /// Get the exact not taken count for this loop exit. 7969 const SCEV * 7970 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7971 ScalarEvolution *SE) const { 7972 for (auto &ENT : ExitNotTaken) 7973 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7974 return ENT.ExactNotTaken; 7975 7976 return SE->getCouldNotCompute(); 7977 } 7978 7979 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7980 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7981 for (auto &ENT : ExitNotTaken) 7982 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7983 return ENT.MaxNotTaken; 7984 7985 return SE->getCouldNotCompute(); 7986 } 7987 7988 /// getConstantMax - Get the constant max backedge taken count for the loop. 7989 const SCEV * 7990 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7991 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7992 return !ENT.hasAlwaysTruePredicate(); 7993 }; 7994 7995 if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue)) 7996 return SE->getCouldNotCompute(); 7997 7998 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7999 isa<SCEVConstant>(getConstantMax())) && 8000 "No point in having a non-constant max backedge taken count!"); 8001 return getConstantMax(); 8002 } 8003 8004 const SCEV * 8005 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 8006 ScalarEvolution *SE) { 8007 if (!SymbolicMax) 8008 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 8009 return SymbolicMax; 8010 } 8011 8012 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 8013 ScalarEvolution *SE) const { 8014 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 8015 return !ENT.hasAlwaysTruePredicate(); 8016 }; 8017 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 8018 } 8019 8020 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 8021 : ExitLimit(E, E, false, None) { 8022 } 8023 8024 ScalarEvolution::ExitLimit::ExitLimit( 8025 const SCEV *E, const SCEV *M, bool MaxOrZero, 8026 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 8027 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 8028 // If we prove the max count is zero, so is the symbolic bound. This happens 8029 // in practice due to differences in a) how context sensitive we've chosen 8030 // to be and b) how we reason about bounds impied by UB. 8031 if (MaxNotTaken->isZero()) 8032 ExactNotTaken = MaxNotTaken; 8033 8034 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 8035 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 8036 "Exact is not allowed to be less precise than Max"); 8037 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 8038 isa<SCEVConstant>(MaxNotTaken)) && 8039 "No point in having a non-constant max backedge taken count!"); 8040 for (auto *PredSet : PredSetList) 8041 for (auto *P : *PredSet) 8042 addPredicate(P); 8043 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) && 8044 "Backedge count should be int"); 8045 assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) && 8046 "Max backedge count should be int"); 8047 } 8048 8049 ScalarEvolution::ExitLimit::ExitLimit( 8050 const SCEV *E, const SCEV *M, bool MaxOrZero, 8051 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 8052 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 8053 } 8054 8055 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 8056 bool MaxOrZero) 8057 : ExitLimit(E, M, MaxOrZero, None) { 8058 } 8059 8060 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 8061 /// computable exit into a persistent ExitNotTakenInfo array. 8062 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 8063 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 8064 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 8065 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 8066 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 8067 8068 ExitNotTaken.reserve(ExitCounts.size()); 8069 std::transform( 8070 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 8071 [&](const EdgeExitInfo &EEI) { 8072 BasicBlock *ExitBB = EEI.first; 8073 const ExitLimit &EL = EEI.second; 8074 if (EL.Predicates.empty()) 8075 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 8076 nullptr); 8077 8078 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 8079 for (auto *Pred : EL.Predicates) 8080 Predicate->add(Pred); 8081 8082 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 8083 std::move(Predicate)); 8084 }); 8085 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 8086 isa<SCEVConstant>(ConstantMax)) && 8087 "No point in having a non-constant max backedge taken count!"); 8088 } 8089 8090 /// Compute the number of times the backedge of the specified loop will execute. 8091 ScalarEvolution::BackedgeTakenInfo 8092 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 8093 bool AllowPredicates) { 8094 SmallVector<BasicBlock *, 8> ExitingBlocks; 8095 L->getExitingBlocks(ExitingBlocks); 8096 8097 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 8098 8099 SmallVector<EdgeExitInfo, 4> ExitCounts; 8100 bool CouldComputeBECount = true; 8101 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 8102 const SCEV *MustExitMaxBECount = nullptr; 8103 const SCEV *MayExitMaxBECount = nullptr; 8104 bool MustExitMaxOrZero = false; 8105 8106 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 8107 // and compute maxBECount. 8108 // Do a union of all the predicates here. 8109 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 8110 BasicBlock *ExitBB = ExitingBlocks[i]; 8111 8112 // We canonicalize untaken exits to br (constant), ignore them so that 8113 // proving an exit untaken doesn't negatively impact our ability to reason 8114 // about the loop as whole. 8115 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 8116 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 8117 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 8118 if (ExitIfTrue == CI->isZero()) 8119 continue; 8120 } 8121 8122 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 8123 8124 assert((AllowPredicates || EL.Predicates.empty()) && 8125 "Predicated exit limit when predicates are not allowed!"); 8126 8127 // 1. For each exit that can be computed, add an entry to ExitCounts. 8128 // CouldComputeBECount is true only if all exits can be computed. 8129 if (EL.ExactNotTaken == getCouldNotCompute()) 8130 // We couldn't compute an exact value for this exit, so 8131 // we won't be able to compute an exact value for the loop. 8132 CouldComputeBECount = false; 8133 else 8134 ExitCounts.emplace_back(ExitBB, EL); 8135 8136 // 2. Derive the loop's MaxBECount from each exit's max number of 8137 // non-exiting iterations. Partition the loop exits into two kinds: 8138 // LoopMustExits and LoopMayExits. 8139 // 8140 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 8141 // is a LoopMayExit. If any computable LoopMustExit is found, then 8142 // MaxBECount is the minimum EL.MaxNotTaken of computable 8143 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 8144 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 8145 // computable EL.MaxNotTaken. 8146 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 8147 DT.dominates(ExitBB, Latch)) { 8148 if (!MustExitMaxBECount) { 8149 MustExitMaxBECount = EL.MaxNotTaken; 8150 MustExitMaxOrZero = EL.MaxOrZero; 8151 } else { 8152 MustExitMaxBECount = 8153 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 8154 } 8155 } else if (MayExitMaxBECount != getCouldNotCompute()) { 8156 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 8157 MayExitMaxBECount = EL.MaxNotTaken; 8158 else { 8159 MayExitMaxBECount = 8160 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 8161 } 8162 } 8163 } 8164 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 8165 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 8166 // The loop backedge will be taken the maximum or zero times if there's 8167 // a single exit that must be taken the maximum or zero times. 8168 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 8169 8170 // Remember which SCEVs are used in exit limits for invalidation purposes. 8171 // We only care about non-constant SCEVs here, so we can ignore EL.MaxNotTaken 8172 // and MaxBECount, which must be SCEVConstant. 8173 for (const auto &Pair : ExitCounts) 8174 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken)) 8175 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates}); 8176 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 8177 MaxBECount, MaxOrZero); 8178 } 8179 8180 ScalarEvolution::ExitLimit 8181 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 8182 bool AllowPredicates) { 8183 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 8184 // If our exiting block does not dominate the latch, then its connection with 8185 // loop's exit limit may be far from trivial. 8186 const BasicBlock *Latch = L->getLoopLatch(); 8187 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 8188 return getCouldNotCompute(); 8189 8190 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 8191 Instruction *Term = ExitingBlock->getTerminator(); 8192 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 8193 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 8194 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 8195 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 8196 "It should have one successor in loop and one exit block!"); 8197 // Proceed to the next level to examine the exit condition expression. 8198 return computeExitLimitFromCond( 8199 L, BI->getCondition(), ExitIfTrue, 8200 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 8201 } 8202 8203 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 8204 // For switch, make sure that there is a single exit from the loop. 8205 BasicBlock *Exit = nullptr; 8206 for (auto *SBB : successors(ExitingBlock)) 8207 if (!L->contains(SBB)) { 8208 if (Exit) // Multiple exit successors. 8209 return getCouldNotCompute(); 8210 Exit = SBB; 8211 } 8212 assert(Exit && "Exiting block must have at least one exit"); 8213 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 8214 /*ControlsExit=*/IsOnlyExit); 8215 } 8216 8217 return getCouldNotCompute(); 8218 } 8219 8220 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 8221 const Loop *L, Value *ExitCond, bool ExitIfTrue, 8222 bool ControlsExit, bool AllowPredicates) { 8223 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 8224 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 8225 ControlsExit, AllowPredicates); 8226 } 8227 8228 Optional<ScalarEvolution::ExitLimit> 8229 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 8230 bool ExitIfTrue, bool ControlsExit, 8231 bool AllowPredicates) { 8232 (void)this->L; 8233 (void)this->ExitIfTrue; 8234 (void)this->AllowPredicates; 8235 8236 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 8237 this->AllowPredicates == AllowPredicates && 8238 "Variance in assumed invariant key components!"); 8239 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 8240 if (Itr == TripCountMap.end()) 8241 return None; 8242 return Itr->second; 8243 } 8244 8245 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 8246 bool ExitIfTrue, 8247 bool ControlsExit, 8248 bool AllowPredicates, 8249 const ExitLimit &EL) { 8250 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 8251 this->AllowPredicates == AllowPredicates && 8252 "Variance in assumed invariant key components!"); 8253 8254 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 8255 assert(InsertResult.second && "Expected successful insertion!"); 8256 (void)InsertResult; 8257 (void)ExitIfTrue; 8258 } 8259 8260 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 8261 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8262 bool ControlsExit, bool AllowPredicates) { 8263 8264 if (auto MaybeEL = 8265 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 8266 return *MaybeEL; 8267 8268 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 8269 ControlsExit, AllowPredicates); 8270 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 8271 return EL; 8272 } 8273 8274 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 8275 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8276 bool ControlsExit, bool AllowPredicates) { 8277 // Handle BinOp conditions (And, Or). 8278 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 8279 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 8280 return *LimitFromBinOp; 8281 8282 // With an icmp, it may be feasible to compute an exact backedge-taken count. 8283 // Proceed to the next level to examine the icmp. 8284 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 8285 ExitLimit EL = 8286 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 8287 if (EL.hasFullInfo() || !AllowPredicates) 8288 return EL; 8289 8290 // Try again, but use SCEV predicates this time. 8291 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 8292 /*AllowPredicates=*/true); 8293 } 8294 8295 // Check for a constant condition. These are normally stripped out by 8296 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 8297 // preserve the CFG and is temporarily leaving constant conditions 8298 // in place. 8299 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 8300 if (ExitIfTrue == !CI->getZExtValue()) 8301 // The backedge is always taken. 8302 return getCouldNotCompute(); 8303 else 8304 // The backedge is never taken. 8305 return getZero(CI->getType()); 8306 } 8307 8308 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic 8309 // with a constant step, we can form an equivalent icmp predicate and figure 8310 // out how many iterations will be taken before we exit. 8311 const WithOverflowInst *WO; 8312 const APInt *C; 8313 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) && 8314 match(WO->getRHS(), m_APInt(C))) { 8315 ConstantRange NWR = 8316 ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C, 8317 WO->getNoWrapKind()); 8318 CmpInst::Predicate Pred; 8319 APInt NewRHSC, Offset; 8320 NWR.getEquivalentICmp(Pred, NewRHSC, Offset); 8321 if (!ExitIfTrue) 8322 Pred = ICmpInst::getInversePredicate(Pred); 8323 auto *LHS = getSCEV(WO->getLHS()); 8324 if (Offset != 0) 8325 LHS = getAddExpr(LHS, getConstant(Offset)); 8326 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC), 8327 ControlsExit, AllowPredicates); 8328 if (EL.hasAnyInfo()) return EL; 8329 } 8330 8331 // If it's not an integer or pointer comparison then compute it the hard way. 8332 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8333 } 8334 8335 Optional<ScalarEvolution::ExitLimit> 8336 ScalarEvolution::computeExitLimitFromCondFromBinOp( 8337 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8338 bool ControlsExit, bool AllowPredicates) { 8339 // Check if the controlling expression for this loop is an And or Or. 8340 Value *Op0, *Op1; 8341 bool IsAnd = false; 8342 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 8343 IsAnd = true; 8344 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 8345 IsAnd = false; 8346 else 8347 return None; 8348 8349 // EitherMayExit is true in these two cases: 8350 // br (and Op0 Op1), loop, exit 8351 // br (or Op0 Op1), exit, loop 8352 bool EitherMayExit = IsAnd ^ ExitIfTrue; 8353 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 8354 ControlsExit && !EitherMayExit, 8355 AllowPredicates); 8356 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 8357 ControlsExit && !EitherMayExit, 8358 AllowPredicates); 8359 8360 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 8361 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 8362 if (isa<ConstantInt>(Op1)) 8363 return Op1 == NeutralElement ? EL0 : EL1; 8364 if (isa<ConstantInt>(Op0)) 8365 return Op0 == NeutralElement ? EL1 : EL0; 8366 8367 const SCEV *BECount = getCouldNotCompute(); 8368 const SCEV *MaxBECount = getCouldNotCompute(); 8369 if (EitherMayExit) { 8370 // Both conditions must be same for the loop to continue executing. 8371 // Choose the less conservative count. 8372 if (EL0.ExactNotTaken != getCouldNotCompute() && 8373 EL1.ExactNotTaken != getCouldNotCompute()) { 8374 BECount = getUMinFromMismatchedTypes( 8375 EL0.ExactNotTaken, EL1.ExactNotTaken, 8376 /*Sequential=*/!isa<BinaryOperator>(ExitCond)); 8377 8378 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 8379 // it should have been simplified to zero (see the condition (3) above) 8380 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 8381 BECount->isZero()); 8382 } 8383 if (EL0.MaxNotTaken == getCouldNotCompute()) 8384 MaxBECount = EL1.MaxNotTaken; 8385 else if (EL1.MaxNotTaken == getCouldNotCompute()) 8386 MaxBECount = EL0.MaxNotTaken; 8387 else 8388 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 8389 } else { 8390 // Both conditions must be same at the same time for the loop to exit. 8391 // For now, be conservative. 8392 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 8393 BECount = EL0.ExactNotTaken; 8394 } 8395 8396 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 8397 // to be more aggressive when computing BECount than when computing 8398 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 8399 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 8400 // to not. 8401 if (isa<SCEVCouldNotCompute>(MaxBECount) && 8402 !isa<SCEVCouldNotCompute>(BECount)) 8403 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 8404 8405 return ExitLimit(BECount, MaxBECount, false, 8406 { &EL0.Predicates, &EL1.Predicates }); 8407 } 8408 8409 ScalarEvolution::ExitLimit 8410 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8411 ICmpInst *ExitCond, 8412 bool ExitIfTrue, 8413 bool ControlsExit, 8414 bool AllowPredicates) { 8415 // If the condition was exit on true, convert the condition to exit on false 8416 ICmpInst::Predicate Pred; 8417 if (!ExitIfTrue) 8418 Pred = ExitCond->getPredicate(); 8419 else 8420 Pred = ExitCond->getInversePredicate(); 8421 const ICmpInst::Predicate OriginalPred = Pred; 8422 8423 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 8424 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 8425 8426 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsExit, 8427 AllowPredicates); 8428 if (EL.hasAnyInfo()) return EL; 8429 8430 auto *ExhaustiveCount = 8431 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8432 8433 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 8434 return ExhaustiveCount; 8435 8436 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 8437 ExitCond->getOperand(1), L, OriginalPred); 8438 } 8439 ScalarEvolution::ExitLimit 8440 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8441 ICmpInst::Predicate Pred, 8442 const SCEV *LHS, const SCEV *RHS, 8443 bool ControlsExit, 8444 bool AllowPredicates) { 8445 8446 // Try to evaluate any dependencies out of the loop. 8447 LHS = getSCEVAtScope(LHS, L); 8448 RHS = getSCEVAtScope(RHS, L); 8449 8450 // At this point, we would like to compute how many iterations of the 8451 // loop the predicate will return true for these inputs. 8452 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 8453 // If there is a loop-invariant, force it into the RHS. 8454 std::swap(LHS, RHS); 8455 Pred = ICmpInst::getSwappedPredicate(Pred); 8456 } 8457 8458 // Simplify the operands before analyzing them. 8459 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8460 8461 // If we have a comparison of a chrec against a constant, try to use value 8462 // ranges to answer this query. 8463 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 8464 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 8465 if (AddRec->getLoop() == L) { 8466 // Form the constant range. 8467 ConstantRange CompRange = 8468 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 8469 8470 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 8471 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 8472 } 8473 8474 // If this loop must exit based on this condition (or execute undefined 8475 // behaviour), and we can prove the test sequence produced must repeat 8476 // the same values on self-wrap of the IV, then we can infer that IV 8477 // doesn't self wrap because if it did, we'd have an infinite (undefined) 8478 // loop. 8479 if (ControlsExit && isLoopInvariant(RHS, L) && loopHasNoAbnormalExits(L) && 8480 loopIsFiniteByAssumption(L)) { 8481 8482 // TODO: We can peel off any functions which are invertible *in L*. Loop 8483 // invariant terms are effectively constants for our purposes here. 8484 auto *InnerLHS = LHS; 8485 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) 8486 InnerLHS = ZExt->getOperand(); 8487 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) { 8488 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 8489 if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() && 8490 StrideC && StrideC->getAPInt().isPowerOf2()) { 8491 auto Flags = AR->getNoWrapFlags(); 8492 Flags = setFlags(Flags, SCEV::FlagNW); 8493 SmallVector<const SCEV*> Operands{AR->operands()}; 8494 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 8495 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 8496 } 8497 } 8498 } 8499 8500 switch (Pred) { 8501 case ICmpInst::ICMP_NE: { // while (X != Y) 8502 // Convert to: while (X-Y != 0) 8503 if (LHS->getType()->isPointerTy()) { 8504 LHS = getLosslessPtrToIntExpr(LHS); 8505 if (isa<SCEVCouldNotCompute>(LHS)) 8506 return LHS; 8507 } 8508 if (RHS->getType()->isPointerTy()) { 8509 RHS = getLosslessPtrToIntExpr(RHS); 8510 if (isa<SCEVCouldNotCompute>(RHS)) 8511 return RHS; 8512 } 8513 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 8514 AllowPredicates); 8515 if (EL.hasAnyInfo()) return EL; 8516 break; 8517 } 8518 case ICmpInst::ICMP_EQ: { // while (X == Y) 8519 // Convert to: while (X-Y == 0) 8520 if (LHS->getType()->isPointerTy()) { 8521 LHS = getLosslessPtrToIntExpr(LHS); 8522 if (isa<SCEVCouldNotCompute>(LHS)) 8523 return LHS; 8524 } 8525 if (RHS->getType()->isPointerTy()) { 8526 RHS = getLosslessPtrToIntExpr(RHS); 8527 if (isa<SCEVCouldNotCompute>(RHS)) 8528 return RHS; 8529 } 8530 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 8531 if (EL.hasAnyInfo()) return EL; 8532 break; 8533 } 8534 case ICmpInst::ICMP_SLT: 8535 case ICmpInst::ICMP_ULT: { // while (X < Y) 8536 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 8537 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 8538 AllowPredicates); 8539 if (EL.hasAnyInfo()) return EL; 8540 break; 8541 } 8542 case ICmpInst::ICMP_SGT: 8543 case ICmpInst::ICMP_UGT: { // while (X > Y) 8544 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 8545 ExitLimit EL = 8546 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 8547 AllowPredicates); 8548 if (EL.hasAnyInfo()) return EL; 8549 break; 8550 } 8551 default: 8552 break; 8553 } 8554 8555 return getCouldNotCompute(); 8556 } 8557 8558 ScalarEvolution::ExitLimit 8559 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 8560 SwitchInst *Switch, 8561 BasicBlock *ExitingBlock, 8562 bool ControlsExit) { 8563 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 8564 8565 // Give up if the exit is the default dest of a switch. 8566 if (Switch->getDefaultDest() == ExitingBlock) 8567 return getCouldNotCompute(); 8568 8569 assert(L->contains(Switch->getDefaultDest()) && 8570 "Default case must not exit the loop!"); 8571 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 8572 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 8573 8574 // while (X != Y) --> while (X-Y != 0) 8575 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 8576 if (EL.hasAnyInfo()) 8577 return EL; 8578 8579 return getCouldNotCompute(); 8580 } 8581 8582 static ConstantInt * 8583 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 8584 ScalarEvolution &SE) { 8585 const SCEV *InVal = SE.getConstant(C); 8586 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 8587 assert(isa<SCEVConstant>(Val) && 8588 "Evaluation of SCEV at constant didn't fold correctly?"); 8589 return cast<SCEVConstant>(Val)->getValue(); 8590 } 8591 8592 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8593 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8594 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8595 if (!RHS) 8596 return getCouldNotCompute(); 8597 8598 const BasicBlock *Latch = L->getLoopLatch(); 8599 if (!Latch) 8600 return getCouldNotCompute(); 8601 8602 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8603 if (!Predecessor) 8604 return getCouldNotCompute(); 8605 8606 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8607 // Return LHS in OutLHS and shift_opt in OutOpCode. 8608 auto MatchPositiveShift = 8609 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8610 8611 using namespace PatternMatch; 8612 8613 ConstantInt *ShiftAmt; 8614 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8615 OutOpCode = Instruction::LShr; 8616 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8617 OutOpCode = Instruction::AShr; 8618 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8619 OutOpCode = Instruction::Shl; 8620 else 8621 return false; 8622 8623 return ShiftAmt->getValue().isStrictlyPositive(); 8624 }; 8625 8626 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8627 // 8628 // loop: 8629 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8630 // %iv.shifted = lshr i32 %iv, <positive constant> 8631 // 8632 // Return true on a successful match. Return the corresponding PHI node (%iv 8633 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8634 auto MatchShiftRecurrence = 8635 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8636 Optional<Instruction::BinaryOps> PostShiftOpCode; 8637 8638 { 8639 Instruction::BinaryOps OpC; 8640 Value *V; 8641 8642 // If we encounter a shift instruction, "peel off" the shift operation, 8643 // and remember that we did so. Later when we inspect %iv's backedge 8644 // value, we will make sure that the backedge value uses the same 8645 // operation. 8646 // 8647 // Note: the peeled shift operation does not have to be the same 8648 // instruction as the one feeding into the PHI's backedge value. We only 8649 // really care about it being the same *kind* of shift instruction -- 8650 // that's all that is required for our later inferences to hold. 8651 if (MatchPositiveShift(LHS, V, OpC)) { 8652 PostShiftOpCode = OpC; 8653 LHS = V; 8654 } 8655 } 8656 8657 PNOut = dyn_cast<PHINode>(LHS); 8658 if (!PNOut || PNOut->getParent() != L->getHeader()) 8659 return false; 8660 8661 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8662 Value *OpLHS; 8663 8664 return 8665 // The backedge value for the PHI node must be a shift by a positive 8666 // amount 8667 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8668 8669 // of the PHI node itself 8670 OpLHS == PNOut && 8671 8672 // and the kind of shift should be match the kind of shift we peeled 8673 // off, if any. 8674 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8675 }; 8676 8677 PHINode *PN; 8678 Instruction::BinaryOps OpCode; 8679 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8680 return getCouldNotCompute(); 8681 8682 const DataLayout &DL = getDataLayout(); 8683 8684 // The key rationale for this optimization is that for some kinds of shift 8685 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8686 // within a finite number of iterations. If the condition guarding the 8687 // backedge (in the sense that the backedge is taken if the condition is true) 8688 // is false for the value the shift recurrence stabilizes to, then we know 8689 // that the backedge is taken only a finite number of times. 8690 8691 ConstantInt *StableValue = nullptr; 8692 switch (OpCode) { 8693 default: 8694 llvm_unreachable("Impossible case!"); 8695 8696 case Instruction::AShr: { 8697 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8698 // bitwidth(K) iterations. 8699 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8700 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8701 Predecessor->getTerminator(), &DT); 8702 auto *Ty = cast<IntegerType>(RHS->getType()); 8703 if (Known.isNonNegative()) 8704 StableValue = ConstantInt::get(Ty, 0); 8705 else if (Known.isNegative()) 8706 StableValue = ConstantInt::get(Ty, -1, true); 8707 else 8708 return getCouldNotCompute(); 8709 8710 break; 8711 } 8712 case Instruction::LShr: 8713 case Instruction::Shl: 8714 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8715 // stabilize to 0 in at most bitwidth(K) iterations. 8716 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8717 break; 8718 } 8719 8720 auto *Result = 8721 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8722 assert(Result->getType()->isIntegerTy(1) && 8723 "Otherwise cannot be an operand to a branch instruction"); 8724 8725 if (Result->isZeroValue()) { 8726 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8727 const SCEV *UpperBound = 8728 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8729 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8730 } 8731 8732 return getCouldNotCompute(); 8733 } 8734 8735 /// Return true if we can constant fold an instruction of the specified type, 8736 /// assuming that all operands were constants. 8737 static bool CanConstantFold(const Instruction *I) { 8738 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8739 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8740 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8741 return true; 8742 8743 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8744 if (const Function *F = CI->getCalledFunction()) 8745 return canConstantFoldCallTo(CI, F); 8746 return false; 8747 } 8748 8749 /// Determine whether this instruction can constant evolve within this loop 8750 /// assuming its operands can all constant evolve. 8751 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8752 // An instruction outside of the loop can't be derived from a loop PHI. 8753 if (!L->contains(I)) return false; 8754 8755 if (isa<PHINode>(I)) { 8756 // We don't currently keep track of the control flow needed to evaluate 8757 // PHIs, so we cannot handle PHIs inside of loops. 8758 return L->getHeader() == I->getParent(); 8759 } 8760 8761 // If we won't be able to constant fold this expression even if the operands 8762 // are constants, bail early. 8763 return CanConstantFold(I); 8764 } 8765 8766 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8767 /// recursing through each instruction operand until reaching a loop header phi. 8768 static PHINode * 8769 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8770 DenseMap<Instruction *, PHINode *> &PHIMap, 8771 unsigned Depth) { 8772 if (Depth > MaxConstantEvolvingDepth) 8773 return nullptr; 8774 8775 // Otherwise, we can evaluate this instruction if all of its operands are 8776 // constant or derived from a PHI node themselves. 8777 PHINode *PHI = nullptr; 8778 for (Value *Op : UseInst->operands()) { 8779 if (isa<Constant>(Op)) continue; 8780 8781 Instruction *OpInst = dyn_cast<Instruction>(Op); 8782 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8783 8784 PHINode *P = dyn_cast<PHINode>(OpInst); 8785 if (!P) 8786 // If this operand is already visited, reuse the prior result. 8787 // We may have P != PHI if this is the deepest point at which the 8788 // inconsistent paths meet. 8789 P = PHIMap.lookup(OpInst); 8790 if (!P) { 8791 // Recurse and memoize the results, whether a phi is found or not. 8792 // This recursive call invalidates pointers into PHIMap. 8793 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8794 PHIMap[OpInst] = P; 8795 } 8796 if (!P) 8797 return nullptr; // Not evolving from PHI 8798 if (PHI && PHI != P) 8799 return nullptr; // Evolving from multiple different PHIs. 8800 PHI = P; 8801 } 8802 // This is a expression evolving from a constant PHI! 8803 return PHI; 8804 } 8805 8806 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8807 /// in the loop that V is derived from. We allow arbitrary operations along the 8808 /// way, but the operands of an operation must either be constants or a value 8809 /// derived from a constant PHI. If this expression does not fit with these 8810 /// constraints, return null. 8811 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8812 Instruction *I = dyn_cast<Instruction>(V); 8813 if (!I || !canConstantEvolve(I, L)) return nullptr; 8814 8815 if (PHINode *PN = dyn_cast<PHINode>(I)) 8816 return PN; 8817 8818 // Record non-constant instructions contained by the loop. 8819 DenseMap<Instruction *, PHINode *> PHIMap; 8820 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8821 } 8822 8823 /// EvaluateExpression - Given an expression that passes the 8824 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8825 /// in the loop has the value PHIVal. If we can't fold this expression for some 8826 /// reason, return null. 8827 static Constant *EvaluateExpression(Value *V, const Loop *L, 8828 DenseMap<Instruction *, Constant *> &Vals, 8829 const DataLayout &DL, 8830 const TargetLibraryInfo *TLI) { 8831 // Convenient constant check, but redundant for recursive calls. 8832 if (Constant *C = dyn_cast<Constant>(V)) return C; 8833 Instruction *I = dyn_cast<Instruction>(V); 8834 if (!I) return nullptr; 8835 8836 if (Constant *C = Vals.lookup(I)) return C; 8837 8838 // An instruction inside the loop depends on a value outside the loop that we 8839 // weren't given a mapping for, or a value such as a call inside the loop. 8840 if (!canConstantEvolve(I, L)) return nullptr; 8841 8842 // An unmapped PHI can be due to a branch or another loop inside this loop, 8843 // or due to this not being the initial iteration through a loop where we 8844 // couldn't compute the evolution of this particular PHI last time. 8845 if (isa<PHINode>(I)) return nullptr; 8846 8847 std::vector<Constant*> Operands(I->getNumOperands()); 8848 8849 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8850 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8851 if (!Operand) { 8852 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8853 if (!Operands[i]) return nullptr; 8854 continue; 8855 } 8856 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8857 Vals[Operand] = C; 8858 if (!C) return nullptr; 8859 Operands[i] = C; 8860 } 8861 8862 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8863 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8864 Operands[1], DL, TLI); 8865 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8866 if (!LI->isVolatile()) 8867 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8868 } 8869 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8870 } 8871 8872 8873 // If every incoming value to PN except the one for BB is a specific Constant, 8874 // return that, else return nullptr. 8875 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8876 Constant *IncomingVal = nullptr; 8877 8878 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8879 if (PN->getIncomingBlock(i) == BB) 8880 continue; 8881 8882 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8883 if (!CurrentVal) 8884 return nullptr; 8885 8886 if (IncomingVal != CurrentVal) { 8887 if (IncomingVal) 8888 return nullptr; 8889 IncomingVal = CurrentVal; 8890 } 8891 } 8892 8893 return IncomingVal; 8894 } 8895 8896 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8897 /// in the header of its containing loop, we know the loop executes a 8898 /// constant number of times, and the PHI node is just a recurrence 8899 /// involving constants, fold it. 8900 Constant * 8901 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8902 const APInt &BEs, 8903 const Loop *L) { 8904 auto I = ConstantEvolutionLoopExitValue.find(PN); 8905 if (I != ConstantEvolutionLoopExitValue.end()) 8906 return I->second; 8907 8908 if (BEs.ugt(MaxBruteForceIterations)) 8909 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8910 8911 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8912 8913 DenseMap<Instruction *, Constant *> CurrentIterVals; 8914 BasicBlock *Header = L->getHeader(); 8915 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8916 8917 BasicBlock *Latch = L->getLoopLatch(); 8918 if (!Latch) 8919 return nullptr; 8920 8921 for (PHINode &PHI : Header->phis()) { 8922 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8923 CurrentIterVals[&PHI] = StartCST; 8924 } 8925 if (!CurrentIterVals.count(PN)) 8926 return RetVal = nullptr; 8927 8928 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8929 8930 // Execute the loop symbolically to determine the exit value. 8931 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8932 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8933 8934 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8935 unsigned IterationNum = 0; 8936 const DataLayout &DL = getDataLayout(); 8937 for (; ; ++IterationNum) { 8938 if (IterationNum == NumIterations) 8939 return RetVal = CurrentIterVals[PN]; // Got exit value! 8940 8941 // Compute the value of the PHIs for the next iteration. 8942 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8943 DenseMap<Instruction *, Constant *> NextIterVals; 8944 Constant *NextPHI = 8945 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8946 if (!NextPHI) 8947 return nullptr; // Couldn't evaluate! 8948 NextIterVals[PN] = NextPHI; 8949 8950 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8951 8952 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8953 // cease to be able to evaluate one of them or if they stop evolving, 8954 // because that doesn't necessarily prevent us from computing PN. 8955 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8956 for (const auto &I : CurrentIterVals) { 8957 PHINode *PHI = dyn_cast<PHINode>(I.first); 8958 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8959 PHIsToCompute.emplace_back(PHI, I.second); 8960 } 8961 // We use two distinct loops because EvaluateExpression may invalidate any 8962 // iterators into CurrentIterVals. 8963 for (const auto &I : PHIsToCompute) { 8964 PHINode *PHI = I.first; 8965 Constant *&NextPHI = NextIterVals[PHI]; 8966 if (!NextPHI) { // Not already computed. 8967 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8968 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8969 } 8970 if (NextPHI != I.second) 8971 StoppedEvolving = false; 8972 } 8973 8974 // If all entries in CurrentIterVals == NextIterVals then we can stop 8975 // iterating, the loop can't continue to change. 8976 if (StoppedEvolving) 8977 return RetVal = CurrentIterVals[PN]; 8978 8979 CurrentIterVals.swap(NextIterVals); 8980 } 8981 } 8982 8983 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8984 Value *Cond, 8985 bool ExitWhen) { 8986 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8987 if (!PN) return getCouldNotCompute(); 8988 8989 // If the loop is canonicalized, the PHI will have exactly two entries. 8990 // That's the only form we support here. 8991 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8992 8993 DenseMap<Instruction *, Constant *> CurrentIterVals; 8994 BasicBlock *Header = L->getHeader(); 8995 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8996 8997 BasicBlock *Latch = L->getLoopLatch(); 8998 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8999 9000 for (PHINode &PHI : Header->phis()) { 9001 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 9002 CurrentIterVals[&PHI] = StartCST; 9003 } 9004 if (!CurrentIterVals.count(PN)) 9005 return getCouldNotCompute(); 9006 9007 // Okay, we find a PHI node that defines the trip count of this loop. Execute 9008 // the loop symbolically to determine when the condition gets a value of 9009 // "ExitWhen". 9010 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 9011 const DataLayout &DL = getDataLayout(); 9012 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 9013 auto *CondVal = dyn_cast_or_null<ConstantInt>( 9014 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 9015 9016 // Couldn't symbolically evaluate. 9017 if (!CondVal) return getCouldNotCompute(); 9018 9019 if (CondVal->getValue() == uint64_t(ExitWhen)) { 9020 ++NumBruteForceTripCountsComputed; 9021 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 9022 } 9023 9024 // Update all the PHI nodes for the next iteration. 9025 DenseMap<Instruction *, Constant *> NextIterVals; 9026 9027 // Create a list of which PHIs we need to compute. We want to do this before 9028 // calling EvaluateExpression on them because that may invalidate iterators 9029 // into CurrentIterVals. 9030 SmallVector<PHINode *, 8> PHIsToCompute; 9031 for (const auto &I : CurrentIterVals) { 9032 PHINode *PHI = dyn_cast<PHINode>(I.first); 9033 if (!PHI || PHI->getParent() != Header) continue; 9034 PHIsToCompute.push_back(PHI); 9035 } 9036 for (PHINode *PHI : PHIsToCompute) { 9037 Constant *&NextPHI = NextIterVals[PHI]; 9038 if (NextPHI) continue; // Already computed! 9039 9040 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 9041 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 9042 } 9043 CurrentIterVals.swap(NextIterVals); 9044 } 9045 9046 // Too many iterations were needed to evaluate. 9047 return getCouldNotCompute(); 9048 } 9049 9050 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 9051 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 9052 ValuesAtScopes[V]; 9053 // Check to see if we've folded this expression at this loop before. 9054 for (auto &LS : Values) 9055 if (LS.first == L) 9056 return LS.second ? LS.second : V; 9057 9058 Values.emplace_back(L, nullptr); 9059 9060 // Otherwise compute it. 9061 const SCEV *C = computeSCEVAtScope(V, L); 9062 for (auto &LS : reverse(ValuesAtScopes[V])) 9063 if (LS.first == L) { 9064 LS.second = C; 9065 if (!isa<SCEVConstant>(C)) 9066 ValuesAtScopesUsers[C].push_back({L, V}); 9067 break; 9068 } 9069 return C; 9070 } 9071 9072 /// This builds up a Constant using the ConstantExpr interface. That way, we 9073 /// will return Constants for objects which aren't represented by a 9074 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 9075 /// Returns NULL if the SCEV isn't representable as a Constant. 9076 static Constant *BuildConstantFromSCEV(const SCEV *V) { 9077 switch (V->getSCEVType()) { 9078 case scCouldNotCompute: 9079 case scAddRecExpr: 9080 return nullptr; 9081 case scConstant: 9082 return cast<SCEVConstant>(V)->getValue(); 9083 case scUnknown: 9084 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 9085 case scSignExtend: { 9086 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 9087 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 9088 return ConstantExpr::getSExt(CastOp, SS->getType()); 9089 return nullptr; 9090 } 9091 case scZeroExtend: { 9092 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 9093 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 9094 return ConstantExpr::getZExt(CastOp, SZ->getType()); 9095 return nullptr; 9096 } 9097 case scPtrToInt: { 9098 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 9099 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 9100 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 9101 9102 return nullptr; 9103 } 9104 case scTruncate: { 9105 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 9106 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 9107 return ConstantExpr::getTrunc(CastOp, ST->getType()); 9108 return nullptr; 9109 } 9110 case scAddExpr: { 9111 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 9112 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 9113 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 9114 unsigned AS = PTy->getAddressSpace(); 9115 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 9116 C = ConstantExpr::getBitCast(C, DestPtrTy); 9117 } 9118 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 9119 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 9120 if (!C2) 9121 return nullptr; 9122 9123 // First pointer! 9124 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 9125 unsigned AS = C2->getType()->getPointerAddressSpace(); 9126 std::swap(C, C2); 9127 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 9128 // The offsets have been converted to bytes. We can add bytes to an 9129 // i8* by GEP with the byte count in the first index. 9130 C = ConstantExpr::getBitCast(C, DestPtrTy); 9131 } 9132 9133 // Don't bother trying to sum two pointers. We probably can't 9134 // statically compute a load that results from it anyway. 9135 if (C2->getType()->isPointerTy()) 9136 return nullptr; 9137 9138 if (C->getType()->isPointerTy()) { 9139 C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()), 9140 C, C2); 9141 } else { 9142 C = ConstantExpr::getAdd(C, C2); 9143 } 9144 } 9145 return C; 9146 } 9147 return nullptr; 9148 } 9149 case scMulExpr: { 9150 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 9151 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 9152 // Don't bother with pointers at all. 9153 if (C->getType()->isPointerTy()) 9154 return nullptr; 9155 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 9156 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 9157 if (!C2 || C2->getType()->isPointerTy()) 9158 return nullptr; 9159 C = ConstantExpr::getMul(C, C2); 9160 } 9161 return C; 9162 } 9163 return nullptr; 9164 } 9165 case scUDivExpr: { 9166 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 9167 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 9168 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 9169 if (LHS->getType() == RHS->getType()) 9170 return ConstantExpr::getUDiv(LHS, RHS); 9171 return nullptr; 9172 } 9173 case scSMaxExpr: 9174 case scUMaxExpr: 9175 case scSMinExpr: 9176 case scUMinExpr: 9177 case scSequentialUMinExpr: 9178 return nullptr; // TODO: smax, umax, smin, umax, umin_seq. 9179 } 9180 llvm_unreachable("Unknown SCEV kind!"); 9181 } 9182 9183 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 9184 if (isa<SCEVConstant>(V)) return V; 9185 9186 // If this instruction is evolved from a constant-evolving PHI, compute the 9187 // exit value from the loop without using SCEVs. 9188 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 9189 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 9190 if (PHINode *PN = dyn_cast<PHINode>(I)) { 9191 const Loop *CurrLoop = this->LI[I->getParent()]; 9192 // Looking for loop exit value. 9193 if (CurrLoop && CurrLoop->getParentLoop() == L && 9194 PN->getParent() == CurrLoop->getHeader()) { 9195 // Okay, there is no closed form solution for the PHI node. Check 9196 // to see if the loop that contains it has a known backedge-taken 9197 // count. If so, we may be able to force computation of the exit 9198 // value. 9199 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 9200 // This trivial case can show up in some degenerate cases where 9201 // the incoming IR has not yet been fully simplified. 9202 if (BackedgeTakenCount->isZero()) { 9203 Value *InitValue = nullptr; 9204 bool MultipleInitValues = false; 9205 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 9206 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 9207 if (!InitValue) 9208 InitValue = PN->getIncomingValue(i); 9209 else if (InitValue != PN->getIncomingValue(i)) { 9210 MultipleInitValues = true; 9211 break; 9212 } 9213 } 9214 } 9215 if (!MultipleInitValues && InitValue) 9216 return getSCEV(InitValue); 9217 } 9218 // Do we have a loop invariant value flowing around the backedge 9219 // for a loop which must execute the backedge? 9220 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 9221 isKnownPositive(BackedgeTakenCount) && 9222 PN->getNumIncomingValues() == 2) { 9223 9224 unsigned InLoopPred = 9225 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 9226 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 9227 if (CurrLoop->isLoopInvariant(BackedgeVal)) 9228 return getSCEV(BackedgeVal); 9229 } 9230 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 9231 // Okay, we know how many times the containing loop executes. If 9232 // this is a constant evolving PHI node, get the final value at 9233 // the specified iteration number. 9234 Constant *RV = getConstantEvolutionLoopExitValue( 9235 PN, BTCC->getAPInt(), CurrLoop); 9236 if (RV) return getSCEV(RV); 9237 } 9238 } 9239 9240 // If there is a single-input Phi, evaluate it at our scope. If we can 9241 // prove that this replacement does not break LCSSA form, use new value. 9242 if (PN->getNumOperands() == 1) { 9243 const SCEV *Input = getSCEV(PN->getOperand(0)); 9244 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 9245 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 9246 // for the simplest case just support constants. 9247 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 9248 } 9249 } 9250 9251 // Okay, this is an expression that we cannot symbolically evaluate 9252 // into a SCEV. Check to see if it's possible to symbolically evaluate 9253 // the arguments into constants, and if so, try to constant propagate the 9254 // result. This is particularly useful for computing loop exit values. 9255 if (CanConstantFold(I)) { 9256 SmallVector<Constant *, 4> Operands; 9257 bool MadeImprovement = false; 9258 for (Value *Op : I->operands()) { 9259 if (Constant *C = dyn_cast<Constant>(Op)) { 9260 Operands.push_back(C); 9261 continue; 9262 } 9263 9264 // If any of the operands is non-constant and if they are 9265 // non-integer and non-pointer, don't even try to analyze them 9266 // with scev techniques. 9267 if (!isSCEVable(Op->getType())) 9268 return V; 9269 9270 const SCEV *OrigV = getSCEV(Op); 9271 const SCEV *OpV = getSCEVAtScope(OrigV, L); 9272 MadeImprovement |= OrigV != OpV; 9273 9274 Constant *C = BuildConstantFromSCEV(OpV); 9275 if (!C) return V; 9276 if (C->getType() != Op->getType()) 9277 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 9278 Op->getType(), 9279 false), 9280 C, Op->getType()); 9281 Operands.push_back(C); 9282 } 9283 9284 // Check to see if getSCEVAtScope actually made an improvement. 9285 if (MadeImprovement) { 9286 Constant *C = nullptr; 9287 const DataLayout &DL = getDataLayout(); 9288 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 9289 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 9290 Operands[1], DL, &TLI); 9291 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 9292 if (!Load->isVolatile()) 9293 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 9294 DL); 9295 } else 9296 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 9297 if (!C) return V; 9298 return getSCEV(C); 9299 } 9300 } 9301 } 9302 9303 // This is some other type of SCEVUnknown, just return it. 9304 return V; 9305 } 9306 9307 if (isa<SCEVCommutativeExpr>(V) || isa<SCEVSequentialMinMaxExpr>(V)) { 9308 const auto *Comm = cast<SCEVNAryExpr>(V); 9309 // Avoid performing the look-up in the common case where the specified 9310 // expression has no loop-variant portions. 9311 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 9312 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 9313 if (OpAtScope != Comm->getOperand(i)) { 9314 // Okay, at least one of these operands is loop variant but might be 9315 // foldable. Build a new instance of the folded commutative expression. 9316 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 9317 Comm->op_begin()+i); 9318 NewOps.push_back(OpAtScope); 9319 9320 for (++i; i != e; ++i) { 9321 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 9322 NewOps.push_back(OpAtScope); 9323 } 9324 if (isa<SCEVAddExpr>(Comm)) 9325 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 9326 if (isa<SCEVMulExpr>(Comm)) 9327 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 9328 if (isa<SCEVMinMaxExpr>(Comm)) 9329 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 9330 if (isa<SCEVSequentialMinMaxExpr>(Comm)) 9331 return getSequentialMinMaxExpr(Comm->getSCEVType(), NewOps); 9332 llvm_unreachable("Unknown commutative / sequential min/max SCEV type!"); 9333 } 9334 } 9335 // If we got here, all operands are loop invariant. 9336 return Comm; 9337 } 9338 9339 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 9340 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 9341 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 9342 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 9343 return Div; // must be loop invariant 9344 return getUDivExpr(LHS, RHS); 9345 } 9346 9347 // If this is a loop recurrence for a loop that does not contain L, then we 9348 // are dealing with the final value computed by the loop. 9349 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 9350 // First, attempt to evaluate each operand. 9351 // Avoid performing the look-up in the common case where the specified 9352 // expression has no loop-variant portions. 9353 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 9354 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 9355 if (OpAtScope == AddRec->getOperand(i)) 9356 continue; 9357 9358 // Okay, at least one of these operands is loop variant but might be 9359 // foldable. Build a new instance of the folded commutative expression. 9360 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 9361 AddRec->op_begin()+i); 9362 NewOps.push_back(OpAtScope); 9363 for (++i; i != e; ++i) 9364 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 9365 9366 const SCEV *FoldedRec = 9367 getAddRecExpr(NewOps, AddRec->getLoop(), 9368 AddRec->getNoWrapFlags(SCEV::FlagNW)); 9369 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 9370 // The addrec may be folded to a nonrecurrence, for example, if the 9371 // induction variable is multiplied by zero after constant folding. Go 9372 // ahead and return the folded value. 9373 if (!AddRec) 9374 return FoldedRec; 9375 break; 9376 } 9377 9378 // If the scope is outside the addrec's loop, evaluate it by using the 9379 // loop exit value of the addrec. 9380 if (!AddRec->getLoop()->contains(L)) { 9381 // To evaluate this recurrence, we need to know how many times the AddRec 9382 // loop iterates. Compute this now. 9383 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 9384 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 9385 9386 // Then, evaluate the AddRec. 9387 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 9388 } 9389 9390 return AddRec; 9391 } 9392 9393 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 9394 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9395 if (Op == Cast->getOperand()) 9396 return Cast; // must be loop invariant 9397 return getZeroExtendExpr(Op, Cast->getType()); 9398 } 9399 9400 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 9401 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9402 if (Op == Cast->getOperand()) 9403 return Cast; // must be loop invariant 9404 return getSignExtendExpr(Op, Cast->getType()); 9405 } 9406 9407 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 9408 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9409 if (Op == Cast->getOperand()) 9410 return Cast; // must be loop invariant 9411 return getTruncateExpr(Op, Cast->getType()); 9412 } 9413 9414 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 9415 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9416 if (Op == Cast->getOperand()) 9417 return Cast; // must be loop invariant 9418 return getPtrToIntExpr(Op, Cast->getType()); 9419 } 9420 9421 llvm_unreachable("Unknown SCEV type!"); 9422 } 9423 9424 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 9425 return getSCEVAtScope(getSCEV(V), L); 9426 } 9427 9428 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 9429 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 9430 return stripInjectiveFunctions(ZExt->getOperand()); 9431 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 9432 return stripInjectiveFunctions(SExt->getOperand()); 9433 return S; 9434 } 9435 9436 /// Finds the minimum unsigned root of the following equation: 9437 /// 9438 /// A * X = B (mod N) 9439 /// 9440 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 9441 /// A and B isn't important. 9442 /// 9443 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 9444 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 9445 ScalarEvolution &SE) { 9446 uint32_t BW = A.getBitWidth(); 9447 assert(BW == SE.getTypeSizeInBits(B->getType())); 9448 assert(A != 0 && "A must be non-zero."); 9449 9450 // 1. D = gcd(A, N) 9451 // 9452 // The gcd of A and N may have only one prime factor: 2. The number of 9453 // trailing zeros in A is its multiplicity 9454 uint32_t Mult2 = A.countTrailingZeros(); 9455 // D = 2^Mult2 9456 9457 // 2. Check if B is divisible by D. 9458 // 9459 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 9460 // is not less than multiplicity of this prime factor for D. 9461 if (SE.GetMinTrailingZeros(B) < Mult2) 9462 return SE.getCouldNotCompute(); 9463 9464 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 9465 // modulo (N / D). 9466 // 9467 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 9468 // (N / D) in general. The inverse itself always fits into BW bits, though, 9469 // so we immediately truncate it. 9470 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 9471 APInt Mod(BW + 1, 0); 9472 Mod.setBit(BW - Mult2); // Mod = N / D 9473 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 9474 9475 // 4. Compute the minimum unsigned root of the equation: 9476 // I * (B / D) mod (N / D) 9477 // To simplify the computation, we factor out the divide by D: 9478 // (I * B mod N) / D 9479 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 9480 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 9481 } 9482 9483 /// For a given quadratic addrec, generate coefficients of the corresponding 9484 /// quadratic equation, multiplied by a common value to ensure that they are 9485 /// integers. 9486 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 9487 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 9488 /// were multiplied by, and BitWidth is the bit width of the original addrec 9489 /// coefficients. 9490 /// This function returns None if the addrec coefficients are not compile- 9491 /// time constants. 9492 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 9493 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 9494 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 9495 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 9496 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 9497 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 9498 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 9499 << *AddRec << '\n'); 9500 9501 // We currently can only solve this if the coefficients are constants. 9502 if (!LC || !MC || !NC) { 9503 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 9504 return None; 9505 } 9506 9507 APInt L = LC->getAPInt(); 9508 APInt M = MC->getAPInt(); 9509 APInt N = NC->getAPInt(); 9510 assert(!N.isZero() && "This is not a quadratic addrec"); 9511 9512 unsigned BitWidth = LC->getAPInt().getBitWidth(); 9513 unsigned NewWidth = BitWidth + 1; 9514 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 9515 << BitWidth << '\n'); 9516 // The sign-extension (as opposed to a zero-extension) here matches the 9517 // extension used in SolveQuadraticEquationWrap (with the same motivation). 9518 N = N.sext(NewWidth); 9519 M = M.sext(NewWidth); 9520 L = L.sext(NewWidth); 9521 9522 // The increments are M, M+N, M+2N, ..., so the accumulated values are 9523 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 9524 // L+M, L+2M+N, L+3M+3N, ... 9525 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 9526 // 9527 // The equation Acc = 0 is then 9528 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 9529 // In a quadratic form it becomes: 9530 // N n^2 + (2M-N) n + 2L = 0. 9531 9532 APInt A = N; 9533 APInt B = 2 * M - A; 9534 APInt C = 2 * L; 9535 APInt T = APInt(NewWidth, 2); 9536 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 9537 << "x + " << C << ", coeff bw: " << NewWidth 9538 << ", multiplied by " << T << '\n'); 9539 return std::make_tuple(A, B, C, T, BitWidth); 9540 } 9541 9542 /// Helper function to compare optional APInts: 9543 /// (a) if X and Y both exist, return min(X, Y), 9544 /// (b) if neither X nor Y exist, return None, 9545 /// (c) if exactly one of X and Y exists, return that value. 9546 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 9547 if (X.hasValue() && Y.hasValue()) { 9548 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 9549 APInt XW = X->sextOrSelf(W); 9550 APInt YW = Y->sextOrSelf(W); 9551 return XW.slt(YW) ? *X : *Y; 9552 } 9553 if (!X.hasValue() && !Y.hasValue()) 9554 return None; 9555 return X.hasValue() ? *X : *Y; 9556 } 9557 9558 /// Helper function to truncate an optional APInt to a given BitWidth. 9559 /// When solving addrec-related equations, it is preferable to return a value 9560 /// that has the same bit width as the original addrec's coefficients. If the 9561 /// solution fits in the original bit width, truncate it (except for i1). 9562 /// Returning a value of a different bit width may inhibit some optimizations. 9563 /// 9564 /// In general, a solution to a quadratic equation generated from an addrec 9565 /// may require BW+1 bits, where BW is the bit width of the addrec's 9566 /// coefficients. The reason is that the coefficients of the quadratic 9567 /// equation are BW+1 bits wide (to avoid truncation when converting from 9568 /// the addrec to the equation). 9569 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 9570 if (!X.hasValue()) 9571 return None; 9572 unsigned W = X->getBitWidth(); 9573 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9574 return X->trunc(BitWidth); 9575 return X; 9576 } 9577 9578 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9579 /// iterations. The values L, M, N are assumed to be signed, and they 9580 /// should all have the same bit widths. 9581 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9582 /// where BW is the bit width of the addrec's coefficients. 9583 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9584 /// returned as such, otherwise the bit width of the returned value may 9585 /// be greater than BW. 9586 /// 9587 /// This function returns None if 9588 /// (a) the addrec coefficients are not constant, or 9589 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9590 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9591 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9592 static Optional<APInt> 9593 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9594 APInt A, B, C, M; 9595 unsigned BitWidth; 9596 auto T = GetQuadraticEquation(AddRec); 9597 if (!T.hasValue()) 9598 return None; 9599 9600 std::tie(A, B, C, M, BitWidth) = *T; 9601 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9602 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9603 if (!X.hasValue()) 9604 return None; 9605 9606 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9607 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9608 if (!V->isZero()) 9609 return None; 9610 9611 return TruncIfPossible(X, BitWidth); 9612 } 9613 9614 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9615 /// iterations. The values M, N are assumed to be signed, and they 9616 /// should all have the same bit widths. 9617 /// Find the least n such that c(n) does not belong to the given range, 9618 /// while c(n-1) does. 9619 /// 9620 /// This function returns None if 9621 /// (a) the addrec coefficients are not constant, or 9622 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9623 /// bounds of the range. 9624 static Optional<APInt> 9625 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9626 const ConstantRange &Range, ScalarEvolution &SE) { 9627 assert(AddRec->getOperand(0)->isZero() && 9628 "Starting value of addrec should be 0"); 9629 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9630 << Range << ", addrec " << *AddRec << '\n'); 9631 // This case is handled in getNumIterationsInRange. Here we can assume that 9632 // we start in the range. 9633 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9634 "Addrec's initial value should be in range"); 9635 9636 APInt A, B, C, M; 9637 unsigned BitWidth; 9638 auto T = GetQuadraticEquation(AddRec); 9639 if (!T.hasValue()) 9640 return None; 9641 9642 // Be careful about the return value: there can be two reasons for not 9643 // returning an actual number. First, if no solutions to the equations 9644 // were found, and second, if the solutions don't leave the given range. 9645 // The first case means that the actual solution is "unknown", the second 9646 // means that it's known, but not valid. If the solution is unknown, we 9647 // cannot make any conclusions. 9648 // Return a pair: the optional solution and a flag indicating if the 9649 // solution was found. 9650 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9651 // Solve for signed overflow and unsigned overflow, pick the lower 9652 // solution. 9653 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9654 << Bound << " (before multiplying by " << M << ")\n"); 9655 Bound *= M; // The quadratic equation multiplier. 9656 9657 Optional<APInt> SO = None; 9658 if (BitWidth > 1) { 9659 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9660 "signed overflow\n"); 9661 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9662 } 9663 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9664 "unsigned overflow\n"); 9665 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9666 BitWidth+1); 9667 9668 auto LeavesRange = [&] (const APInt &X) { 9669 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9670 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9671 if (Range.contains(V0->getValue())) 9672 return false; 9673 // X should be at least 1, so X-1 is non-negative. 9674 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9675 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9676 if (Range.contains(V1->getValue())) 9677 return true; 9678 return false; 9679 }; 9680 9681 // If SolveQuadraticEquationWrap returns None, it means that there can 9682 // be a solution, but the function failed to find it. We cannot treat it 9683 // as "no solution". 9684 if (!SO.hasValue() || !UO.hasValue()) 9685 return { None, false }; 9686 9687 // Check the smaller value first to see if it leaves the range. 9688 // At this point, both SO and UO must have values. 9689 Optional<APInt> Min = MinOptional(SO, UO); 9690 if (LeavesRange(*Min)) 9691 return { Min, true }; 9692 Optional<APInt> Max = Min == SO ? UO : SO; 9693 if (LeavesRange(*Max)) 9694 return { Max, true }; 9695 9696 // Solutions were found, but were eliminated, hence the "true". 9697 return { None, true }; 9698 }; 9699 9700 std::tie(A, B, C, M, BitWidth) = *T; 9701 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9702 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9703 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9704 auto SL = SolveForBoundary(Lower); 9705 auto SU = SolveForBoundary(Upper); 9706 // If any of the solutions was unknown, no meaninigful conclusions can 9707 // be made. 9708 if (!SL.second || !SU.second) 9709 return None; 9710 9711 // Claim: The correct solution is not some value between Min and Max. 9712 // 9713 // Justification: Assuming that Min and Max are different values, one of 9714 // them is when the first signed overflow happens, the other is when the 9715 // first unsigned overflow happens. Crossing the range boundary is only 9716 // possible via an overflow (treating 0 as a special case of it, modeling 9717 // an overflow as crossing k*2^W for some k). 9718 // 9719 // The interesting case here is when Min was eliminated as an invalid 9720 // solution, but Max was not. The argument is that if there was another 9721 // overflow between Min and Max, it would also have been eliminated if 9722 // it was considered. 9723 // 9724 // For a given boundary, it is possible to have two overflows of the same 9725 // type (signed/unsigned) without having the other type in between: this 9726 // can happen when the vertex of the parabola is between the iterations 9727 // corresponding to the overflows. This is only possible when the two 9728 // overflows cross k*2^W for the same k. In such case, if the second one 9729 // left the range (and was the first one to do so), the first overflow 9730 // would have to enter the range, which would mean that either we had left 9731 // the range before or that we started outside of it. Both of these cases 9732 // are contradictions. 9733 // 9734 // Claim: In the case where SolveForBoundary returns None, the correct 9735 // solution is not some value between the Max for this boundary and the 9736 // Min of the other boundary. 9737 // 9738 // Justification: Assume that we had such Max_A and Min_B corresponding 9739 // to range boundaries A and B and such that Max_A < Min_B. If there was 9740 // a solution between Max_A and Min_B, it would have to be caused by an 9741 // overflow corresponding to either A or B. It cannot correspond to B, 9742 // since Min_B is the first occurrence of such an overflow. If it 9743 // corresponded to A, it would have to be either a signed or an unsigned 9744 // overflow that is larger than both eliminated overflows for A. But 9745 // between the eliminated overflows and this overflow, the values would 9746 // cover the entire value space, thus crossing the other boundary, which 9747 // is a contradiction. 9748 9749 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9750 } 9751 9752 ScalarEvolution::ExitLimit 9753 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9754 bool AllowPredicates) { 9755 9756 // This is only used for loops with a "x != y" exit test. The exit condition 9757 // is now expressed as a single expression, V = x-y. So the exit test is 9758 // effectively V != 0. We know and take advantage of the fact that this 9759 // expression only being used in a comparison by zero context. 9760 9761 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9762 // If the value is a constant 9763 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9764 // If the value is already zero, the branch will execute zero times. 9765 if (C->getValue()->isZero()) return C; 9766 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9767 } 9768 9769 const SCEVAddRecExpr *AddRec = 9770 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9771 9772 if (!AddRec && AllowPredicates) 9773 // Try to make this an AddRec using runtime tests, in the first X 9774 // iterations of this loop, where X is the SCEV expression found by the 9775 // algorithm below. 9776 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9777 9778 if (!AddRec || AddRec->getLoop() != L) 9779 return getCouldNotCompute(); 9780 9781 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9782 // the quadratic equation to solve it. 9783 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9784 // We can only use this value if the chrec ends up with an exact zero 9785 // value at this index. When solving for "X*X != 5", for example, we 9786 // should not accept a root of 2. 9787 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9788 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9789 return ExitLimit(R, R, false, Predicates); 9790 } 9791 return getCouldNotCompute(); 9792 } 9793 9794 // Otherwise we can only handle this if it is affine. 9795 if (!AddRec->isAffine()) 9796 return getCouldNotCompute(); 9797 9798 // If this is an affine expression, the execution count of this branch is 9799 // the minimum unsigned root of the following equation: 9800 // 9801 // Start + Step*N = 0 (mod 2^BW) 9802 // 9803 // equivalent to: 9804 // 9805 // Step*N = -Start (mod 2^BW) 9806 // 9807 // where BW is the common bit width of Start and Step. 9808 9809 // Get the initial value for the loop. 9810 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9811 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9812 9813 // For now we handle only constant steps. 9814 // 9815 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9816 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9817 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9818 // We have not yet seen any such cases. 9819 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9820 if (!StepC || StepC->getValue()->isZero()) 9821 return getCouldNotCompute(); 9822 9823 // For positive steps (counting up until unsigned overflow): 9824 // N = -Start/Step (as unsigned) 9825 // For negative steps (counting down to zero): 9826 // N = Start/-Step 9827 // First compute the unsigned distance from zero in the direction of Step. 9828 bool CountDown = StepC->getAPInt().isNegative(); 9829 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9830 9831 // Handle unitary steps, which cannot wraparound. 9832 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9833 // N = Distance (as unsigned) 9834 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9835 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9836 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance)); 9837 9838 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9839 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9840 // case, and see if we can improve the bound. 9841 // 9842 // Explicitly handling this here is necessary because getUnsignedRange 9843 // isn't context-sensitive; it doesn't know that we only care about the 9844 // range inside the loop. 9845 const SCEV *Zero = getZero(Distance->getType()); 9846 const SCEV *One = getOne(Distance->getType()); 9847 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9848 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9849 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9850 // as "unsigned_max(Distance + 1) - 1". 9851 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9852 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9853 } 9854 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9855 } 9856 9857 // If the condition controls loop exit (the loop exits only if the expression 9858 // is true) and the addition is no-wrap we can use unsigned divide to 9859 // compute the backedge count. In this case, the step may not divide the 9860 // distance, but we don't care because if the condition is "missed" the loop 9861 // will have undefined behavior due to wrapping. 9862 if (ControlsExit && AddRec->hasNoSelfWrap() && 9863 loopHasNoAbnormalExits(AddRec->getLoop())) { 9864 const SCEV *Exact = 9865 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9866 const SCEV *Max = getCouldNotCompute(); 9867 if (Exact != getCouldNotCompute()) { 9868 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 9869 Max = getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact))); 9870 } 9871 return ExitLimit(Exact, Max, false, Predicates); 9872 } 9873 9874 // Solve the general equation. 9875 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9876 getNegativeSCEV(Start), *this); 9877 9878 const SCEV *M = E; 9879 if (E != getCouldNotCompute()) { 9880 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L)); 9881 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E))); 9882 } 9883 return ExitLimit(E, M, false, Predicates); 9884 } 9885 9886 ScalarEvolution::ExitLimit 9887 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9888 // Loops that look like: while (X == 0) are very strange indeed. We don't 9889 // handle them yet except for the trivial case. This could be expanded in the 9890 // future as needed. 9891 9892 // If the value is a constant, check to see if it is known to be non-zero 9893 // already. If so, the backedge will execute zero times. 9894 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9895 if (!C->getValue()->isZero()) 9896 return getZero(C->getType()); 9897 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9898 } 9899 9900 // We could implement others, but I really doubt anyone writes loops like 9901 // this, and if they did, they would already be constant folded. 9902 return getCouldNotCompute(); 9903 } 9904 9905 std::pair<const BasicBlock *, const BasicBlock *> 9906 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9907 const { 9908 // If the block has a unique predecessor, then there is no path from the 9909 // predecessor to the block that does not go through the direct edge 9910 // from the predecessor to the block. 9911 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9912 return {Pred, BB}; 9913 9914 // A loop's header is defined to be a block that dominates the loop. 9915 // If the header has a unique predecessor outside the loop, it must be 9916 // a block that has exactly one successor that can reach the loop. 9917 if (const Loop *L = LI.getLoopFor(BB)) 9918 return {L->getLoopPredecessor(), L->getHeader()}; 9919 9920 return {nullptr, nullptr}; 9921 } 9922 9923 /// SCEV structural equivalence is usually sufficient for testing whether two 9924 /// expressions are equal, however for the purposes of looking for a condition 9925 /// guarding a loop, it can be useful to be a little more general, since a 9926 /// front-end may have replicated the controlling expression. 9927 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9928 // Quick check to see if they are the same SCEV. 9929 if (A == B) return true; 9930 9931 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9932 // Not all instructions that are "identical" compute the same value. For 9933 // instance, two distinct alloca instructions allocating the same type are 9934 // identical and do not read memory; but compute distinct values. 9935 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9936 }; 9937 9938 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9939 // two different instructions with the same value. Check for this case. 9940 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9941 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9942 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9943 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9944 if (ComputesEqualValues(AI, BI)) 9945 return true; 9946 9947 // Otherwise assume they may have a different value. 9948 return false; 9949 } 9950 9951 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9952 const SCEV *&LHS, const SCEV *&RHS, 9953 unsigned Depth) { 9954 bool Changed = false; 9955 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9956 // '0 != 0'. 9957 auto TrivialCase = [&](bool TriviallyTrue) { 9958 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9959 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9960 return true; 9961 }; 9962 // If we hit the max recursion limit bail out. 9963 if (Depth >= 3) 9964 return false; 9965 9966 // Canonicalize a constant to the right side. 9967 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9968 // Check for both operands constant. 9969 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9970 if (ConstantExpr::getICmp(Pred, 9971 LHSC->getValue(), 9972 RHSC->getValue())->isNullValue()) 9973 return TrivialCase(false); 9974 else 9975 return TrivialCase(true); 9976 } 9977 // Otherwise swap the operands to put the constant on the right. 9978 std::swap(LHS, RHS); 9979 Pred = ICmpInst::getSwappedPredicate(Pred); 9980 Changed = true; 9981 } 9982 9983 // If we're comparing an addrec with a value which is loop-invariant in the 9984 // addrec's loop, put the addrec on the left. Also make a dominance check, 9985 // as both operands could be addrecs loop-invariant in each other's loop. 9986 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9987 const Loop *L = AR->getLoop(); 9988 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9989 std::swap(LHS, RHS); 9990 Pred = ICmpInst::getSwappedPredicate(Pred); 9991 Changed = true; 9992 } 9993 } 9994 9995 // If there's a constant operand, canonicalize comparisons with boundary 9996 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9997 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9998 const APInt &RA = RC->getAPInt(); 9999 10000 bool SimplifiedByConstantRange = false; 10001 10002 if (!ICmpInst::isEquality(Pred)) { 10003 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 10004 if (ExactCR.isFullSet()) 10005 return TrivialCase(true); 10006 else if (ExactCR.isEmptySet()) 10007 return TrivialCase(false); 10008 10009 APInt NewRHS; 10010 CmpInst::Predicate NewPred; 10011 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 10012 ICmpInst::isEquality(NewPred)) { 10013 // We were able to convert an inequality to an equality. 10014 Pred = NewPred; 10015 RHS = getConstant(NewRHS); 10016 Changed = SimplifiedByConstantRange = true; 10017 } 10018 } 10019 10020 if (!SimplifiedByConstantRange) { 10021 switch (Pred) { 10022 default: 10023 break; 10024 case ICmpInst::ICMP_EQ: 10025 case ICmpInst::ICMP_NE: 10026 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 10027 if (!RA) 10028 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 10029 if (const SCEVMulExpr *ME = 10030 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 10031 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 10032 ME->getOperand(0)->isAllOnesValue()) { 10033 RHS = AE->getOperand(1); 10034 LHS = ME->getOperand(1); 10035 Changed = true; 10036 } 10037 break; 10038 10039 10040 // The "Should have been caught earlier!" messages refer to the fact 10041 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 10042 // should have fired on the corresponding cases, and canonicalized the 10043 // check to trivial case. 10044 10045 case ICmpInst::ICMP_UGE: 10046 assert(!RA.isMinValue() && "Should have been caught earlier!"); 10047 Pred = ICmpInst::ICMP_UGT; 10048 RHS = getConstant(RA - 1); 10049 Changed = true; 10050 break; 10051 case ICmpInst::ICMP_ULE: 10052 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 10053 Pred = ICmpInst::ICMP_ULT; 10054 RHS = getConstant(RA + 1); 10055 Changed = true; 10056 break; 10057 case ICmpInst::ICMP_SGE: 10058 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 10059 Pred = ICmpInst::ICMP_SGT; 10060 RHS = getConstant(RA - 1); 10061 Changed = true; 10062 break; 10063 case ICmpInst::ICMP_SLE: 10064 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 10065 Pred = ICmpInst::ICMP_SLT; 10066 RHS = getConstant(RA + 1); 10067 Changed = true; 10068 break; 10069 } 10070 } 10071 } 10072 10073 // Check for obvious equality. 10074 if (HasSameValue(LHS, RHS)) { 10075 if (ICmpInst::isTrueWhenEqual(Pred)) 10076 return TrivialCase(true); 10077 if (ICmpInst::isFalseWhenEqual(Pred)) 10078 return TrivialCase(false); 10079 } 10080 10081 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 10082 // adding or subtracting 1 from one of the operands. 10083 switch (Pred) { 10084 case ICmpInst::ICMP_SLE: 10085 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 10086 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 10087 SCEV::FlagNSW); 10088 Pred = ICmpInst::ICMP_SLT; 10089 Changed = true; 10090 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 10091 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 10092 SCEV::FlagNSW); 10093 Pred = ICmpInst::ICMP_SLT; 10094 Changed = true; 10095 } 10096 break; 10097 case ICmpInst::ICMP_SGE: 10098 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 10099 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 10100 SCEV::FlagNSW); 10101 Pred = ICmpInst::ICMP_SGT; 10102 Changed = true; 10103 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 10104 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 10105 SCEV::FlagNSW); 10106 Pred = ICmpInst::ICMP_SGT; 10107 Changed = true; 10108 } 10109 break; 10110 case ICmpInst::ICMP_ULE: 10111 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 10112 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 10113 SCEV::FlagNUW); 10114 Pred = ICmpInst::ICMP_ULT; 10115 Changed = true; 10116 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 10117 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 10118 Pred = ICmpInst::ICMP_ULT; 10119 Changed = true; 10120 } 10121 break; 10122 case ICmpInst::ICMP_UGE: 10123 if (!getUnsignedRangeMin(RHS).isMinValue()) { 10124 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 10125 Pred = ICmpInst::ICMP_UGT; 10126 Changed = true; 10127 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 10128 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 10129 SCEV::FlagNUW); 10130 Pred = ICmpInst::ICMP_UGT; 10131 Changed = true; 10132 } 10133 break; 10134 default: 10135 break; 10136 } 10137 10138 // TODO: More simplifications are possible here. 10139 10140 // Recursively simplify until we either hit a recursion limit or nothing 10141 // changes. 10142 if (Changed) 10143 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 10144 10145 return Changed; 10146 } 10147 10148 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 10149 return getSignedRangeMax(S).isNegative(); 10150 } 10151 10152 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 10153 return getSignedRangeMin(S).isStrictlyPositive(); 10154 } 10155 10156 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 10157 return !getSignedRangeMin(S).isNegative(); 10158 } 10159 10160 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 10161 return !getSignedRangeMax(S).isStrictlyPositive(); 10162 } 10163 10164 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 10165 return getUnsignedRangeMin(S) != 0; 10166 } 10167 10168 std::pair<const SCEV *, const SCEV *> 10169 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 10170 // Compute SCEV on entry of loop L. 10171 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 10172 if (Start == getCouldNotCompute()) 10173 return { Start, Start }; 10174 // Compute post increment SCEV for loop L. 10175 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 10176 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 10177 return { Start, PostInc }; 10178 } 10179 10180 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 10181 const SCEV *LHS, const SCEV *RHS) { 10182 // First collect all loops. 10183 SmallPtrSet<const Loop *, 8> LoopsUsed; 10184 getUsedLoops(LHS, LoopsUsed); 10185 getUsedLoops(RHS, LoopsUsed); 10186 10187 if (LoopsUsed.empty()) 10188 return false; 10189 10190 // Domination relationship must be a linear order on collected loops. 10191 #ifndef NDEBUG 10192 for (auto *L1 : LoopsUsed) 10193 for (auto *L2 : LoopsUsed) 10194 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 10195 DT.dominates(L2->getHeader(), L1->getHeader())) && 10196 "Domination relationship is not a linear order"); 10197 #endif 10198 10199 const Loop *MDL = 10200 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 10201 [&](const Loop *L1, const Loop *L2) { 10202 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 10203 }); 10204 10205 // Get init and post increment value for LHS. 10206 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 10207 // if LHS contains unknown non-invariant SCEV then bail out. 10208 if (SplitLHS.first == getCouldNotCompute()) 10209 return false; 10210 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 10211 // Get init and post increment value for RHS. 10212 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 10213 // if RHS contains unknown non-invariant SCEV then bail out. 10214 if (SplitRHS.first == getCouldNotCompute()) 10215 return false; 10216 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 10217 // It is possible that init SCEV contains an invariant load but it does 10218 // not dominate MDL and is not available at MDL loop entry, so we should 10219 // check it here. 10220 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 10221 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 10222 return false; 10223 10224 // It seems backedge guard check is faster than entry one so in some cases 10225 // it can speed up whole estimation by short circuit 10226 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 10227 SplitRHS.second) && 10228 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 10229 } 10230 10231 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 10232 const SCEV *LHS, const SCEV *RHS) { 10233 // Canonicalize the inputs first. 10234 (void)SimplifyICmpOperands(Pred, LHS, RHS); 10235 10236 if (isKnownViaInduction(Pred, LHS, RHS)) 10237 return true; 10238 10239 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 10240 return true; 10241 10242 // Otherwise see what can be done with some simple reasoning. 10243 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 10244 } 10245 10246 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 10247 const SCEV *LHS, 10248 const SCEV *RHS) { 10249 if (isKnownPredicate(Pred, LHS, RHS)) 10250 return true; 10251 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 10252 return false; 10253 return None; 10254 } 10255 10256 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 10257 const SCEV *LHS, const SCEV *RHS, 10258 const Instruction *CtxI) { 10259 // TODO: Analyze guards and assumes from Context's block. 10260 return isKnownPredicate(Pred, LHS, RHS) || 10261 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS); 10262 } 10263 10264 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, 10265 const SCEV *LHS, 10266 const SCEV *RHS, 10267 const Instruction *CtxI) { 10268 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 10269 if (KnownWithoutContext) 10270 return KnownWithoutContext; 10271 10272 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS)) 10273 return true; 10274 else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), 10275 ICmpInst::getInversePredicate(Pred), 10276 LHS, RHS)) 10277 return false; 10278 return None; 10279 } 10280 10281 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 10282 const SCEVAddRecExpr *LHS, 10283 const SCEV *RHS) { 10284 const Loop *L = LHS->getLoop(); 10285 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 10286 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 10287 } 10288 10289 Optional<ScalarEvolution::MonotonicPredicateType> 10290 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 10291 ICmpInst::Predicate Pred) { 10292 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 10293 10294 #ifndef NDEBUG 10295 // Verify an invariant: inverting the predicate should turn a monotonically 10296 // increasing change to a monotonically decreasing one, and vice versa. 10297 if (Result) { 10298 auto ResultSwapped = 10299 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 10300 10301 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 10302 assert(ResultSwapped.getValue() != Result.getValue() && 10303 "monotonicity should flip as we flip the predicate"); 10304 } 10305 #endif 10306 10307 return Result; 10308 } 10309 10310 Optional<ScalarEvolution::MonotonicPredicateType> 10311 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 10312 ICmpInst::Predicate Pred) { 10313 // A zero step value for LHS means the induction variable is essentially a 10314 // loop invariant value. We don't really depend on the predicate actually 10315 // flipping from false to true (for increasing predicates, and the other way 10316 // around for decreasing predicates), all we care about is that *if* the 10317 // predicate changes then it only changes from false to true. 10318 // 10319 // A zero step value in itself is not very useful, but there may be places 10320 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 10321 // as general as possible. 10322 10323 // Only handle LE/LT/GE/GT predicates. 10324 if (!ICmpInst::isRelational(Pred)) 10325 return None; 10326 10327 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 10328 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 10329 "Should be greater or less!"); 10330 10331 // Check that AR does not wrap. 10332 if (ICmpInst::isUnsigned(Pred)) { 10333 if (!LHS->hasNoUnsignedWrap()) 10334 return None; 10335 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10336 } else { 10337 assert(ICmpInst::isSigned(Pred) && 10338 "Relational predicate is either signed or unsigned!"); 10339 if (!LHS->hasNoSignedWrap()) 10340 return None; 10341 10342 const SCEV *Step = LHS->getStepRecurrence(*this); 10343 10344 if (isKnownNonNegative(Step)) 10345 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10346 10347 if (isKnownNonPositive(Step)) 10348 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10349 10350 return None; 10351 } 10352 } 10353 10354 Optional<ScalarEvolution::LoopInvariantPredicate> 10355 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 10356 const SCEV *LHS, const SCEV *RHS, 10357 const Loop *L) { 10358 10359 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10360 if (!isLoopInvariant(RHS, L)) { 10361 if (!isLoopInvariant(LHS, L)) 10362 return None; 10363 10364 std::swap(LHS, RHS); 10365 Pred = ICmpInst::getSwappedPredicate(Pred); 10366 } 10367 10368 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10369 if (!ArLHS || ArLHS->getLoop() != L) 10370 return None; 10371 10372 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 10373 if (!MonotonicType) 10374 return None; 10375 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 10376 // true as the loop iterates, and the backedge is control dependent on 10377 // "ArLHS `Pred` RHS" == true then we can reason as follows: 10378 // 10379 // * if the predicate was false in the first iteration then the predicate 10380 // is never evaluated again, since the loop exits without taking the 10381 // backedge. 10382 // * if the predicate was true in the first iteration then it will 10383 // continue to be true for all future iterations since it is 10384 // monotonically increasing. 10385 // 10386 // For both the above possibilities, we can replace the loop varying 10387 // predicate with its value on the first iteration of the loop (which is 10388 // loop invariant). 10389 // 10390 // A similar reasoning applies for a monotonically decreasing predicate, by 10391 // replacing true with false and false with true in the above two bullets. 10392 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 10393 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 10394 10395 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 10396 return None; 10397 10398 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 10399 } 10400 10401 Optional<ScalarEvolution::LoopInvariantPredicate> 10402 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 10403 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 10404 const Instruction *CtxI, const SCEV *MaxIter) { 10405 // Try to prove the following set of facts: 10406 // - The predicate is monotonic in the iteration space. 10407 // - If the check does not fail on the 1st iteration: 10408 // - No overflow will happen during first MaxIter iterations; 10409 // - It will not fail on the MaxIter'th iteration. 10410 // If the check does fail on the 1st iteration, we leave the loop and no 10411 // other checks matter. 10412 10413 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10414 if (!isLoopInvariant(RHS, L)) { 10415 if (!isLoopInvariant(LHS, L)) 10416 return None; 10417 10418 std::swap(LHS, RHS); 10419 Pred = ICmpInst::getSwappedPredicate(Pred); 10420 } 10421 10422 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 10423 if (!AR || AR->getLoop() != L) 10424 return None; 10425 10426 // The predicate must be relational (i.e. <, <=, >=, >). 10427 if (!ICmpInst::isRelational(Pred)) 10428 return None; 10429 10430 // TODO: Support steps other than +/- 1. 10431 const SCEV *Step = AR->getStepRecurrence(*this); 10432 auto *One = getOne(Step->getType()); 10433 auto *MinusOne = getNegativeSCEV(One); 10434 if (Step != One && Step != MinusOne) 10435 return None; 10436 10437 // Type mismatch here means that MaxIter is potentially larger than max 10438 // unsigned value in start type, which mean we cannot prove no wrap for the 10439 // indvar. 10440 if (AR->getType() != MaxIter->getType()) 10441 return None; 10442 10443 // Value of IV on suggested last iteration. 10444 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 10445 // Does it still meet the requirement? 10446 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 10447 return None; 10448 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 10449 // not exceed max unsigned value of this type), this effectively proves 10450 // that there is no wrap during the iteration. To prove that there is no 10451 // signed/unsigned wrap, we need to check that 10452 // Start <= Last for step = 1 or Start >= Last for step = -1. 10453 ICmpInst::Predicate NoOverflowPred = 10454 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 10455 if (Step == MinusOne) 10456 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 10457 const SCEV *Start = AR->getStart(); 10458 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI)) 10459 return None; 10460 10461 // Everything is fine. 10462 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 10463 } 10464 10465 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 10466 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 10467 if (HasSameValue(LHS, RHS)) 10468 return ICmpInst::isTrueWhenEqual(Pred); 10469 10470 // This code is split out from isKnownPredicate because it is called from 10471 // within isLoopEntryGuardedByCond. 10472 10473 auto CheckRanges = [&](const ConstantRange &RangeLHS, 10474 const ConstantRange &RangeRHS) { 10475 return RangeLHS.icmp(Pred, RangeRHS); 10476 }; 10477 10478 // The check at the top of the function catches the case where the values are 10479 // known to be equal. 10480 if (Pred == CmpInst::ICMP_EQ) 10481 return false; 10482 10483 if (Pred == CmpInst::ICMP_NE) { 10484 if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 10485 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS))) 10486 return true; 10487 auto *Diff = getMinusSCEV(LHS, RHS); 10488 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff); 10489 } 10490 10491 if (CmpInst::isSigned(Pred)) 10492 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 10493 10494 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 10495 } 10496 10497 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 10498 const SCEV *LHS, 10499 const SCEV *RHS) { 10500 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where 10501 // C1 and C2 are constant integers. If either X or Y are not add expressions, 10502 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via 10503 // OutC1 and OutC2. 10504 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y, 10505 APInt &OutC1, APInt &OutC2, 10506 SCEV::NoWrapFlags ExpectedFlags) { 10507 const SCEV *XNonConstOp, *XConstOp; 10508 const SCEV *YNonConstOp, *YConstOp; 10509 SCEV::NoWrapFlags XFlagsPresent; 10510 SCEV::NoWrapFlags YFlagsPresent; 10511 10512 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) { 10513 XConstOp = getZero(X->getType()); 10514 XNonConstOp = X; 10515 XFlagsPresent = ExpectedFlags; 10516 } 10517 if (!isa<SCEVConstant>(XConstOp) || 10518 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) 10519 return false; 10520 10521 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) { 10522 YConstOp = getZero(Y->getType()); 10523 YNonConstOp = Y; 10524 YFlagsPresent = ExpectedFlags; 10525 } 10526 10527 if (!isa<SCEVConstant>(YConstOp) || 10528 (YFlagsPresent & ExpectedFlags) != ExpectedFlags) 10529 return false; 10530 10531 if (YNonConstOp != XNonConstOp) 10532 return false; 10533 10534 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt(); 10535 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt(); 10536 10537 return true; 10538 }; 10539 10540 APInt C1; 10541 APInt C2; 10542 10543 switch (Pred) { 10544 default: 10545 break; 10546 10547 case ICmpInst::ICMP_SGE: 10548 std::swap(LHS, RHS); 10549 LLVM_FALLTHROUGH; 10550 case ICmpInst::ICMP_SLE: 10551 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2. 10552 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2)) 10553 return true; 10554 10555 break; 10556 10557 case ICmpInst::ICMP_SGT: 10558 std::swap(LHS, RHS); 10559 LLVM_FALLTHROUGH; 10560 case ICmpInst::ICMP_SLT: 10561 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2. 10562 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2)) 10563 return true; 10564 10565 break; 10566 10567 case ICmpInst::ICMP_UGE: 10568 std::swap(LHS, RHS); 10569 LLVM_FALLTHROUGH; 10570 case ICmpInst::ICMP_ULE: 10571 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2. 10572 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2)) 10573 return true; 10574 10575 break; 10576 10577 case ICmpInst::ICMP_UGT: 10578 std::swap(LHS, RHS); 10579 LLVM_FALLTHROUGH; 10580 case ICmpInst::ICMP_ULT: 10581 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2. 10582 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2)) 10583 return true; 10584 break; 10585 } 10586 10587 return false; 10588 } 10589 10590 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10591 const SCEV *LHS, 10592 const SCEV *RHS) { 10593 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10594 return false; 10595 10596 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10597 // the stack can result in exponential time complexity. 10598 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10599 10600 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10601 // 10602 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10603 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10604 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10605 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10606 // use isKnownPredicate later if needed. 10607 return isKnownNonNegative(RHS) && 10608 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10609 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10610 } 10611 10612 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10613 ICmpInst::Predicate Pred, 10614 const SCEV *LHS, const SCEV *RHS) { 10615 // No need to even try if we know the module has no guards. 10616 if (!HasGuards) 10617 return false; 10618 10619 return any_of(*BB, [&](const Instruction &I) { 10620 using namespace llvm::PatternMatch; 10621 10622 Value *Condition; 10623 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10624 m_Value(Condition))) && 10625 isImpliedCond(Pred, LHS, RHS, Condition, false); 10626 }); 10627 } 10628 10629 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10630 /// protected by a conditional between LHS and RHS. This is used to 10631 /// to eliminate casts. 10632 bool 10633 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10634 ICmpInst::Predicate Pred, 10635 const SCEV *LHS, const SCEV *RHS) { 10636 // Interpret a null as meaning no loop, where there is obviously no guard 10637 // (interprocedural conditions notwithstanding). 10638 if (!L) return true; 10639 10640 if (VerifyIR) 10641 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10642 "This cannot be done on broken IR!"); 10643 10644 10645 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10646 return true; 10647 10648 BasicBlock *Latch = L->getLoopLatch(); 10649 if (!Latch) 10650 return false; 10651 10652 BranchInst *LoopContinuePredicate = 10653 dyn_cast<BranchInst>(Latch->getTerminator()); 10654 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10655 isImpliedCond(Pred, LHS, RHS, 10656 LoopContinuePredicate->getCondition(), 10657 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10658 return true; 10659 10660 // We don't want more than one activation of the following loops on the stack 10661 // -- that can lead to O(n!) time complexity. 10662 if (WalkingBEDominatingConds) 10663 return false; 10664 10665 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10666 10667 // See if we can exploit a trip count to prove the predicate. 10668 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10669 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10670 if (LatchBECount != getCouldNotCompute()) { 10671 // We know that Latch branches back to the loop header exactly 10672 // LatchBECount times. This means the backdege condition at Latch is 10673 // equivalent to "{0,+,1} u< LatchBECount". 10674 Type *Ty = LatchBECount->getType(); 10675 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10676 const SCEV *LoopCounter = 10677 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10678 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10679 LatchBECount)) 10680 return true; 10681 } 10682 10683 // Check conditions due to any @llvm.assume intrinsics. 10684 for (auto &AssumeVH : AC.assumptions()) { 10685 if (!AssumeVH) 10686 continue; 10687 auto *CI = cast<CallInst>(AssumeVH); 10688 if (!DT.dominates(CI, Latch->getTerminator())) 10689 continue; 10690 10691 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10692 return true; 10693 } 10694 10695 // If the loop is not reachable from the entry block, we risk running into an 10696 // infinite loop as we walk up into the dom tree. These loops do not matter 10697 // anyway, so we just return a conservative answer when we see them. 10698 if (!DT.isReachableFromEntry(L->getHeader())) 10699 return false; 10700 10701 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10702 return true; 10703 10704 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10705 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10706 assert(DTN && "should reach the loop header before reaching the root!"); 10707 10708 BasicBlock *BB = DTN->getBlock(); 10709 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10710 return true; 10711 10712 BasicBlock *PBB = BB->getSinglePredecessor(); 10713 if (!PBB) 10714 continue; 10715 10716 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10717 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10718 continue; 10719 10720 Value *Condition = ContinuePredicate->getCondition(); 10721 10722 // If we have an edge `E` within the loop body that dominates the only 10723 // latch, the condition guarding `E` also guards the backedge. This 10724 // reasoning works only for loops with a single latch. 10725 10726 BasicBlockEdge DominatingEdge(PBB, BB); 10727 if (DominatingEdge.isSingleEdge()) { 10728 // We're constructively (and conservatively) enumerating edges within the 10729 // loop body that dominate the latch. The dominator tree better agree 10730 // with us on this: 10731 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10732 10733 if (isImpliedCond(Pred, LHS, RHS, Condition, 10734 BB != ContinuePredicate->getSuccessor(0))) 10735 return true; 10736 } 10737 } 10738 10739 return false; 10740 } 10741 10742 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10743 ICmpInst::Predicate Pred, 10744 const SCEV *LHS, 10745 const SCEV *RHS) { 10746 if (VerifyIR) 10747 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10748 "This cannot be done on broken IR!"); 10749 10750 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10751 // the facts (a >= b && a != b) separately. A typical situation is when the 10752 // non-strict comparison is known from ranges and non-equality is known from 10753 // dominating predicates. If we are proving strict comparison, we always try 10754 // to prove non-equality and non-strict comparison separately. 10755 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10756 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10757 bool ProvedNonStrictComparison = false; 10758 bool ProvedNonEquality = false; 10759 10760 auto SplitAndProve = 10761 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10762 if (!ProvedNonStrictComparison) 10763 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10764 if (!ProvedNonEquality) 10765 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10766 if (ProvedNonStrictComparison && ProvedNonEquality) 10767 return true; 10768 return false; 10769 }; 10770 10771 if (ProvingStrictComparison) { 10772 auto ProofFn = [&](ICmpInst::Predicate P) { 10773 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10774 }; 10775 if (SplitAndProve(ProofFn)) 10776 return true; 10777 } 10778 10779 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10780 auto ProveViaGuard = [&](const BasicBlock *Block) { 10781 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10782 return true; 10783 if (ProvingStrictComparison) { 10784 auto ProofFn = [&](ICmpInst::Predicate P) { 10785 return isImpliedViaGuard(Block, P, LHS, RHS); 10786 }; 10787 if (SplitAndProve(ProofFn)) 10788 return true; 10789 } 10790 return false; 10791 }; 10792 10793 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10794 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10795 const Instruction *CtxI = &BB->front(); 10796 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI)) 10797 return true; 10798 if (ProvingStrictComparison) { 10799 auto ProofFn = [&](ICmpInst::Predicate P) { 10800 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI); 10801 }; 10802 if (SplitAndProve(ProofFn)) 10803 return true; 10804 } 10805 return false; 10806 }; 10807 10808 // Starting at the block's predecessor, climb up the predecessor chain, as long 10809 // as there are predecessors that can be found that have unique successors 10810 // leading to the original block. 10811 const Loop *ContainingLoop = LI.getLoopFor(BB); 10812 const BasicBlock *PredBB; 10813 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10814 PredBB = ContainingLoop->getLoopPredecessor(); 10815 else 10816 PredBB = BB->getSinglePredecessor(); 10817 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10818 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10819 if (ProveViaGuard(Pair.first)) 10820 return true; 10821 10822 const BranchInst *LoopEntryPredicate = 10823 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10824 if (!LoopEntryPredicate || 10825 LoopEntryPredicate->isUnconditional()) 10826 continue; 10827 10828 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10829 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10830 return true; 10831 } 10832 10833 // Check conditions due to any @llvm.assume intrinsics. 10834 for (auto &AssumeVH : AC.assumptions()) { 10835 if (!AssumeVH) 10836 continue; 10837 auto *CI = cast<CallInst>(AssumeVH); 10838 if (!DT.dominates(CI, BB)) 10839 continue; 10840 10841 if (ProveViaCond(CI->getArgOperand(0), false)) 10842 return true; 10843 } 10844 10845 return false; 10846 } 10847 10848 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10849 ICmpInst::Predicate Pred, 10850 const SCEV *LHS, 10851 const SCEV *RHS) { 10852 // Interpret a null as meaning no loop, where there is obviously no guard 10853 // (interprocedural conditions notwithstanding). 10854 if (!L) 10855 return false; 10856 10857 // Both LHS and RHS must be available at loop entry. 10858 assert(isAvailableAtLoopEntry(LHS, L) && 10859 "LHS is not available at Loop Entry"); 10860 assert(isAvailableAtLoopEntry(RHS, L) && 10861 "RHS is not available at Loop Entry"); 10862 10863 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10864 return true; 10865 10866 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10867 } 10868 10869 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10870 const SCEV *RHS, 10871 const Value *FoundCondValue, bool Inverse, 10872 const Instruction *CtxI) { 10873 // False conditions implies anything. Do not bother analyzing it further. 10874 if (FoundCondValue == 10875 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 10876 return true; 10877 10878 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10879 return false; 10880 10881 auto ClearOnExit = 10882 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10883 10884 // Recursively handle And and Or conditions. 10885 const Value *Op0, *Op1; 10886 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 10887 if (!Inverse) 10888 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 10889 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 10890 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 10891 if (Inverse) 10892 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 10893 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 10894 } 10895 10896 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10897 if (!ICI) return false; 10898 10899 // Now that we found a conditional branch that dominates the loop or controls 10900 // the loop latch. Check to see if it is the comparison we are looking for. 10901 ICmpInst::Predicate FoundPred; 10902 if (Inverse) 10903 FoundPred = ICI->getInversePredicate(); 10904 else 10905 FoundPred = ICI->getPredicate(); 10906 10907 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10908 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10909 10910 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI); 10911 } 10912 10913 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10914 const SCEV *RHS, 10915 ICmpInst::Predicate FoundPred, 10916 const SCEV *FoundLHS, const SCEV *FoundRHS, 10917 const Instruction *CtxI) { 10918 // Balance the types. 10919 if (getTypeSizeInBits(LHS->getType()) < 10920 getTypeSizeInBits(FoundLHS->getType())) { 10921 // For unsigned and equality predicates, try to prove that both found 10922 // operands fit into narrow unsigned range. If so, try to prove facts in 10923 // narrow types. 10924 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy()) { 10925 auto *NarrowType = LHS->getType(); 10926 auto *WideType = FoundLHS->getType(); 10927 auto BitWidth = getTypeSizeInBits(NarrowType); 10928 const SCEV *MaxValue = getZeroExtendExpr( 10929 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10930 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS, 10931 MaxValue) && 10932 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS, 10933 MaxValue)) { 10934 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10935 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10936 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10937 TruncFoundRHS, CtxI)) 10938 return true; 10939 } 10940 } 10941 10942 if (LHS->getType()->isPointerTy()) 10943 return false; 10944 if (CmpInst::isSigned(Pred)) { 10945 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10946 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10947 } else { 10948 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10949 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10950 } 10951 } else if (getTypeSizeInBits(LHS->getType()) > 10952 getTypeSizeInBits(FoundLHS->getType())) { 10953 if (FoundLHS->getType()->isPointerTy()) 10954 return false; 10955 if (CmpInst::isSigned(FoundPred)) { 10956 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10957 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10958 } else { 10959 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10960 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10961 } 10962 } 10963 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10964 FoundRHS, CtxI); 10965 } 10966 10967 bool ScalarEvolution::isImpliedCondBalancedTypes( 10968 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10969 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10970 const Instruction *CtxI) { 10971 assert(getTypeSizeInBits(LHS->getType()) == 10972 getTypeSizeInBits(FoundLHS->getType()) && 10973 "Types should be balanced!"); 10974 // Canonicalize the query to match the way instcombine will have 10975 // canonicalized the comparison. 10976 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10977 if (LHS == RHS) 10978 return CmpInst::isTrueWhenEqual(Pred); 10979 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10980 if (FoundLHS == FoundRHS) 10981 return CmpInst::isFalseWhenEqual(FoundPred); 10982 10983 // Check to see if we can make the LHS or RHS match. 10984 if (LHS == FoundRHS || RHS == FoundLHS) { 10985 if (isa<SCEVConstant>(RHS)) { 10986 std::swap(FoundLHS, FoundRHS); 10987 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10988 } else { 10989 std::swap(LHS, RHS); 10990 Pred = ICmpInst::getSwappedPredicate(Pred); 10991 } 10992 } 10993 10994 // Check whether the found predicate is the same as the desired predicate. 10995 if (FoundPred == Pred) 10996 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 10997 10998 // Check whether swapping the found predicate makes it the same as the 10999 // desired predicate. 11000 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 11001 // We can write the implication 11002 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 11003 // using one of the following ways: 11004 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 11005 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 11006 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 11007 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 11008 // Forms 1. and 2. require swapping the operands of one condition. Don't 11009 // do this if it would break canonical constant/addrec ordering. 11010 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 11011 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 11012 CtxI); 11013 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 11014 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI); 11015 11016 // There's no clear preference between forms 3. and 4., try both. Avoid 11017 // forming getNotSCEV of pointer values as the resulting subtract is 11018 // not legal. 11019 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() && 11020 isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 11021 FoundLHS, FoundRHS, CtxI)) 11022 return true; 11023 11024 if (!FoundLHS->getType()->isPointerTy() && 11025 !FoundRHS->getType()->isPointerTy() && 11026 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 11027 getNotSCEV(FoundRHS), CtxI)) 11028 return true; 11029 11030 return false; 11031 } 11032 11033 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1, 11034 CmpInst::Predicate P2) { 11035 assert(P1 != P2 && "Handled earlier!"); 11036 return CmpInst::isRelational(P2) && 11037 P1 == CmpInst::getFlippedSignednessPredicate(P2); 11038 }; 11039 if (IsSignFlippedPredicate(Pred, FoundPred)) { 11040 // Unsigned comparison is the same as signed comparison when both the 11041 // operands are non-negative or negative. 11042 if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) || 11043 (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS))) 11044 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 11045 // Create local copies that we can freely swap and canonicalize our 11046 // conditions to "le/lt". 11047 ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred; 11048 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS, 11049 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS; 11050 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) { 11051 CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred); 11052 CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred); 11053 std::swap(CanonicalLHS, CanonicalRHS); 11054 std::swap(CanonicalFoundLHS, CanonicalFoundRHS); 11055 } 11056 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) && 11057 "Must be!"); 11058 assert((ICmpInst::isLT(CanonicalFoundPred) || 11059 ICmpInst::isLE(CanonicalFoundPred)) && 11060 "Must be!"); 11061 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS)) 11062 // Use implication: 11063 // x <u y && y >=s 0 --> x <s y. 11064 // If we can prove the left part, the right part is also proven. 11065 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 11066 CanonicalRHS, CanonicalFoundLHS, 11067 CanonicalFoundRHS); 11068 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS)) 11069 // Use implication: 11070 // x <s y && y <s 0 --> x <u y. 11071 // If we can prove the left part, the right part is also proven. 11072 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 11073 CanonicalRHS, CanonicalFoundLHS, 11074 CanonicalFoundRHS); 11075 } 11076 11077 // Check if we can make progress by sharpening ranges. 11078 if (FoundPred == ICmpInst::ICMP_NE && 11079 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 11080 11081 const SCEVConstant *C = nullptr; 11082 const SCEV *V = nullptr; 11083 11084 if (isa<SCEVConstant>(FoundLHS)) { 11085 C = cast<SCEVConstant>(FoundLHS); 11086 V = FoundRHS; 11087 } else { 11088 C = cast<SCEVConstant>(FoundRHS); 11089 V = FoundLHS; 11090 } 11091 11092 // The guarding predicate tells us that C != V. If the known range 11093 // of V is [C, t), we can sharpen the range to [C + 1, t). The 11094 // range we consider has to correspond to same signedness as the 11095 // predicate we're interested in folding. 11096 11097 APInt Min = ICmpInst::isSigned(Pred) ? 11098 getSignedRangeMin(V) : getUnsignedRangeMin(V); 11099 11100 if (Min == C->getAPInt()) { 11101 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 11102 // This is true even if (Min + 1) wraps around -- in case of 11103 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 11104 11105 APInt SharperMin = Min + 1; 11106 11107 switch (Pred) { 11108 case ICmpInst::ICMP_SGE: 11109 case ICmpInst::ICMP_UGE: 11110 // We know V `Pred` SharperMin. If this implies LHS `Pred` 11111 // RHS, we're done. 11112 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 11113 CtxI)) 11114 return true; 11115 LLVM_FALLTHROUGH; 11116 11117 case ICmpInst::ICMP_SGT: 11118 case ICmpInst::ICMP_UGT: 11119 // We know from the range information that (V `Pred` Min || 11120 // V == Min). We know from the guarding condition that !(V 11121 // == Min). This gives us 11122 // 11123 // V `Pred` Min || V == Min && !(V == Min) 11124 // => V `Pred` Min 11125 // 11126 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 11127 11128 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI)) 11129 return true; 11130 break; 11131 11132 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 11133 case ICmpInst::ICMP_SLE: 11134 case ICmpInst::ICMP_ULE: 11135 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 11136 LHS, V, getConstant(SharperMin), CtxI)) 11137 return true; 11138 LLVM_FALLTHROUGH; 11139 11140 case ICmpInst::ICMP_SLT: 11141 case ICmpInst::ICMP_ULT: 11142 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 11143 LHS, V, getConstant(Min), CtxI)) 11144 return true; 11145 break; 11146 11147 default: 11148 // No change 11149 break; 11150 } 11151 } 11152 } 11153 11154 // Check whether the actual condition is beyond sufficient. 11155 if (FoundPred == ICmpInst::ICMP_EQ) 11156 if (ICmpInst::isTrueWhenEqual(Pred)) 11157 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 11158 return true; 11159 if (Pred == ICmpInst::ICMP_NE) 11160 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 11161 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 11162 return true; 11163 11164 // Otherwise assume the worst. 11165 return false; 11166 } 11167 11168 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 11169 const SCEV *&L, const SCEV *&R, 11170 SCEV::NoWrapFlags &Flags) { 11171 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 11172 if (!AE || AE->getNumOperands() != 2) 11173 return false; 11174 11175 L = AE->getOperand(0); 11176 R = AE->getOperand(1); 11177 Flags = AE->getNoWrapFlags(); 11178 return true; 11179 } 11180 11181 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 11182 const SCEV *Less) { 11183 // We avoid subtracting expressions here because this function is usually 11184 // fairly deep in the call stack (i.e. is called many times). 11185 11186 // X - X = 0. 11187 if (More == Less) 11188 return APInt(getTypeSizeInBits(More->getType()), 0); 11189 11190 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 11191 const auto *LAR = cast<SCEVAddRecExpr>(Less); 11192 const auto *MAR = cast<SCEVAddRecExpr>(More); 11193 11194 if (LAR->getLoop() != MAR->getLoop()) 11195 return None; 11196 11197 // We look at affine expressions only; not for correctness but to keep 11198 // getStepRecurrence cheap. 11199 if (!LAR->isAffine() || !MAR->isAffine()) 11200 return None; 11201 11202 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 11203 return None; 11204 11205 Less = LAR->getStart(); 11206 More = MAR->getStart(); 11207 11208 // fall through 11209 } 11210 11211 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 11212 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 11213 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 11214 return M - L; 11215 } 11216 11217 SCEV::NoWrapFlags Flags; 11218 const SCEV *LLess = nullptr, *RLess = nullptr; 11219 const SCEV *LMore = nullptr, *RMore = nullptr; 11220 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 11221 // Compare (X + C1) vs X. 11222 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 11223 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 11224 if (RLess == More) 11225 return -(C1->getAPInt()); 11226 11227 // Compare X vs (X + C2). 11228 if (splitBinaryAdd(More, LMore, RMore, Flags)) 11229 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 11230 if (RMore == Less) 11231 return C2->getAPInt(); 11232 11233 // Compare (X + C1) vs (X + C2). 11234 if (C1 && C2 && RLess == RMore) 11235 return C2->getAPInt() - C1->getAPInt(); 11236 11237 return None; 11238 } 11239 11240 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 11241 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 11242 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) { 11243 // Try to recognize the following pattern: 11244 // 11245 // FoundRHS = ... 11246 // ... 11247 // loop: 11248 // FoundLHS = {Start,+,W} 11249 // context_bb: // Basic block from the same loop 11250 // known(Pred, FoundLHS, FoundRHS) 11251 // 11252 // If some predicate is known in the context of a loop, it is also known on 11253 // each iteration of this loop, including the first iteration. Therefore, in 11254 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 11255 // prove the original pred using this fact. 11256 if (!CtxI) 11257 return false; 11258 const BasicBlock *ContextBB = CtxI->getParent(); 11259 // Make sure AR varies in the context block. 11260 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 11261 const Loop *L = AR->getLoop(); 11262 // Make sure that context belongs to the loop and executes on 1st iteration 11263 // (if it ever executes at all). 11264 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 11265 return false; 11266 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 11267 return false; 11268 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 11269 } 11270 11271 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 11272 const Loop *L = AR->getLoop(); 11273 // Make sure that context belongs to the loop and executes on 1st iteration 11274 // (if it ever executes at all). 11275 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 11276 return false; 11277 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 11278 return false; 11279 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 11280 } 11281 11282 return false; 11283 } 11284 11285 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 11286 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 11287 const SCEV *FoundLHS, const SCEV *FoundRHS) { 11288 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 11289 return false; 11290 11291 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 11292 if (!AddRecLHS) 11293 return false; 11294 11295 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 11296 if (!AddRecFoundLHS) 11297 return false; 11298 11299 // We'd like to let SCEV reason about control dependencies, so we constrain 11300 // both the inequalities to be about add recurrences on the same loop. This 11301 // way we can use isLoopEntryGuardedByCond later. 11302 11303 const Loop *L = AddRecFoundLHS->getLoop(); 11304 if (L != AddRecLHS->getLoop()) 11305 return false; 11306 11307 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 11308 // 11309 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 11310 // ... (2) 11311 // 11312 // Informal proof for (2), assuming (1) [*]: 11313 // 11314 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 11315 // 11316 // Then 11317 // 11318 // FoundLHS s< FoundRHS s< INT_MIN - C 11319 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 11320 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 11321 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 11322 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 11323 // <=> FoundLHS + C s< FoundRHS + C 11324 // 11325 // [*]: (1) can be proved by ruling out overflow. 11326 // 11327 // [**]: This can be proved by analyzing all the four possibilities: 11328 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 11329 // (A s>= 0, B s>= 0). 11330 // 11331 // Note: 11332 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 11333 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 11334 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 11335 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 11336 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 11337 // C)". 11338 11339 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 11340 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 11341 if (!LDiff || !RDiff || *LDiff != *RDiff) 11342 return false; 11343 11344 if (LDiff->isMinValue()) 11345 return true; 11346 11347 APInt FoundRHSLimit; 11348 11349 if (Pred == CmpInst::ICMP_ULT) { 11350 FoundRHSLimit = -(*RDiff); 11351 } else { 11352 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 11353 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 11354 } 11355 11356 // Try to prove (1) or (2), as needed. 11357 return isAvailableAtLoopEntry(FoundRHS, L) && 11358 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 11359 getConstant(FoundRHSLimit)); 11360 } 11361 11362 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 11363 const SCEV *LHS, const SCEV *RHS, 11364 const SCEV *FoundLHS, 11365 const SCEV *FoundRHS, unsigned Depth) { 11366 const PHINode *LPhi = nullptr, *RPhi = nullptr; 11367 11368 auto ClearOnExit = make_scope_exit([&]() { 11369 if (LPhi) { 11370 bool Erased = PendingMerges.erase(LPhi); 11371 assert(Erased && "Failed to erase LPhi!"); 11372 (void)Erased; 11373 } 11374 if (RPhi) { 11375 bool Erased = PendingMerges.erase(RPhi); 11376 assert(Erased && "Failed to erase RPhi!"); 11377 (void)Erased; 11378 } 11379 }); 11380 11381 // Find respective Phis and check that they are not being pending. 11382 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 11383 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 11384 if (!PendingMerges.insert(Phi).second) 11385 return false; 11386 LPhi = Phi; 11387 } 11388 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 11389 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 11390 // If we detect a loop of Phi nodes being processed by this method, for 11391 // example: 11392 // 11393 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 11394 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 11395 // 11396 // we don't want to deal with a case that complex, so return conservative 11397 // answer false. 11398 if (!PendingMerges.insert(Phi).second) 11399 return false; 11400 RPhi = Phi; 11401 } 11402 11403 // If none of LHS, RHS is a Phi, nothing to do here. 11404 if (!LPhi && !RPhi) 11405 return false; 11406 11407 // If there is a SCEVUnknown Phi we are interested in, make it left. 11408 if (!LPhi) { 11409 std::swap(LHS, RHS); 11410 std::swap(FoundLHS, FoundRHS); 11411 std::swap(LPhi, RPhi); 11412 Pred = ICmpInst::getSwappedPredicate(Pred); 11413 } 11414 11415 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 11416 const BasicBlock *LBB = LPhi->getParent(); 11417 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11418 11419 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 11420 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 11421 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 11422 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 11423 }; 11424 11425 if (RPhi && RPhi->getParent() == LBB) { 11426 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 11427 // If we compare two Phis from the same block, and for each entry block 11428 // the predicate is true for incoming values from this block, then the 11429 // predicate is also true for the Phis. 11430 for (const BasicBlock *IncBB : predecessors(LBB)) { 11431 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11432 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 11433 if (!ProvedEasily(L, R)) 11434 return false; 11435 } 11436 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 11437 // Case two: RHS is also a Phi from the same basic block, and it is an 11438 // AddRec. It means that there is a loop which has both AddRec and Unknown 11439 // PHIs, for it we can compare incoming values of AddRec from above the loop 11440 // and latch with their respective incoming values of LPhi. 11441 // TODO: Generalize to handle loops with many inputs in a header. 11442 if (LPhi->getNumIncomingValues() != 2) return false; 11443 11444 auto *RLoop = RAR->getLoop(); 11445 auto *Predecessor = RLoop->getLoopPredecessor(); 11446 assert(Predecessor && "Loop with AddRec with no predecessor?"); 11447 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 11448 if (!ProvedEasily(L1, RAR->getStart())) 11449 return false; 11450 auto *Latch = RLoop->getLoopLatch(); 11451 assert(Latch && "Loop with AddRec with no latch?"); 11452 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 11453 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 11454 return false; 11455 } else { 11456 // In all other cases go over inputs of LHS and compare each of them to RHS, 11457 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 11458 // At this point RHS is either a non-Phi, or it is a Phi from some block 11459 // different from LBB. 11460 for (const BasicBlock *IncBB : predecessors(LBB)) { 11461 // Check that RHS is available in this block. 11462 if (!dominates(RHS, IncBB)) 11463 return false; 11464 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11465 // Make sure L does not refer to a value from a potentially previous 11466 // iteration of a loop. 11467 if (!properlyDominates(L, IncBB)) 11468 return false; 11469 if (!ProvedEasily(L, RHS)) 11470 return false; 11471 } 11472 } 11473 return true; 11474 } 11475 11476 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 11477 const SCEV *LHS, const SCEV *RHS, 11478 const SCEV *FoundLHS, 11479 const SCEV *FoundRHS, 11480 const Instruction *CtxI) { 11481 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11482 return true; 11483 11484 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11485 return true; 11486 11487 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 11488 CtxI)) 11489 return true; 11490 11491 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 11492 FoundLHS, FoundRHS); 11493 } 11494 11495 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 11496 template <typename MinMaxExprType> 11497 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 11498 const SCEV *Candidate) { 11499 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 11500 if (!MinMaxExpr) 11501 return false; 11502 11503 return is_contained(MinMaxExpr->operands(), Candidate); 11504 } 11505 11506 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 11507 ICmpInst::Predicate Pred, 11508 const SCEV *LHS, const SCEV *RHS) { 11509 // If both sides are affine addrecs for the same loop, with equal 11510 // steps, and we know the recurrences don't wrap, then we only 11511 // need to check the predicate on the starting values. 11512 11513 if (!ICmpInst::isRelational(Pred)) 11514 return false; 11515 11516 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 11517 if (!LAR) 11518 return false; 11519 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11520 if (!RAR) 11521 return false; 11522 if (LAR->getLoop() != RAR->getLoop()) 11523 return false; 11524 if (!LAR->isAffine() || !RAR->isAffine()) 11525 return false; 11526 11527 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 11528 return false; 11529 11530 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 11531 SCEV::FlagNSW : SCEV::FlagNUW; 11532 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 11533 return false; 11534 11535 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 11536 } 11537 11538 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 11539 /// expression? 11540 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 11541 ICmpInst::Predicate Pred, 11542 const SCEV *LHS, const SCEV *RHS) { 11543 switch (Pred) { 11544 default: 11545 return false; 11546 11547 case ICmpInst::ICMP_SGE: 11548 std::swap(LHS, RHS); 11549 LLVM_FALLTHROUGH; 11550 case ICmpInst::ICMP_SLE: 11551 return 11552 // min(A, ...) <= A 11553 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 11554 // A <= max(A, ...) 11555 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 11556 11557 case ICmpInst::ICMP_UGE: 11558 std::swap(LHS, RHS); 11559 LLVM_FALLTHROUGH; 11560 case ICmpInst::ICMP_ULE: 11561 return 11562 // min(A, ...) <= A 11563 // FIXME: what about umin_seq? 11564 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 11565 // A <= max(A, ...) 11566 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 11567 } 11568 11569 llvm_unreachable("covered switch fell through?!"); 11570 } 11571 11572 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 11573 const SCEV *LHS, const SCEV *RHS, 11574 const SCEV *FoundLHS, 11575 const SCEV *FoundRHS, 11576 unsigned Depth) { 11577 assert(getTypeSizeInBits(LHS->getType()) == 11578 getTypeSizeInBits(RHS->getType()) && 11579 "LHS and RHS have different sizes?"); 11580 assert(getTypeSizeInBits(FoundLHS->getType()) == 11581 getTypeSizeInBits(FoundRHS->getType()) && 11582 "FoundLHS and FoundRHS have different sizes?"); 11583 // We want to avoid hurting the compile time with analysis of too big trees. 11584 if (Depth > MaxSCEVOperationsImplicationDepth) 11585 return false; 11586 11587 // We only want to work with GT comparison so far. 11588 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 11589 Pred = CmpInst::getSwappedPredicate(Pred); 11590 std::swap(LHS, RHS); 11591 std::swap(FoundLHS, FoundRHS); 11592 } 11593 11594 // For unsigned, try to reduce it to corresponding signed comparison. 11595 if (Pred == ICmpInst::ICMP_UGT) 11596 // We can replace unsigned predicate with its signed counterpart if all 11597 // involved values are non-negative. 11598 // TODO: We could have better support for unsigned. 11599 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 11600 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 11601 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 11602 // use this fact to prove that LHS and RHS are non-negative. 11603 const SCEV *MinusOne = getMinusOne(LHS->getType()); 11604 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 11605 FoundRHS) && 11606 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 11607 FoundRHS)) 11608 Pred = ICmpInst::ICMP_SGT; 11609 } 11610 11611 if (Pred != ICmpInst::ICMP_SGT) 11612 return false; 11613 11614 auto GetOpFromSExt = [&](const SCEV *S) { 11615 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 11616 return Ext->getOperand(); 11617 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 11618 // the constant in some cases. 11619 return S; 11620 }; 11621 11622 // Acquire values from extensions. 11623 auto *OrigLHS = LHS; 11624 auto *OrigFoundLHS = FoundLHS; 11625 LHS = GetOpFromSExt(LHS); 11626 FoundLHS = GetOpFromSExt(FoundLHS); 11627 11628 // Is the SGT predicate can be proved trivially or using the found context. 11629 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 11630 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 11631 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 11632 FoundRHS, Depth + 1); 11633 }; 11634 11635 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 11636 // We want to avoid creation of any new non-constant SCEV. Since we are 11637 // going to compare the operands to RHS, we should be certain that we don't 11638 // need any size extensions for this. So let's decline all cases when the 11639 // sizes of types of LHS and RHS do not match. 11640 // TODO: Maybe try to get RHS from sext to catch more cases? 11641 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11642 return false; 11643 11644 // Should not overflow. 11645 if (!LHSAddExpr->hasNoSignedWrap()) 11646 return false; 11647 11648 auto *LL = LHSAddExpr->getOperand(0); 11649 auto *LR = LHSAddExpr->getOperand(1); 11650 auto *MinusOne = getMinusOne(RHS->getType()); 11651 11652 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11653 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11654 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11655 }; 11656 // Try to prove the following rule: 11657 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11658 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11659 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11660 return true; 11661 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11662 Value *LL, *LR; 11663 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11664 11665 using namespace llvm::PatternMatch; 11666 11667 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11668 // Rules for division. 11669 // We are going to perform some comparisons with Denominator and its 11670 // derivative expressions. In general case, creating a SCEV for it may 11671 // lead to a complex analysis of the entire graph, and in particular it 11672 // can request trip count recalculation for the same loop. This would 11673 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11674 // this, we only want to create SCEVs that are constants in this section. 11675 // So we bail if Denominator is not a constant. 11676 if (!isa<ConstantInt>(LR)) 11677 return false; 11678 11679 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11680 11681 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11682 // then a SCEV for the numerator already exists and matches with FoundLHS. 11683 auto *Numerator = getExistingSCEV(LL); 11684 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11685 return false; 11686 11687 // Make sure that the numerator matches with FoundLHS and the denominator 11688 // is positive. 11689 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11690 return false; 11691 11692 auto *DTy = Denominator->getType(); 11693 auto *FRHSTy = FoundRHS->getType(); 11694 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11695 // One of types is a pointer and another one is not. We cannot extend 11696 // them properly to a wider type, so let us just reject this case. 11697 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11698 // to avoid this check. 11699 return false; 11700 11701 // Given that: 11702 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11703 auto *WTy = getWiderType(DTy, FRHSTy); 11704 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11705 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11706 11707 // Try to prove the following rule: 11708 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11709 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11710 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11711 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11712 if (isKnownNonPositive(RHS) && 11713 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11714 return true; 11715 11716 // Try to prove the following rule: 11717 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11718 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11719 // If we divide it by Denominator > 2, then: 11720 // 1. If FoundLHS is negative, then the result is 0. 11721 // 2. If FoundLHS is non-negative, then the result is non-negative. 11722 // Anyways, the result is non-negative. 11723 auto *MinusOne = getMinusOne(WTy); 11724 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11725 if (isKnownNegative(RHS) && 11726 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11727 return true; 11728 } 11729 } 11730 11731 // If our expression contained SCEVUnknown Phis, and we split it down and now 11732 // need to prove something for them, try to prove the predicate for every 11733 // possible incoming values of those Phis. 11734 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11735 return true; 11736 11737 return false; 11738 } 11739 11740 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11741 const SCEV *LHS, const SCEV *RHS) { 11742 // zext x u<= sext x, sext x s<= zext x 11743 switch (Pred) { 11744 case ICmpInst::ICMP_SGE: 11745 std::swap(LHS, RHS); 11746 LLVM_FALLTHROUGH; 11747 case ICmpInst::ICMP_SLE: { 11748 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11749 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11750 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11751 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11752 return true; 11753 break; 11754 } 11755 case ICmpInst::ICMP_UGE: 11756 std::swap(LHS, RHS); 11757 LLVM_FALLTHROUGH; 11758 case ICmpInst::ICMP_ULE: { 11759 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11760 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11761 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11762 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11763 return true; 11764 break; 11765 } 11766 default: 11767 break; 11768 }; 11769 return false; 11770 } 11771 11772 bool 11773 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 11774 const SCEV *LHS, const SCEV *RHS) { 11775 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 11776 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 11777 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 11778 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 11779 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 11780 } 11781 11782 bool 11783 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 11784 const SCEV *LHS, const SCEV *RHS, 11785 const SCEV *FoundLHS, 11786 const SCEV *FoundRHS) { 11787 switch (Pred) { 11788 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 11789 case ICmpInst::ICMP_EQ: 11790 case ICmpInst::ICMP_NE: 11791 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 11792 return true; 11793 break; 11794 case ICmpInst::ICMP_SLT: 11795 case ICmpInst::ICMP_SLE: 11796 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 11797 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 11798 return true; 11799 break; 11800 case ICmpInst::ICMP_SGT: 11801 case ICmpInst::ICMP_SGE: 11802 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 11803 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 11804 return true; 11805 break; 11806 case ICmpInst::ICMP_ULT: 11807 case ICmpInst::ICMP_ULE: 11808 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 11809 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 11810 return true; 11811 break; 11812 case ICmpInst::ICMP_UGT: 11813 case ICmpInst::ICMP_UGE: 11814 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 11815 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 11816 return true; 11817 break; 11818 } 11819 11820 // Maybe it can be proved via operations? 11821 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11822 return true; 11823 11824 return false; 11825 } 11826 11827 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 11828 const SCEV *LHS, 11829 const SCEV *RHS, 11830 const SCEV *FoundLHS, 11831 const SCEV *FoundRHS) { 11832 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 11833 // The restriction on `FoundRHS` be lifted easily -- it exists only to 11834 // reduce the compile time impact of this optimization. 11835 return false; 11836 11837 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 11838 if (!Addend) 11839 return false; 11840 11841 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 11842 11843 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 11844 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 11845 ConstantRange FoundLHSRange = 11846 ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS); 11847 11848 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 11849 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 11850 11851 // We can also compute the range of values for `LHS` that satisfy the 11852 // consequent, "`LHS` `Pred` `RHS`": 11853 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 11854 // The antecedent implies the consequent if every value of `LHS` that 11855 // satisfies the antecedent also satisfies the consequent. 11856 return LHSRange.icmp(Pred, ConstRHS); 11857 } 11858 11859 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 11860 bool IsSigned) { 11861 assert(isKnownPositive(Stride) && "Positive stride expected!"); 11862 11863 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11864 const SCEV *One = getOne(Stride->getType()); 11865 11866 if (IsSigned) { 11867 APInt MaxRHS = getSignedRangeMax(RHS); 11868 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11869 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11870 11871 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11872 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11873 } 11874 11875 APInt MaxRHS = getUnsignedRangeMax(RHS); 11876 APInt MaxValue = APInt::getMaxValue(BitWidth); 11877 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11878 11879 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11880 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11881 } 11882 11883 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11884 bool IsSigned) { 11885 11886 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11887 const SCEV *One = getOne(Stride->getType()); 11888 11889 if (IsSigned) { 11890 APInt MinRHS = getSignedRangeMin(RHS); 11891 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11892 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11893 11894 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11895 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11896 } 11897 11898 APInt MinRHS = getUnsignedRangeMin(RHS); 11899 APInt MinValue = APInt::getMinValue(BitWidth); 11900 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11901 11902 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11903 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11904 } 11905 11906 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) { 11907 // umin(N, 1) + floor((N - umin(N, 1)) / D) 11908 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin 11909 // expression fixes the case of N=0. 11910 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType())); 11911 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne); 11912 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D)); 11913 } 11914 11915 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11916 const SCEV *Stride, 11917 const SCEV *End, 11918 unsigned BitWidth, 11919 bool IsSigned) { 11920 // The logic in this function assumes we can represent a positive stride. 11921 // If we can't, the backedge-taken count must be zero. 11922 if (IsSigned && BitWidth == 1) 11923 return getZero(Stride->getType()); 11924 11925 // This code has only been closely audited for negative strides in the 11926 // unsigned comparison case, it may be correct for signed comparison, but 11927 // that needs to be established. 11928 assert((!IsSigned || !isKnownNonPositive(Stride)) && 11929 "Stride is expected strictly positive for signed case!"); 11930 11931 // Calculate the maximum backedge count based on the range of values 11932 // permitted by Start, End, and Stride. 11933 APInt MinStart = 11934 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11935 11936 APInt MinStride = 11937 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11938 11939 // We assume either the stride is positive, or the backedge-taken count 11940 // is zero. So force StrideForMaxBECount to be at least one. 11941 APInt One(BitWidth, 1); 11942 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride) 11943 : APIntOps::umax(One, MinStride); 11944 11945 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11946 : APInt::getMaxValue(BitWidth); 11947 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11948 11949 // Although End can be a MAX expression we estimate MaxEnd considering only 11950 // the case End = RHS of the loop termination condition. This is safe because 11951 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11952 // taken count. 11953 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11954 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11955 11956 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride) 11957 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart) 11958 : APIntOps::umax(MaxEnd, MinStart); 11959 11960 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */, 11961 getConstant(StrideForMaxBECount) /* Step */); 11962 } 11963 11964 ScalarEvolution::ExitLimit 11965 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11966 const Loop *L, bool IsSigned, 11967 bool ControlsExit, bool AllowPredicates) { 11968 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11969 11970 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11971 bool PredicatedIV = false; 11972 11973 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) { 11974 // Can we prove this loop *must* be UB if overflow of IV occurs? 11975 // Reasoning goes as follows: 11976 // * Suppose the IV did self wrap. 11977 // * If Stride evenly divides the iteration space, then once wrap 11978 // occurs, the loop must revisit the same values. 11979 // * We know that RHS is invariant, and that none of those values 11980 // caused this exit to be taken previously. Thus, this exit is 11981 // dynamically dead. 11982 // * If this is the sole exit, then a dead exit implies the loop 11983 // must be infinite if there are no abnormal exits. 11984 // * If the loop were infinite, then it must either not be mustprogress 11985 // or have side effects. Otherwise, it must be UB. 11986 // * It can't (by assumption), be UB so we have contradicted our 11987 // premise and can conclude the IV did not in fact self-wrap. 11988 if (!isLoopInvariant(RHS, L)) 11989 return false; 11990 11991 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 11992 if (!StrideC || !StrideC->getAPInt().isPowerOf2()) 11993 return false; 11994 11995 if (!ControlsExit || !loopHasNoAbnormalExits(L)) 11996 return false; 11997 11998 return loopIsFiniteByAssumption(L); 11999 }; 12000 12001 if (!IV) { 12002 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) { 12003 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand()); 12004 if (AR && AR->getLoop() == L && AR->isAffine()) { 12005 auto canProveNUW = [&]() { 12006 if (!isLoopInvariant(RHS, L)) 12007 return false; 12008 12009 if (!isKnownNonZero(AR->getStepRecurrence(*this))) 12010 // We need the sequence defined by AR to strictly increase in the 12011 // unsigned integer domain for the logic below to hold. 12012 return false; 12013 12014 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType()); 12015 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType()); 12016 // If RHS <=u Limit, then there must exist a value V in the sequence 12017 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and 12018 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned 12019 // overflow occurs. This limit also implies that a signed comparison 12020 // (in the wide bitwidth) is equivalent to an unsigned comparison as 12021 // the high bits on both sides must be zero. 12022 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this)); 12023 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1); 12024 Limit = Limit.zext(OuterBitWidth); 12025 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit); 12026 }; 12027 auto Flags = AR->getNoWrapFlags(); 12028 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW()) 12029 Flags = setFlags(Flags, SCEV::FlagNUW); 12030 12031 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 12032 if (AR->hasNoUnsignedWrap()) { 12033 // Emulate what getZeroExtendExpr would have done during construction 12034 // if we'd been able to infer the fact just above at that time. 12035 const SCEV *Step = AR->getStepRecurrence(*this); 12036 Type *Ty = ZExt->getType(); 12037 auto *S = getAddRecExpr( 12038 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0), 12039 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags()); 12040 IV = dyn_cast<SCEVAddRecExpr>(S); 12041 } 12042 } 12043 } 12044 } 12045 12046 12047 if (!IV && AllowPredicates) { 12048 // Try to make this an AddRec using runtime tests, in the first X 12049 // iterations of this loop, where X is the SCEV expression found by the 12050 // algorithm below. 12051 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12052 PredicatedIV = true; 12053 } 12054 12055 // Avoid weird loops 12056 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12057 return getCouldNotCompute(); 12058 12059 // A precondition of this method is that the condition being analyzed 12060 // reaches an exiting branch which dominates the latch. Given that, we can 12061 // assume that an increment which violates the nowrap specification and 12062 // produces poison must cause undefined behavior when the resulting poison 12063 // value is branched upon and thus we can conclude that the backedge is 12064 // taken no more often than would be required to produce that poison value. 12065 // Note that a well defined loop can exit on the iteration which violates 12066 // the nowrap specification if there is another exit (either explicit or 12067 // implicit/exceptional) which causes the loop to execute before the 12068 // exiting instruction we're analyzing would trigger UB. 12069 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12070 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12071 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 12072 12073 const SCEV *Stride = IV->getStepRecurrence(*this); 12074 12075 bool PositiveStride = isKnownPositive(Stride); 12076 12077 // Avoid negative or zero stride values. 12078 if (!PositiveStride) { 12079 // We can compute the correct backedge taken count for loops with unknown 12080 // strides if we can prove that the loop is not an infinite loop with side 12081 // effects. Here's the loop structure we are trying to handle - 12082 // 12083 // i = start 12084 // do { 12085 // A[i] = i; 12086 // i += s; 12087 // } while (i < end); 12088 // 12089 // The backedge taken count for such loops is evaluated as - 12090 // (max(end, start + stride) - start - 1) /u stride 12091 // 12092 // The additional preconditions that we need to check to prove correctness 12093 // of the above formula is as follows - 12094 // 12095 // a) IV is either nuw or nsw depending upon signedness (indicated by the 12096 // NoWrap flag). 12097 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has 12098 // no side effects within the loop) 12099 // c) loop has a single static exit (with no abnormal exits) 12100 // 12101 // Precondition a) implies that if the stride is negative, this is a single 12102 // trip loop. The backedge taken count formula reduces to zero in this case. 12103 // 12104 // Precondition b) and c) combine to imply that if rhs is invariant in L, 12105 // then a zero stride means the backedge can't be taken without executing 12106 // undefined behavior. 12107 // 12108 // The positive stride case is the same as isKnownPositive(Stride) returning 12109 // true (original behavior of the function). 12110 // 12111 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) || 12112 !loopHasNoAbnormalExits(L)) 12113 return getCouldNotCompute(); 12114 12115 // This bailout is protecting the logic in computeMaxBECountForLT which 12116 // has not yet been sufficiently auditted or tested with negative strides. 12117 // We used to filter out all known-non-positive cases here, we're in the 12118 // process of being less restrictive bit by bit. 12119 if (IsSigned && isKnownNonPositive(Stride)) 12120 return getCouldNotCompute(); 12121 12122 if (!isKnownNonZero(Stride)) { 12123 // If we have a step of zero, and RHS isn't invariant in L, we don't know 12124 // if it might eventually be greater than start and if so, on which 12125 // iteration. We can't even produce a useful upper bound. 12126 if (!isLoopInvariant(RHS, L)) 12127 return getCouldNotCompute(); 12128 12129 // We allow a potentially zero stride, but we need to divide by stride 12130 // below. Since the loop can't be infinite and this check must control 12131 // the sole exit, we can infer the exit must be taken on the first 12132 // iteration (e.g. backedge count = 0) if the stride is zero. Given that, 12133 // we know the numerator in the divides below must be zero, so we can 12134 // pick an arbitrary non-zero value for the denominator (e.g. stride) 12135 // and produce the right result. 12136 // FIXME: Handle the case where Stride is poison? 12137 auto wouldZeroStrideBeUB = [&]() { 12138 // Proof by contradiction. Suppose the stride were zero. If we can 12139 // prove that the backedge *is* taken on the first iteration, then since 12140 // we know this condition controls the sole exit, we must have an 12141 // infinite loop. We can't have a (well defined) infinite loop per 12142 // check just above. 12143 // Note: The (Start - Stride) term is used to get the start' term from 12144 // (start' + stride,+,stride). Remember that we only care about the 12145 // result of this expression when stride == 0 at runtime. 12146 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride); 12147 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS); 12148 }; 12149 if (!wouldZeroStrideBeUB()) { 12150 Stride = getUMaxExpr(Stride, getOne(Stride->getType())); 12151 } 12152 } 12153 } else if (!Stride->isOne() && !NoWrap) { 12154 auto isUBOnWrap = [&]() { 12155 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This 12156 // follows trivially from the fact that every (un)signed-wrapped, but 12157 // not self-wrapped value must be LT than the last value before 12158 // (un)signed wrap. Since we know that last value didn't exit, nor 12159 // will any smaller one. 12160 return canAssumeNoSelfWrap(IV); 12161 }; 12162 12163 // Avoid proven overflow cases: this will ensure that the backedge taken 12164 // count will not generate any unsigned overflow. Relaxed no-overflow 12165 // conditions exploit NoWrapFlags, allowing to optimize in presence of 12166 // undefined behaviors like the case of C language. 12167 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap()) 12168 return getCouldNotCompute(); 12169 } 12170 12171 // On all paths just preceeding, we established the following invariant: 12172 // IV can be assumed not to overflow up to and including the exiting 12173 // iteration. We proved this in one of two ways: 12174 // 1) We can show overflow doesn't occur before the exiting iteration 12175 // 1a) canIVOverflowOnLT, and b) step of one 12176 // 2) We can show that if overflow occurs, the loop must execute UB 12177 // before any possible exit. 12178 // Note that we have not yet proved RHS invariant (in general). 12179 12180 const SCEV *Start = IV->getStart(); 12181 12182 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond. 12183 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases. 12184 // Use integer-typed versions for actual computation; we can't subtract 12185 // pointers in general. 12186 const SCEV *OrigStart = Start; 12187 const SCEV *OrigRHS = RHS; 12188 if (Start->getType()->isPointerTy()) { 12189 Start = getLosslessPtrToIntExpr(Start); 12190 if (isa<SCEVCouldNotCompute>(Start)) 12191 return Start; 12192 } 12193 if (RHS->getType()->isPointerTy()) { 12194 RHS = getLosslessPtrToIntExpr(RHS); 12195 if (isa<SCEVCouldNotCompute>(RHS)) 12196 return RHS; 12197 } 12198 12199 // When the RHS is not invariant, we do not know the end bound of the loop and 12200 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 12201 // calculate the MaxBECount, given the start, stride and max value for the end 12202 // bound of the loop (RHS), and the fact that IV does not overflow (which is 12203 // checked above). 12204 if (!isLoopInvariant(RHS, L)) { 12205 const SCEV *MaxBECount = computeMaxBECountForLT( 12206 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 12207 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 12208 false /*MaxOrZero*/, Predicates); 12209 } 12210 12211 // We use the expression (max(End,Start)-Start)/Stride to describe the 12212 // backedge count, as if the backedge is taken at least once max(End,Start) 12213 // is End and so the result is as above, and if not max(End,Start) is Start 12214 // so we get a backedge count of zero. 12215 const SCEV *BECount = nullptr; 12216 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride); 12217 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!"); 12218 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!"); 12219 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!"); 12220 // Can we prove (max(RHS,Start) > Start - Stride? 12221 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) && 12222 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) { 12223 // In this case, we can use a refined formula for computing backedge taken 12224 // count. The general formula remains: 12225 // "End-Start /uceiling Stride" where "End = max(RHS,Start)" 12226 // We want to use the alternate formula: 12227 // "((End - 1) - (Start - Stride)) /u Stride" 12228 // Let's do a quick case analysis to show these are equivalent under 12229 // our precondition that max(RHS,Start) > Start - Stride. 12230 // * For RHS <= Start, the backedge-taken count must be zero. 12231 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 12232 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to 12233 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values 12234 // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing 12235 // this to the stride of 1 case. 12236 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride". 12237 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 12238 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to 12239 // "((RHS - (Start - Stride) - 1) /u Stride". 12240 // Our preconditions trivially imply no overflow in that form. 12241 const SCEV *MinusOne = getMinusOne(Stride->getType()); 12242 const SCEV *Numerator = 12243 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride)); 12244 BECount = getUDivExpr(Numerator, Stride); 12245 } 12246 12247 const SCEV *BECountIfBackedgeTaken = nullptr; 12248 if (!BECount) { 12249 auto canProveRHSGreaterThanEqualStart = [&]() { 12250 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 12251 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart)) 12252 return true; 12253 12254 // (RHS > Start - 1) implies RHS >= Start. 12255 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if 12256 // "Start - 1" doesn't overflow. 12257 // * For signed comparison, if Start - 1 does overflow, it's equal 12258 // to INT_MAX, and "RHS >s INT_MAX" is trivially false. 12259 // * For unsigned comparison, if Start - 1 does overflow, it's equal 12260 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false. 12261 // 12262 // FIXME: Should isLoopEntryGuardedByCond do this for us? 12263 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12264 auto *StartMinusOne = getAddExpr(OrigStart, 12265 getMinusOne(OrigStart->getType())); 12266 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne); 12267 }; 12268 12269 // If we know that RHS >= Start in the context of loop, then we know that 12270 // max(RHS, Start) = RHS at this point. 12271 const SCEV *End; 12272 if (canProveRHSGreaterThanEqualStart()) { 12273 End = RHS; 12274 } else { 12275 // If RHS < Start, the backedge will be taken zero times. So in 12276 // general, we can write the backedge-taken count as: 12277 // 12278 // RHS >= Start ? ceil(RHS - Start) / Stride : 0 12279 // 12280 // We convert it to the following to make it more convenient for SCEV: 12281 // 12282 // ceil(max(RHS, Start) - Start) / Stride 12283 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 12284 12285 // See what would happen if we assume the backedge is taken. This is 12286 // used to compute MaxBECount. 12287 BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride); 12288 } 12289 12290 // At this point, we know: 12291 // 12292 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End 12293 // 2. The index variable doesn't overflow. 12294 // 12295 // Therefore, we know N exists such that 12296 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)" 12297 // doesn't overflow. 12298 // 12299 // Using this information, try to prove whether the addition in 12300 // "(Start - End) + (Stride - 1)" has unsigned overflow. 12301 const SCEV *One = getOne(Stride->getType()); 12302 bool MayAddOverflow = [&] { 12303 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) { 12304 if (StrideC->getAPInt().isPowerOf2()) { 12305 // Suppose Stride is a power of two, and Start/End are unsigned 12306 // integers. Let UMAX be the largest representable unsigned 12307 // integer. 12308 // 12309 // By the preconditions of this function, we know 12310 // "(Start + Stride * N) >= End", and this doesn't overflow. 12311 // As a formula: 12312 // 12313 // End <= (Start + Stride * N) <= UMAX 12314 // 12315 // Subtracting Start from all the terms: 12316 // 12317 // End - Start <= Stride * N <= UMAX - Start 12318 // 12319 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore: 12320 // 12321 // End - Start <= Stride * N <= UMAX 12322 // 12323 // Stride * N is a multiple of Stride. Therefore, 12324 // 12325 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride) 12326 // 12327 // Since Stride is a power of two, UMAX + 1 is divisible by Stride. 12328 // Therefore, UMAX mod Stride == Stride - 1. So we can write: 12329 // 12330 // End - Start <= Stride * N <= UMAX - Stride - 1 12331 // 12332 // Dropping the middle term: 12333 // 12334 // End - Start <= UMAX - Stride - 1 12335 // 12336 // Adding Stride - 1 to both sides: 12337 // 12338 // (End - Start) + (Stride - 1) <= UMAX 12339 // 12340 // In other words, the addition doesn't have unsigned overflow. 12341 // 12342 // A similar proof works if we treat Start/End as signed values. 12343 // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to 12344 // use signed max instead of unsigned max. Note that we're trying 12345 // to prove a lack of unsigned overflow in either case. 12346 return false; 12347 } 12348 } 12349 if (Start == Stride || Start == getMinusSCEV(Stride, One)) { 12350 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1. 12351 // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End. 12352 // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End. 12353 // 12354 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End. 12355 return false; 12356 } 12357 return true; 12358 }(); 12359 12360 const SCEV *Delta = getMinusSCEV(End, Start); 12361 if (!MayAddOverflow) { 12362 // floor((D + (S - 1)) / S) 12363 // We prefer this formulation if it's legal because it's fewer operations. 12364 BECount = 12365 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride); 12366 } else { 12367 BECount = getUDivCeilSCEV(Delta, Stride); 12368 } 12369 } 12370 12371 const SCEV *MaxBECount; 12372 bool MaxOrZero = false; 12373 if (isa<SCEVConstant>(BECount)) { 12374 MaxBECount = BECount; 12375 } else if (BECountIfBackedgeTaken && 12376 isa<SCEVConstant>(BECountIfBackedgeTaken)) { 12377 // If we know exactly how many times the backedge will be taken if it's 12378 // taken at least once, then the backedge count will either be that or 12379 // zero. 12380 MaxBECount = BECountIfBackedgeTaken; 12381 MaxOrZero = true; 12382 } else { 12383 MaxBECount = computeMaxBECountForLT( 12384 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 12385 } 12386 12387 if (isa<SCEVCouldNotCompute>(MaxBECount) && 12388 !isa<SCEVCouldNotCompute>(BECount)) 12389 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 12390 12391 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 12392 } 12393 12394 ScalarEvolution::ExitLimit 12395 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 12396 const Loop *L, bool IsSigned, 12397 bool ControlsExit, bool AllowPredicates) { 12398 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 12399 // We handle only IV > Invariant 12400 if (!isLoopInvariant(RHS, L)) 12401 return getCouldNotCompute(); 12402 12403 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 12404 if (!IV && AllowPredicates) 12405 // Try to make this an AddRec using runtime tests, in the first X 12406 // iterations of this loop, where X is the SCEV expression found by the 12407 // algorithm below. 12408 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12409 12410 // Avoid weird loops 12411 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12412 return getCouldNotCompute(); 12413 12414 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12415 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12416 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12417 12418 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 12419 12420 // Avoid negative or zero stride values 12421 if (!isKnownPositive(Stride)) 12422 return getCouldNotCompute(); 12423 12424 // Avoid proven overflow cases: this will ensure that the backedge taken count 12425 // will not generate any unsigned overflow. Relaxed no-overflow conditions 12426 // exploit NoWrapFlags, allowing to optimize in presence of undefined 12427 // behaviors like the case of C language. 12428 if (!Stride->isOne() && !NoWrap) 12429 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 12430 return getCouldNotCompute(); 12431 12432 const SCEV *Start = IV->getStart(); 12433 const SCEV *End = RHS; 12434 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 12435 // If we know that Start >= RHS in the context of loop, then we know that 12436 // min(RHS, Start) = RHS at this point. 12437 if (isLoopEntryGuardedByCond( 12438 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 12439 End = RHS; 12440 else 12441 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 12442 } 12443 12444 if (Start->getType()->isPointerTy()) { 12445 Start = getLosslessPtrToIntExpr(Start); 12446 if (isa<SCEVCouldNotCompute>(Start)) 12447 return Start; 12448 } 12449 if (End->getType()->isPointerTy()) { 12450 End = getLosslessPtrToIntExpr(End); 12451 if (isa<SCEVCouldNotCompute>(End)) 12452 return End; 12453 } 12454 12455 // Compute ((Start - End) + (Stride - 1)) / Stride. 12456 // FIXME: This can overflow. Holding off on fixing this for now; 12457 // howManyGreaterThans will hopefully be gone soon. 12458 const SCEV *One = getOne(Stride->getType()); 12459 const SCEV *BECount = getUDivExpr( 12460 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride); 12461 12462 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 12463 : getUnsignedRangeMax(Start); 12464 12465 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 12466 : getUnsignedRangeMin(Stride); 12467 12468 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 12469 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 12470 : APInt::getMinValue(BitWidth) + (MinStride - 1); 12471 12472 // Although End can be a MIN expression we estimate MinEnd considering only 12473 // the case End = RHS. This is safe because in the other case (Start - End) 12474 // is zero, leading to a zero maximum backedge taken count. 12475 APInt MinEnd = 12476 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 12477 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 12478 12479 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 12480 ? BECount 12481 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd), 12482 getConstant(MinStride)); 12483 12484 if (isa<SCEVCouldNotCompute>(MaxBECount)) 12485 MaxBECount = BECount; 12486 12487 return ExitLimit(BECount, MaxBECount, false, Predicates); 12488 } 12489 12490 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 12491 ScalarEvolution &SE) const { 12492 if (Range.isFullSet()) // Infinite loop. 12493 return SE.getCouldNotCompute(); 12494 12495 // If the start is a non-zero constant, shift the range to simplify things. 12496 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 12497 if (!SC->getValue()->isZero()) { 12498 SmallVector<const SCEV *, 4> Operands(operands()); 12499 Operands[0] = SE.getZero(SC->getType()); 12500 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 12501 getNoWrapFlags(FlagNW)); 12502 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 12503 return ShiftedAddRec->getNumIterationsInRange( 12504 Range.subtract(SC->getAPInt()), SE); 12505 // This is strange and shouldn't happen. 12506 return SE.getCouldNotCompute(); 12507 } 12508 12509 // The only time we can solve this is when we have all constant indices. 12510 // Otherwise, we cannot determine the overflow conditions. 12511 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 12512 return SE.getCouldNotCompute(); 12513 12514 // Okay at this point we know that all elements of the chrec are constants and 12515 // that the start element is zero. 12516 12517 // First check to see if the range contains zero. If not, the first 12518 // iteration exits. 12519 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 12520 if (!Range.contains(APInt(BitWidth, 0))) 12521 return SE.getZero(getType()); 12522 12523 if (isAffine()) { 12524 // If this is an affine expression then we have this situation: 12525 // Solve {0,+,A} in Range === Ax in Range 12526 12527 // We know that zero is in the range. If A is positive then we know that 12528 // the upper value of the range must be the first possible exit value. 12529 // If A is negative then the lower of the range is the last possible loop 12530 // value. Also note that we already checked for a full range. 12531 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 12532 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 12533 12534 // The exit value should be (End+A)/A. 12535 APInt ExitVal = (End + A).udiv(A); 12536 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 12537 12538 // Evaluate at the exit value. If we really did fall out of the valid 12539 // range, then we computed our trip count, otherwise wrap around or other 12540 // things must have happened. 12541 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 12542 if (Range.contains(Val->getValue())) 12543 return SE.getCouldNotCompute(); // Something strange happened 12544 12545 // Ensure that the previous value is in the range. 12546 assert(Range.contains( 12547 EvaluateConstantChrecAtConstant(this, 12548 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 12549 "Linear scev computation is off in a bad way!"); 12550 return SE.getConstant(ExitValue); 12551 } 12552 12553 if (isQuadratic()) { 12554 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 12555 return SE.getConstant(S.getValue()); 12556 } 12557 12558 return SE.getCouldNotCompute(); 12559 } 12560 12561 const SCEVAddRecExpr * 12562 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 12563 assert(getNumOperands() > 1 && "AddRec with zero step?"); 12564 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 12565 // but in this case we cannot guarantee that the value returned will be an 12566 // AddRec because SCEV does not have a fixed point where it stops 12567 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 12568 // may happen if we reach arithmetic depth limit while simplifying. So we 12569 // construct the returned value explicitly. 12570 SmallVector<const SCEV *, 3> Ops; 12571 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 12572 // (this + Step) is {A+B,+,B+C,+...,+,N}. 12573 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 12574 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 12575 // We know that the last operand is not a constant zero (otherwise it would 12576 // have been popped out earlier). This guarantees us that if the result has 12577 // the same last operand, then it will also not be popped out, meaning that 12578 // the returned value will be an AddRec. 12579 const SCEV *Last = getOperand(getNumOperands() - 1); 12580 assert(!Last->isZero() && "Recurrency with zero step?"); 12581 Ops.push_back(Last); 12582 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 12583 SCEV::FlagAnyWrap)); 12584 } 12585 12586 // Return true when S contains at least an undef value. 12587 bool ScalarEvolution::containsUndefs(const SCEV *S) const { 12588 return SCEVExprContains(S, [](const SCEV *S) { 12589 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 12590 return isa<UndefValue>(SU->getValue()); 12591 return false; 12592 }); 12593 } 12594 12595 /// Return the size of an element read or written by Inst. 12596 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 12597 Type *Ty; 12598 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 12599 Ty = Store->getValueOperand()->getType(); 12600 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 12601 Ty = Load->getType(); 12602 else 12603 return nullptr; 12604 12605 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 12606 return getSizeOfExpr(ETy, Ty); 12607 } 12608 12609 //===----------------------------------------------------------------------===// 12610 // SCEVCallbackVH Class Implementation 12611 //===----------------------------------------------------------------------===// 12612 12613 void ScalarEvolution::SCEVCallbackVH::deleted() { 12614 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12615 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12616 SE->ConstantEvolutionLoopExitValue.erase(PN); 12617 SE->eraseValueFromMap(getValPtr()); 12618 // this now dangles! 12619 } 12620 12621 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12622 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12623 12624 // Forget all the expressions associated with users of the old value, 12625 // so that future queries will recompute the expressions using the new 12626 // value. 12627 Value *Old = getValPtr(); 12628 SmallVector<User *, 16> Worklist(Old->users()); 12629 SmallPtrSet<User *, 8> Visited; 12630 while (!Worklist.empty()) { 12631 User *U = Worklist.pop_back_val(); 12632 // Deleting the Old value will cause this to dangle. Postpone 12633 // that until everything else is done. 12634 if (U == Old) 12635 continue; 12636 if (!Visited.insert(U).second) 12637 continue; 12638 if (PHINode *PN = dyn_cast<PHINode>(U)) 12639 SE->ConstantEvolutionLoopExitValue.erase(PN); 12640 SE->eraseValueFromMap(U); 12641 llvm::append_range(Worklist, U->users()); 12642 } 12643 // Delete the Old value. 12644 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12645 SE->ConstantEvolutionLoopExitValue.erase(PN); 12646 SE->eraseValueFromMap(Old); 12647 // this now dangles! 12648 } 12649 12650 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12651 : CallbackVH(V), SE(se) {} 12652 12653 //===----------------------------------------------------------------------===// 12654 // ScalarEvolution Class Implementation 12655 //===----------------------------------------------------------------------===// 12656 12657 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12658 AssumptionCache &AC, DominatorTree &DT, 12659 LoopInfo &LI) 12660 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12661 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12662 LoopDispositions(64), BlockDispositions(64) { 12663 // To use guards for proving predicates, we need to scan every instruction in 12664 // relevant basic blocks, and not just terminators. Doing this is a waste of 12665 // time if the IR does not actually contain any calls to 12666 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12667 // 12668 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12669 // to _add_ guards to the module when there weren't any before, and wants 12670 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12671 // efficient in lieu of being smart in that rather obscure case. 12672 12673 auto *GuardDecl = F.getParent()->getFunction( 12674 Intrinsic::getName(Intrinsic::experimental_guard)); 12675 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12676 } 12677 12678 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12679 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12680 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12681 ValueExprMap(std::move(Arg.ValueExprMap)), 12682 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12683 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12684 PendingMerges(std::move(Arg.PendingMerges)), 12685 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12686 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12687 PredicatedBackedgeTakenCounts( 12688 std::move(Arg.PredicatedBackedgeTakenCounts)), 12689 BECountUsers(std::move(Arg.BECountUsers)), 12690 ConstantEvolutionLoopExitValue( 12691 std::move(Arg.ConstantEvolutionLoopExitValue)), 12692 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12693 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)), 12694 LoopDispositions(std::move(Arg.LoopDispositions)), 12695 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12696 BlockDispositions(std::move(Arg.BlockDispositions)), 12697 SCEVUsers(std::move(Arg.SCEVUsers)), 12698 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12699 SignedRanges(std::move(Arg.SignedRanges)), 12700 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12701 UniquePreds(std::move(Arg.UniquePreds)), 12702 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12703 LoopUsers(std::move(Arg.LoopUsers)), 12704 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12705 FirstUnknown(Arg.FirstUnknown) { 12706 Arg.FirstUnknown = nullptr; 12707 } 12708 12709 ScalarEvolution::~ScalarEvolution() { 12710 // Iterate through all the SCEVUnknown instances and call their 12711 // destructors, so that they release their references to their values. 12712 for (SCEVUnknown *U = FirstUnknown; U;) { 12713 SCEVUnknown *Tmp = U; 12714 U = U->Next; 12715 Tmp->~SCEVUnknown(); 12716 } 12717 FirstUnknown = nullptr; 12718 12719 ExprValueMap.clear(); 12720 ValueExprMap.clear(); 12721 HasRecMap.clear(); 12722 BackedgeTakenCounts.clear(); 12723 PredicatedBackedgeTakenCounts.clear(); 12724 12725 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12726 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12727 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12728 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12729 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12730 } 12731 12732 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12733 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12734 } 12735 12736 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12737 const Loop *L) { 12738 // Print all inner loops first 12739 for (Loop *I : *L) 12740 PrintLoopInfo(OS, SE, I); 12741 12742 OS << "Loop "; 12743 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12744 OS << ": "; 12745 12746 SmallVector<BasicBlock *, 8> ExitingBlocks; 12747 L->getExitingBlocks(ExitingBlocks); 12748 if (ExitingBlocks.size() != 1) 12749 OS << "<multiple exits> "; 12750 12751 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12752 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12753 else 12754 OS << "Unpredictable backedge-taken count.\n"; 12755 12756 if (ExitingBlocks.size() > 1) 12757 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12758 OS << " exit count for " << ExitingBlock->getName() << ": " 12759 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12760 } 12761 12762 OS << "Loop "; 12763 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12764 OS << ": "; 12765 12766 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12767 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12768 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12769 OS << ", actual taken count either this or zero."; 12770 } else { 12771 OS << "Unpredictable max backedge-taken count. "; 12772 } 12773 12774 OS << "\n" 12775 "Loop "; 12776 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12777 OS << ": "; 12778 12779 SCEVUnionPredicate Pred; 12780 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12781 if (!isa<SCEVCouldNotCompute>(PBT)) { 12782 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12783 OS << " Predicates:\n"; 12784 Pred.print(OS, 4); 12785 } else { 12786 OS << "Unpredictable predicated backedge-taken count. "; 12787 } 12788 OS << "\n"; 12789 12790 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12791 OS << "Loop "; 12792 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12793 OS << ": "; 12794 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12795 } 12796 } 12797 12798 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12799 switch (LD) { 12800 case ScalarEvolution::LoopVariant: 12801 return "Variant"; 12802 case ScalarEvolution::LoopInvariant: 12803 return "Invariant"; 12804 case ScalarEvolution::LoopComputable: 12805 return "Computable"; 12806 } 12807 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12808 } 12809 12810 void ScalarEvolution::print(raw_ostream &OS) const { 12811 // ScalarEvolution's implementation of the print method is to print 12812 // out SCEV values of all instructions that are interesting. Doing 12813 // this potentially causes it to create new SCEV objects though, 12814 // which technically conflicts with the const qualifier. This isn't 12815 // observable from outside the class though, so casting away the 12816 // const isn't dangerous. 12817 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12818 12819 if (ClassifyExpressions) { 12820 OS << "Classifying expressions for: "; 12821 F.printAsOperand(OS, /*PrintType=*/false); 12822 OS << "\n"; 12823 for (Instruction &I : instructions(F)) 12824 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12825 OS << I << '\n'; 12826 OS << " --> "; 12827 const SCEV *SV = SE.getSCEV(&I); 12828 SV->print(OS); 12829 if (!isa<SCEVCouldNotCompute>(SV)) { 12830 OS << " U: "; 12831 SE.getUnsignedRange(SV).print(OS); 12832 OS << " S: "; 12833 SE.getSignedRange(SV).print(OS); 12834 } 12835 12836 const Loop *L = LI.getLoopFor(I.getParent()); 12837 12838 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12839 if (AtUse != SV) { 12840 OS << " --> "; 12841 AtUse->print(OS); 12842 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12843 OS << " U: "; 12844 SE.getUnsignedRange(AtUse).print(OS); 12845 OS << " S: "; 12846 SE.getSignedRange(AtUse).print(OS); 12847 } 12848 } 12849 12850 if (L) { 12851 OS << "\t\t" "Exits: "; 12852 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12853 if (!SE.isLoopInvariant(ExitValue, L)) { 12854 OS << "<<Unknown>>"; 12855 } else { 12856 OS << *ExitValue; 12857 } 12858 12859 bool First = true; 12860 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12861 if (First) { 12862 OS << "\t\t" "LoopDispositions: { "; 12863 First = false; 12864 } else { 12865 OS << ", "; 12866 } 12867 12868 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12869 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12870 } 12871 12872 for (auto *InnerL : depth_first(L)) { 12873 if (InnerL == L) 12874 continue; 12875 if (First) { 12876 OS << "\t\t" "LoopDispositions: { "; 12877 First = false; 12878 } else { 12879 OS << ", "; 12880 } 12881 12882 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12883 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12884 } 12885 12886 OS << " }"; 12887 } 12888 12889 OS << "\n"; 12890 } 12891 } 12892 12893 OS << "Determining loop execution counts for: "; 12894 F.printAsOperand(OS, /*PrintType=*/false); 12895 OS << "\n"; 12896 for (Loop *I : LI) 12897 PrintLoopInfo(OS, &SE, I); 12898 } 12899 12900 ScalarEvolution::LoopDisposition 12901 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12902 auto &Values = LoopDispositions[S]; 12903 for (auto &V : Values) { 12904 if (V.getPointer() == L) 12905 return V.getInt(); 12906 } 12907 Values.emplace_back(L, LoopVariant); 12908 LoopDisposition D = computeLoopDisposition(S, L); 12909 auto &Values2 = LoopDispositions[S]; 12910 for (auto &V : llvm::reverse(Values2)) { 12911 if (V.getPointer() == L) { 12912 V.setInt(D); 12913 break; 12914 } 12915 } 12916 return D; 12917 } 12918 12919 ScalarEvolution::LoopDisposition 12920 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12921 switch (S->getSCEVType()) { 12922 case scConstant: 12923 return LoopInvariant; 12924 case scPtrToInt: 12925 case scTruncate: 12926 case scZeroExtend: 12927 case scSignExtend: 12928 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12929 case scAddRecExpr: { 12930 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12931 12932 // If L is the addrec's loop, it's computable. 12933 if (AR->getLoop() == L) 12934 return LoopComputable; 12935 12936 // Add recurrences are never invariant in the function-body (null loop). 12937 if (!L) 12938 return LoopVariant; 12939 12940 // Everything that is not defined at loop entry is variant. 12941 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12942 return LoopVariant; 12943 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12944 " dominate the contained loop's header?"); 12945 12946 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12947 if (AR->getLoop()->contains(L)) 12948 return LoopInvariant; 12949 12950 // This recurrence is variant w.r.t. L if any of its operands 12951 // are variant. 12952 for (auto *Op : AR->operands()) 12953 if (!isLoopInvariant(Op, L)) 12954 return LoopVariant; 12955 12956 // Otherwise it's loop-invariant. 12957 return LoopInvariant; 12958 } 12959 case scAddExpr: 12960 case scMulExpr: 12961 case scUMaxExpr: 12962 case scSMaxExpr: 12963 case scUMinExpr: 12964 case scSMinExpr: 12965 case scSequentialUMinExpr: { 12966 bool HasVarying = false; 12967 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12968 LoopDisposition D = getLoopDisposition(Op, L); 12969 if (D == LoopVariant) 12970 return LoopVariant; 12971 if (D == LoopComputable) 12972 HasVarying = true; 12973 } 12974 return HasVarying ? LoopComputable : LoopInvariant; 12975 } 12976 case scUDivExpr: { 12977 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12978 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12979 if (LD == LoopVariant) 12980 return LoopVariant; 12981 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12982 if (RD == LoopVariant) 12983 return LoopVariant; 12984 return (LD == LoopInvariant && RD == LoopInvariant) ? 12985 LoopInvariant : LoopComputable; 12986 } 12987 case scUnknown: 12988 // All non-instruction values are loop invariant. All instructions are loop 12989 // invariant if they are not contained in the specified loop. 12990 // Instructions are never considered invariant in the function body 12991 // (null loop) because they are defined within the "loop". 12992 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12993 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12994 return LoopInvariant; 12995 case scCouldNotCompute: 12996 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12997 } 12998 llvm_unreachable("Unknown SCEV kind!"); 12999 } 13000 13001 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 13002 return getLoopDisposition(S, L) == LoopInvariant; 13003 } 13004 13005 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 13006 return getLoopDisposition(S, L) == LoopComputable; 13007 } 13008 13009 ScalarEvolution::BlockDisposition 13010 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 13011 auto &Values = BlockDispositions[S]; 13012 for (auto &V : Values) { 13013 if (V.getPointer() == BB) 13014 return V.getInt(); 13015 } 13016 Values.emplace_back(BB, DoesNotDominateBlock); 13017 BlockDisposition D = computeBlockDisposition(S, BB); 13018 auto &Values2 = BlockDispositions[S]; 13019 for (auto &V : llvm::reverse(Values2)) { 13020 if (V.getPointer() == BB) { 13021 V.setInt(D); 13022 break; 13023 } 13024 } 13025 return D; 13026 } 13027 13028 ScalarEvolution::BlockDisposition 13029 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 13030 switch (S->getSCEVType()) { 13031 case scConstant: 13032 return ProperlyDominatesBlock; 13033 case scPtrToInt: 13034 case scTruncate: 13035 case scZeroExtend: 13036 case scSignExtend: 13037 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 13038 case scAddRecExpr: { 13039 // This uses a "dominates" query instead of "properly dominates" query 13040 // to test for proper dominance too, because the instruction which 13041 // produces the addrec's value is a PHI, and a PHI effectively properly 13042 // dominates its entire containing block. 13043 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 13044 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 13045 return DoesNotDominateBlock; 13046 13047 // Fall through into SCEVNAryExpr handling. 13048 LLVM_FALLTHROUGH; 13049 } 13050 case scAddExpr: 13051 case scMulExpr: 13052 case scUMaxExpr: 13053 case scSMaxExpr: 13054 case scUMinExpr: 13055 case scSMinExpr: 13056 case scSequentialUMinExpr: { 13057 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 13058 bool Proper = true; 13059 for (const SCEV *NAryOp : NAry->operands()) { 13060 BlockDisposition D = getBlockDisposition(NAryOp, BB); 13061 if (D == DoesNotDominateBlock) 13062 return DoesNotDominateBlock; 13063 if (D == DominatesBlock) 13064 Proper = false; 13065 } 13066 return Proper ? ProperlyDominatesBlock : DominatesBlock; 13067 } 13068 case scUDivExpr: { 13069 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 13070 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 13071 BlockDisposition LD = getBlockDisposition(LHS, BB); 13072 if (LD == DoesNotDominateBlock) 13073 return DoesNotDominateBlock; 13074 BlockDisposition RD = getBlockDisposition(RHS, BB); 13075 if (RD == DoesNotDominateBlock) 13076 return DoesNotDominateBlock; 13077 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 13078 ProperlyDominatesBlock : DominatesBlock; 13079 } 13080 case scUnknown: 13081 if (Instruction *I = 13082 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 13083 if (I->getParent() == BB) 13084 return DominatesBlock; 13085 if (DT.properlyDominates(I->getParent(), BB)) 13086 return ProperlyDominatesBlock; 13087 return DoesNotDominateBlock; 13088 } 13089 return ProperlyDominatesBlock; 13090 case scCouldNotCompute: 13091 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 13092 } 13093 llvm_unreachable("Unknown SCEV kind!"); 13094 } 13095 13096 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 13097 return getBlockDisposition(S, BB) >= DominatesBlock; 13098 } 13099 13100 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 13101 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 13102 } 13103 13104 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 13105 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 13106 } 13107 13108 void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L, 13109 bool Predicated) { 13110 auto &BECounts = 13111 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts; 13112 auto It = BECounts.find(L); 13113 if (It != BECounts.end()) { 13114 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) { 13115 if (!isa<SCEVConstant>(ENT.ExactNotTaken)) { 13116 auto UserIt = BECountUsers.find(ENT.ExactNotTaken); 13117 assert(UserIt != BECountUsers.end()); 13118 UserIt->second.erase({L, Predicated}); 13119 } 13120 } 13121 BECounts.erase(It); 13122 } 13123 } 13124 13125 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) { 13126 SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end()); 13127 SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end()); 13128 13129 while (!Worklist.empty()) { 13130 const SCEV *Curr = Worklist.pop_back_val(); 13131 auto Users = SCEVUsers.find(Curr); 13132 if (Users != SCEVUsers.end()) 13133 for (auto *User : Users->second) 13134 if (ToForget.insert(User).second) 13135 Worklist.push_back(User); 13136 } 13137 13138 for (auto *S : ToForget) 13139 forgetMemoizedResultsImpl(S); 13140 13141 for (auto I = PredicatedSCEVRewrites.begin(); 13142 I != PredicatedSCEVRewrites.end();) { 13143 std::pair<const SCEV *, const Loop *> Entry = I->first; 13144 if (ToForget.count(Entry.first)) 13145 PredicatedSCEVRewrites.erase(I++); 13146 else 13147 ++I; 13148 } 13149 } 13150 13151 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) { 13152 LoopDispositions.erase(S); 13153 BlockDispositions.erase(S); 13154 UnsignedRanges.erase(S); 13155 SignedRanges.erase(S); 13156 HasRecMap.erase(S); 13157 MinTrailingZerosCache.erase(S); 13158 13159 auto ExprIt = ExprValueMap.find(S); 13160 if (ExprIt != ExprValueMap.end()) { 13161 for (auto &ValueAndOffset : ExprIt->second) { 13162 if (ValueAndOffset.second == nullptr) { 13163 auto ValueIt = ValueExprMap.find_as(ValueAndOffset.first); 13164 if (ValueIt != ValueExprMap.end()) 13165 ValueExprMap.erase(ValueIt); 13166 } 13167 } 13168 ExprValueMap.erase(ExprIt); 13169 } 13170 13171 auto ScopeIt = ValuesAtScopes.find(S); 13172 if (ScopeIt != ValuesAtScopes.end()) { 13173 for (const auto &Pair : ScopeIt->second) 13174 if (!isa_and_nonnull<SCEVConstant>(Pair.second)) 13175 erase_value(ValuesAtScopesUsers[Pair.second], 13176 std::make_pair(Pair.first, S)); 13177 ValuesAtScopes.erase(ScopeIt); 13178 } 13179 13180 auto ScopeUserIt = ValuesAtScopesUsers.find(S); 13181 if (ScopeUserIt != ValuesAtScopesUsers.end()) { 13182 for (const auto &Pair : ScopeUserIt->second) 13183 erase_value(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S)); 13184 ValuesAtScopesUsers.erase(ScopeUserIt); 13185 } 13186 13187 auto BEUsersIt = BECountUsers.find(S); 13188 if (BEUsersIt != BECountUsers.end()) { 13189 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original. 13190 auto Copy = BEUsersIt->second; 13191 for (const auto &Pair : Copy) 13192 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt()); 13193 BECountUsers.erase(BEUsersIt); 13194 } 13195 } 13196 13197 void 13198 ScalarEvolution::getUsedLoops(const SCEV *S, 13199 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 13200 struct FindUsedLoops { 13201 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 13202 : LoopsUsed(LoopsUsed) {} 13203 SmallPtrSetImpl<const Loop *> &LoopsUsed; 13204 bool follow(const SCEV *S) { 13205 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 13206 LoopsUsed.insert(AR->getLoop()); 13207 return true; 13208 } 13209 13210 bool isDone() const { return false; } 13211 }; 13212 13213 FindUsedLoops F(LoopsUsed); 13214 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 13215 } 13216 13217 void ScalarEvolution::verify() const { 13218 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 13219 ScalarEvolution SE2(F, TLI, AC, DT, LI); 13220 13221 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 13222 13223 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 13224 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 13225 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 13226 13227 const SCEV *visitConstant(const SCEVConstant *Constant) { 13228 return SE.getConstant(Constant->getAPInt()); 13229 } 13230 13231 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13232 return SE.getUnknown(Expr->getValue()); 13233 } 13234 13235 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 13236 return SE.getCouldNotCompute(); 13237 } 13238 }; 13239 13240 SCEVMapper SCM(SE2); 13241 13242 while (!LoopStack.empty()) { 13243 auto *L = LoopStack.pop_back_val(); 13244 llvm::append_range(LoopStack, *L); 13245 13246 auto *CurBECount = SCM.visit( 13247 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 13248 auto *NewBECount = SE2.getBackedgeTakenCount(L); 13249 13250 if (CurBECount == SE2.getCouldNotCompute() || 13251 NewBECount == SE2.getCouldNotCompute()) { 13252 // NB! This situation is legal, but is very suspicious -- whatever pass 13253 // change the loop to make a trip count go from could not compute to 13254 // computable or vice-versa *should have* invalidated SCEV. However, we 13255 // choose not to assert here (for now) since we don't want false 13256 // positives. 13257 continue; 13258 } 13259 13260 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 13261 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 13262 // not propagate undef aggressively). This means we can (and do) fail 13263 // verification in cases where a transform makes the trip count of a loop 13264 // go from "undef" to "undef+1" (say). The transform is fine, since in 13265 // both cases the loop iterates "undef" times, but SCEV thinks we 13266 // increased the trip count of the loop by 1 incorrectly. 13267 continue; 13268 } 13269 13270 if (SE.getTypeSizeInBits(CurBECount->getType()) > 13271 SE.getTypeSizeInBits(NewBECount->getType())) 13272 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 13273 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 13274 SE.getTypeSizeInBits(NewBECount->getType())) 13275 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 13276 13277 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 13278 13279 // Unless VerifySCEVStrict is set, we only compare constant deltas. 13280 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 13281 dbgs() << "Trip Count for " << *L << " Changed!\n"; 13282 dbgs() << "Old: " << *CurBECount << "\n"; 13283 dbgs() << "New: " << *NewBECount << "\n"; 13284 dbgs() << "Delta: " << *Delta << "\n"; 13285 std::abort(); 13286 } 13287 } 13288 13289 // Collect all valid loops currently in LoopInfo. 13290 SmallPtrSet<Loop *, 32> ValidLoops; 13291 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 13292 while (!Worklist.empty()) { 13293 Loop *L = Worklist.pop_back_val(); 13294 if (ValidLoops.contains(L)) 13295 continue; 13296 ValidLoops.insert(L); 13297 Worklist.append(L->begin(), L->end()); 13298 } 13299 for (auto &KV : ValueExprMap) { 13300 #ifndef NDEBUG 13301 // Check for SCEV expressions referencing invalid/deleted loops. 13302 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) { 13303 assert(ValidLoops.contains(AR->getLoop()) && 13304 "AddRec references invalid loop"); 13305 } 13306 #endif 13307 13308 // Check that the value is also part of the reverse map. 13309 auto It = ExprValueMap.find(KV.second); 13310 if (It == ExprValueMap.end() || !It->second.contains({KV.first, nullptr})) { 13311 dbgs() << "Value " << *KV.first 13312 << " is in ValueExprMap but not in ExprValueMap\n"; 13313 std::abort(); 13314 } 13315 } 13316 13317 for (const auto &KV : ExprValueMap) { 13318 for (const auto &ValueAndOffset : KV.second) { 13319 if (ValueAndOffset.second != nullptr) 13320 continue; 13321 13322 auto It = ValueExprMap.find_as(ValueAndOffset.first); 13323 if (It == ValueExprMap.end()) { 13324 dbgs() << "Value " << *ValueAndOffset.first 13325 << " is in ExprValueMap but not in ValueExprMap\n"; 13326 std::abort(); 13327 } 13328 if (It->second != KV.first) { 13329 dbgs() << "Value " << *ValueAndOffset.first 13330 << " mapped to " << *It->second 13331 << " rather than " << *KV.first << "\n"; 13332 std::abort(); 13333 } 13334 } 13335 } 13336 13337 // Verify integrity of SCEV users. 13338 for (const auto &S : UniqueSCEVs) { 13339 SmallVector<const SCEV *, 4> Ops; 13340 collectUniqueOps(&S, Ops); 13341 for (const auto *Op : Ops) { 13342 // We do not store dependencies of constants. 13343 if (isa<SCEVConstant>(Op)) 13344 continue; 13345 auto It = SCEVUsers.find(Op); 13346 if (It != SCEVUsers.end() && It->second.count(&S)) 13347 continue; 13348 dbgs() << "Use of operand " << *Op << " by user " << S 13349 << " is not being tracked!\n"; 13350 std::abort(); 13351 } 13352 } 13353 13354 // Verify integrity of ValuesAtScopes users. 13355 for (const auto &ValueAndVec : ValuesAtScopes) { 13356 const SCEV *Value = ValueAndVec.first; 13357 for (const auto &LoopAndValueAtScope : ValueAndVec.second) { 13358 const Loop *L = LoopAndValueAtScope.first; 13359 const SCEV *ValueAtScope = LoopAndValueAtScope.second; 13360 if (!isa<SCEVConstant>(ValueAtScope)) { 13361 auto It = ValuesAtScopesUsers.find(ValueAtScope); 13362 if (It != ValuesAtScopesUsers.end() && 13363 is_contained(It->second, std::make_pair(L, Value))) 13364 continue; 13365 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: " 13366 << *ValueAtScope << " missing in ValuesAtScopesUsers\n"; 13367 std::abort(); 13368 } 13369 } 13370 } 13371 13372 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) { 13373 const SCEV *ValueAtScope = ValueAtScopeAndVec.first; 13374 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) { 13375 const Loop *L = LoopAndValue.first; 13376 const SCEV *Value = LoopAndValue.second; 13377 assert(!isa<SCEVConstant>(Value)); 13378 auto It = ValuesAtScopes.find(Value); 13379 if (It != ValuesAtScopes.end() && 13380 is_contained(It->second, std::make_pair(L, ValueAtScope))) 13381 continue; 13382 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: " 13383 << *ValueAtScope << " missing in ValuesAtScopes\n"; 13384 std::abort(); 13385 } 13386 } 13387 13388 // Verify integrity of BECountUsers. 13389 auto VerifyBECountUsers = [&](bool Predicated) { 13390 auto &BECounts = 13391 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts; 13392 for (const auto &LoopAndBEInfo : BECounts) { 13393 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) { 13394 if (!isa<SCEVConstant>(ENT.ExactNotTaken)) { 13395 auto UserIt = BECountUsers.find(ENT.ExactNotTaken); 13396 if (UserIt != BECountUsers.end() && 13397 UserIt->second.contains({ LoopAndBEInfo.first, Predicated })) 13398 continue; 13399 dbgs() << "Value " << *ENT.ExactNotTaken << " for loop " 13400 << *LoopAndBEInfo.first << " missing from BECountUsers\n"; 13401 std::abort(); 13402 } 13403 } 13404 } 13405 }; 13406 VerifyBECountUsers(/* Predicated */ false); 13407 VerifyBECountUsers(/* Predicated */ true); 13408 } 13409 13410 bool ScalarEvolution::invalidate( 13411 Function &F, const PreservedAnalyses &PA, 13412 FunctionAnalysisManager::Invalidator &Inv) { 13413 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 13414 // of its dependencies is invalidated. 13415 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 13416 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 13417 Inv.invalidate<AssumptionAnalysis>(F, PA) || 13418 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 13419 Inv.invalidate<LoopAnalysis>(F, PA); 13420 } 13421 13422 AnalysisKey ScalarEvolutionAnalysis::Key; 13423 13424 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 13425 FunctionAnalysisManager &AM) { 13426 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 13427 AM.getResult<AssumptionAnalysis>(F), 13428 AM.getResult<DominatorTreeAnalysis>(F), 13429 AM.getResult<LoopAnalysis>(F)); 13430 } 13431 13432 PreservedAnalyses 13433 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 13434 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 13435 return PreservedAnalyses::all(); 13436 } 13437 13438 PreservedAnalyses 13439 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 13440 // For compatibility with opt's -analyze feature under legacy pass manager 13441 // which was not ported to NPM. This keeps tests using 13442 // update_analyze_test_checks.py working. 13443 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 13444 << F.getName() << "':\n"; 13445 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 13446 return PreservedAnalyses::all(); 13447 } 13448 13449 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 13450 "Scalar Evolution Analysis", false, true) 13451 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 13452 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 13453 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 13454 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 13455 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 13456 "Scalar Evolution Analysis", false, true) 13457 13458 char ScalarEvolutionWrapperPass::ID = 0; 13459 13460 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 13461 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 13462 } 13463 13464 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 13465 SE.reset(new ScalarEvolution( 13466 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 13467 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 13468 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 13469 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 13470 return false; 13471 } 13472 13473 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 13474 13475 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 13476 SE->print(OS); 13477 } 13478 13479 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 13480 if (!VerifySCEV) 13481 return; 13482 13483 SE->verify(); 13484 } 13485 13486 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 13487 AU.setPreservesAll(); 13488 AU.addRequiredTransitive<AssumptionCacheTracker>(); 13489 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 13490 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 13491 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 13492 } 13493 13494 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 13495 const SCEV *RHS) { 13496 FoldingSetNodeID ID; 13497 assert(LHS->getType() == RHS->getType() && 13498 "Type mismatch between LHS and RHS"); 13499 // Unique this node based on the arguments 13500 ID.AddInteger(SCEVPredicate::P_Equal); 13501 ID.AddPointer(LHS); 13502 ID.AddPointer(RHS); 13503 void *IP = nullptr; 13504 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13505 return S; 13506 SCEVEqualPredicate *Eq = new (SCEVAllocator) 13507 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 13508 UniquePreds.InsertNode(Eq, IP); 13509 return Eq; 13510 } 13511 13512 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 13513 const SCEVAddRecExpr *AR, 13514 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13515 FoldingSetNodeID ID; 13516 // Unique this node based on the arguments 13517 ID.AddInteger(SCEVPredicate::P_Wrap); 13518 ID.AddPointer(AR); 13519 ID.AddInteger(AddedFlags); 13520 void *IP = nullptr; 13521 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13522 return S; 13523 auto *OF = new (SCEVAllocator) 13524 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 13525 UniquePreds.InsertNode(OF, IP); 13526 return OF; 13527 } 13528 13529 namespace { 13530 13531 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 13532 public: 13533 13534 /// Rewrites \p S in the context of a loop L and the SCEV predication 13535 /// infrastructure. 13536 /// 13537 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 13538 /// equivalences present in \p Pred. 13539 /// 13540 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 13541 /// \p NewPreds such that the result will be an AddRecExpr. 13542 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 13543 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13544 SCEVUnionPredicate *Pred) { 13545 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 13546 return Rewriter.visit(S); 13547 } 13548 13549 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13550 if (Pred) { 13551 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 13552 for (auto *Pred : ExprPreds) 13553 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 13554 if (IPred->getLHS() == Expr) 13555 return IPred->getRHS(); 13556 } 13557 return convertToAddRecWithPreds(Expr); 13558 } 13559 13560 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 13561 const SCEV *Operand = visit(Expr->getOperand()); 13562 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13563 if (AR && AR->getLoop() == L && AR->isAffine()) { 13564 // This couldn't be folded because the operand didn't have the nuw 13565 // flag. Add the nusw flag as an assumption that we could make. 13566 const SCEV *Step = AR->getStepRecurrence(SE); 13567 Type *Ty = Expr->getType(); 13568 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 13569 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 13570 SE.getSignExtendExpr(Step, Ty), L, 13571 AR->getNoWrapFlags()); 13572 } 13573 return SE.getZeroExtendExpr(Operand, Expr->getType()); 13574 } 13575 13576 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 13577 const SCEV *Operand = visit(Expr->getOperand()); 13578 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13579 if (AR && AR->getLoop() == L && AR->isAffine()) { 13580 // This couldn't be folded because the operand didn't have the nsw 13581 // flag. Add the nssw flag as an assumption that we could make. 13582 const SCEV *Step = AR->getStepRecurrence(SE); 13583 Type *Ty = Expr->getType(); 13584 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 13585 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 13586 SE.getSignExtendExpr(Step, Ty), L, 13587 AR->getNoWrapFlags()); 13588 } 13589 return SE.getSignExtendExpr(Operand, Expr->getType()); 13590 } 13591 13592 private: 13593 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 13594 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13595 SCEVUnionPredicate *Pred) 13596 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 13597 13598 bool addOverflowAssumption(const SCEVPredicate *P) { 13599 if (!NewPreds) { 13600 // Check if we've already made this assumption. 13601 return Pred && Pred->implies(P); 13602 } 13603 NewPreds->insert(P); 13604 return true; 13605 } 13606 13607 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 13608 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13609 auto *A = SE.getWrapPredicate(AR, AddedFlags); 13610 return addOverflowAssumption(A); 13611 } 13612 13613 // If \p Expr represents a PHINode, we try to see if it can be represented 13614 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 13615 // to add this predicate as a runtime overflow check, we return the AddRec. 13616 // If \p Expr does not meet these conditions (is not a PHI node, or we 13617 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13618 // return \p Expr. 13619 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13620 if (!isa<PHINode>(Expr->getValue())) 13621 return Expr; 13622 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13623 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13624 if (!PredicatedRewrite) 13625 return Expr; 13626 for (auto *P : PredicatedRewrite->second){ 13627 // Wrap predicates from outer loops are not supported. 13628 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13629 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 13630 if (L != AR->getLoop()) 13631 return Expr; 13632 } 13633 if (!addOverflowAssumption(P)) 13634 return Expr; 13635 } 13636 return PredicatedRewrite->first; 13637 } 13638 13639 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13640 SCEVUnionPredicate *Pred; 13641 const Loop *L; 13642 }; 13643 13644 } // end anonymous namespace 13645 13646 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13647 SCEVUnionPredicate &Preds) { 13648 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13649 } 13650 13651 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13652 const SCEV *S, const Loop *L, 13653 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13654 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13655 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13656 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13657 13658 if (!AddRec) 13659 return nullptr; 13660 13661 // Since the transformation was successful, we can now transfer the SCEV 13662 // predicates. 13663 for (auto *P : TransformPreds) 13664 Preds.insert(P); 13665 13666 return AddRec; 13667 } 13668 13669 /// SCEV predicates 13670 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13671 SCEVPredicateKind Kind) 13672 : FastID(ID), Kind(Kind) {} 13673 13674 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 13675 const SCEV *LHS, const SCEV *RHS) 13676 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 13677 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13678 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13679 } 13680 13681 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 13682 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 13683 13684 if (!Op) 13685 return false; 13686 13687 return Op->LHS == LHS && Op->RHS == RHS; 13688 } 13689 13690 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 13691 13692 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 13693 13694 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 13695 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13696 } 13697 13698 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13699 const SCEVAddRecExpr *AR, 13700 IncrementWrapFlags Flags) 13701 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13702 13703 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 13704 13705 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 13706 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 13707 13708 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 13709 } 13710 13711 bool SCEVWrapPredicate::isAlwaysTrue() const { 13712 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 13713 IncrementWrapFlags IFlags = Flags; 13714 13715 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 13716 IFlags = clearFlags(IFlags, IncrementNSSW); 13717 13718 return IFlags == IncrementAnyWrap; 13719 } 13720 13721 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 13722 OS.indent(Depth) << *getExpr() << " Added Flags: "; 13723 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 13724 OS << "<nusw>"; 13725 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 13726 OS << "<nssw>"; 13727 OS << "\n"; 13728 } 13729 13730 SCEVWrapPredicate::IncrementWrapFlags 13731 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 13732 ScalarEvolution &SE) { 13733 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 13734 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 13735 13736 // We can safely transfer the NSW flag as NSSW. 13737 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 13738 ImpliedFlags = IncrementNSSW; 13739 13740 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 13741 // If the increment is positive, the SCEV NUW flag will also imply the 13742 // WrapPredicate NUSW flag. 13743 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 13744 if (Step->getValue()->getValue().isNonNegative()) 13745 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 13746 } 13747 13748 return ImpliedFlags; 13749 } 13750 13751 /// Union predicates don't get cached so create a dummy set ID for it. 13752 SCEVUnionPredicate::SCEVUnionPredicate() 13753 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 13754 13755 bool SCEVUnionPredicate::isAlwaysTrue() const { 13756 return all_of(Preds, 13757 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 13758 } 13759 13760 ArrayRef<const SCEVPredicate *> 13761 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 13762 auto I = SCEVToPreds.find(Expr); 13763 if (I == SCEVToPreds.end()) 13764 return ArrayRef<const SCEVPredicate *>(); 13765 return I->second; 13766 } 13767 13768 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 13769 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 13770 return all_of(Set->Preds, 13771 [this](const SCEVPredicate *I) { return this->implies(I); }); 13772 13773 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 13774 if (ScevPredsIt == SCEVToPreds.end()) 13775 return false; 13776 auto &SCEVPreds = ScevPredsIt->second; 13777 13778 return any_of(SCEVPreds, 13779 [N](const SCEVPredicate *I) { return I->implies(N); }); 13780 } 13781 13782 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 13783 13784 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 13785 for (auto Pred : Preds) 13786 Pred->print(OS, Depth); 13787 } 13788 13789 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 13790 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 13791 for (auto Pred : Set->Preds) 13792 add(Pred); 13793 return; 13794 } 13795 13796 if (implies(N)) 13797 return; 13798 13799 const SCEV *Key = N->getExpr(); 13800 assert(Key && "Only SCEVUnionPredicate doesn't have an " 13801 " associated expression!"); 13802 13803 SCEVToPreds[Key].push_back(N); 13804 Preds.push_back(N); 13805 } 13806 13807 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 13808 Loop &L) 13809 : SE(SE), L(L) {} 13810 13811 void ScalarEvolution::registerUser(const SCEV *User, 13812 ArrayRef<const SCEV *> Ops) { 13813 for (auto *Op : Ops) 13814 // We do not expect that forgetting cached data for SCEVConstants will ever 13815 // open any prospects for sharpening or introduce any correctness issues, 13816 // so we don't bother storing their dependencies. 13817 if (!isa<SCEVConstant>(Op)) 13818 SCEVUsers[Op].insert(User); 13819 } 13820 13821 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 13822 const SCEV *Expr = SE.getSCEV(V); 13823 RewriteEntry &Entry = RewriteMap[Expr]; 13824 13825 // If we already have an entry and the version matches, return it. 13826 if (Entry.second && Generation == Entry.first) 13827 return Entry.second; 13828 13829 // We found an entry but it's stale. Rewrite the stale entry 13830 // according to the current predicate. 13831 if (Entry.second) 13832 Expr = Entry.second; 13833 13834 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 13835 Entry = {Generation, NewSCEV}; 13836 13837 return NewSCEV; 13838 } 13839 13840 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13841 if (!BackedgeCount) { 13842 SCEVUnionPredicate BackedgePred; 13843 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 13844 addPredicate(BackedgePred); 13845 } 13846 return BackedgeCount; 13847 } 13848 13849 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13850 if (Preds.implies(&Pred)) 13851 return; 13852 Preds.add(&Pred); 13853 updateGeneration(); 13854 } 13855 13856 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 13857 return Preds; 13858 } 13859 13860 void PredicatedScalarEvolution::updateGeneration() { 13861 // If the generation number wrapped recompute everything. 13862 if (++Generation == 0) { 13863 for (auto &II : RewriteMap) { 13864 const SCEV *Rewritten = II.second.second; 13865 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 13866 } 13867 } 13868 } 13869 13870 void PredicatedScalarEvolution::setNoOverflow( 13871 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13872 const SCEV *Expr = getSCEV(V); 13873 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13874 13875 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13876 13877 // Clear the statically implied flags. 13878 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13879 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13880 13881 auto II = FlagsMap.insert({V, Flags}); 13882 if (!II.second) 13883 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13884 } 13885 13886 bool PredicatedScalarEvolution::hasNoOverflow( 13887 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13888 const SCEV *Expr = getSCEV(V); 13889 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13890 13891 Flags = SCEVWrapPredicate::clearFlags( 13892 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13893 13894 auto II = FlagsMap.find(V); 13895 13896 if (II != FlagsMap.end()) 13897 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13898 13899 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13900 } 13901 13902 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13903 const SCEV *Expr = this->getSCEV(V); 13904 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13905 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13906 13907 if (!New) 13908 return nullptr; 13909 13910 for (auto *P : NewPreds) 13911 Preds.add(P); 13912 13913 updateGeneration(); 13914 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13915 return New; 13916 } 13917 13918 PredicatedScalarEvolution::PredicatedScalarEvolution( 13919 const PredicatedScalarEvolution &Init) 13920 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13921 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13922 for (auto I : Init.FlagsMap) 13923 FlagsMap.insert(I); 13924 } 13925 13926 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13927 // For each block. 13928 for (auto *BB : L.getBlocks()) 13929 for (auto &I : *BB) { 13930 if (!SE.isSCEVable(I.getType())) 13931 continue; 13932 13933 auto *Expr = SE.getSCEV(&I); 13934 auto II = RewriteMap.find(Expr); 13935 13936 if (II == RewriteMap.end()) 13937 continue; 13938 13939 // Don't print things that are not interesting. 13940 if (II->second.second == Expr) 13941 continue; 13942 13943 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13944 OS.indent(Depth + 2) << *Expr << "\n"; 13945 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13946 } 13947 } 13948 13949 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13950 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13951 // for URem with constant power-of-2 second operands. 13952 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13953 // 4, A / B becomes X / 8). 13954 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13955 const SCEV *&RHS) { 13956 // Try to match 'zext (trunc A to iB) to iY', which is used 13957 // for URem with constant power-of-2 second operands. Make sure the size of 13958 // the operand A matches the size of the whole expressions. 13959 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13960 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13961 LHS = Trunc->getOperand(); 13962 // Bail out if the type of the LHS is larger than the type of the 13963 // expression for now. 13964 if (getTypeSizeInBits(LHS->getType()) > 13965 getTypeSizeInBits(Expr->getType())) 13966 return false; 13967 if (LHS->getType() != Expr->getType()) 13968 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13969 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13970 << getTypeSizeInBits(Trunc->getType())); 13971 return true; 13972 } 13973 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13974 if (Add == nullptr || Add->getNumOperands() != 2) 13975 return false; 13976 13977 const SCEV *A = Add->getOperand(1); 13978 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13979 13980 if (Mul == nullptr) 13981 return false; 13982 13983 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13984 // (SomeExpr + (-(SomeExpr / B) * B)). 13985 if (Expr == getURemExpr(A, B)) { 13986 LHS = A; 13987 RHS = B; 13988 return true; 13989 } 13990 return false; 13991 }; 13992 13993 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13994 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13995 return MatchURemWithDivisor(Mul->getOperand(1)) || 13996 MatchURemWithDivisor(Mul->getOperand(2)); 13997 13998 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13999 if (Mul->getNumOperands() == 2) 14000 return MatchURemWithDivisor(Mul->getOperand(1)) || 14001 MatchURemWithDivisor(Mul->getOperand(0)) || 14002 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 14003 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 14004 return false; 14005 } 14006 14007 const SCEV * 14008 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 14009 SmallVector<BasicBlock*, 16> ExitingBlocks; 14010 L->getExitingBlocks(ExitingBlocks); 14011 14012 // Form an expression for the maximum exit count possible for this loop. We 14013 // merge the max and exact information to approximate a version of 14014 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 14015 SmallVector<const SCEV*, 4> ExitCounts; 14016 for (BasicBlock *ExitingBB : ExitingBlocks) { 14017 const SCEV *ExitCount = getExitCount(L, ExitingBB); 14018 if (isa<SCEVCouldNotCompute>(ExitCount)) 14019 ExitCount = getExitCount(L, ExitingBB, 14020 ScalarEvolution::ConstantMaximum); 14021 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 14022 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 14023 "We should only have known counts for exiting blocks that " 14024 "dominate latch!"); 14025 ExitCounts.push_back(ExitCount); 14026 } 14027 } 14028 if (ExitCounts.empty()) 14029 return getCouldNotCompute(); 14030 return getUMinFromMismatchedTypes(ExitCounts); 14031 } 14032 14033 /// A rewriter to replace SCEV expressions in Map with the corresponding entry 14034 /// in the map. It skips AddRecExpr because we cannot guarantee that the 14035 /// replacement is loop invariant in the loop of the AddRec. 14036 /// 14037 /// At the moment only rewriting SCEVUnknown and SCEVZeroExtendExpr is 14038 /// supported. 14039 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 14040 const DenseMap<const SCEV *, const SCEV *> ⤅ 14041 14042 public: 14043 SCEVLoopGuardRewriter(ScalarEvolution &SE, 14044 DenseMap<const SCEV *, const SCEV *> &M) 14045 : SCEVRewriteVisitor(SE), Map(M) {} 14046 14047 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 14048 14049 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 14050 auto I = Map.find(Expr); 14051 if (I == Map.end()) 14052 return Expr; 14053 return I->second; 14054 } 14055 14056 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 14057 auto I = Map.find(Expr); 14058 if (I == Map.end()) 14059 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr( 14060 Expr); 14061 return I->second; 14062 } 14063 }; 14064 14065 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 14066 SmallVector<const SCEV *> ExprsToRewrite; 14067 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 14068 const SCEV *RHS, 14069 DenseMap<const SCEV *, const SCEV *> 14070 &RewriteMap) { 14071 // WARNING: It is generally unsound to apply any wrap flags to the proposed 14072 // replacement SCEV which isn't directly implied by the structure of that 14073 // SCEV. In particular, using contextual facts to imply flags is *NOT* 14074 // legal. See the scoping rules for flags in the header to understand why. 14075 14076 // If LHS is a constant, apply information to the other expression. 14077 if (isa<SCEVConstant>(LHS)) { 14078 std::swap(LHS, RHS); 14079 Predicate = CmpInst::getSwappedPredicate(Predicate); 14080 } 14081 14082 // Check for a condition of the form (-C1 + X < C2). InstCombine will 14083 // create this form when combining two checks of the form (X u< C2 + C1) and 14084 // (X >=u C1). 14085 auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap, 14086 &ExprsToRewrite]() { 14087 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS); 14088 if (!AddExpr || AddExpr->getNumOperands() != 2) 14089 return false; 14090 14091 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0)); 14092 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1)); 14093 auto *C2 = dyn_cast<SCEVConstant>(RHS); 14094 if (!C1 || !C2 || !LHSUnknown) 14095 return false; 14096 14097 auto ExactRegion = 14098 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt()) 14099 .sub(C1->getAPInt()); 14100 14101 // Bail out, unless we have a non-wrapping, monotonic range. 14102 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet()) 14103 return false; 14104 auto I = RewriteMap.find(LHSUnknown); 14105 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown; 14106 RewriteMap[LHSUnknown] = getUMaxExpr( 14107 getConstant(ExactRegion.getUnsignedMin()), 14108 getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax()))); 14109 ExprsToRewrite.push_back(LHSUnknown); 14110 return true; 14111 }; 14112 if (MatchRangeCheckIdiom()) 14113 return; 14114 14115 // If we have LHS == 0, check if LHS is computing a property of some unknown 14116 // SCEV %v which we can rewrite %v to express explicitly. 14117 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 14118 if (Predicate == CmpInst::ICMP_EQ && RHSC && 14119 RHSC->getValue()->isNullValue()) { 14120 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 14121 // explicitly express that. 14122 const SCEV *URemLHS = nullptr; 14123 const SCEV *URemRHS = nullptr; 14124 if (matchURem(LHS, URemLHS, URemRHS)) { 14125 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 14126 auto Multiple = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS); 14127 RewriteMap[LHSUnknown] = Multiple; 14128 ExprsToRewrite.push_back(LHSUnknown); 14129 return; 14130 } 14131 } 14132 } 14133 14134 // Do not apply information for constants or if RHS contains an AddRec. 14135 if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS)) 14136 return; 14137 14138 // If RHS is SCEVUnknown, make sure the information is applied to it. 14139 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) { 14140 std::swap(LHS, RHS); 14141 Predicate = CmpInst::getSwappedPredicate(Predicate); 14142 } 14143 14144 // Limit to expressions that can be rewritten. 14145 if (!isa<SCEVUnknown>(LHS) && !isa<SCEVZeroExtendExpr>(LHS)) 14146 return; 14147 14148 // Check whether LHS has already been rewritten. In that case we want to 14149 // chain further rewrites onto the already rewritten value. 14150 auto I = RewriteMap.find(LHS); 14151 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 14152 14153 const SCEV *RewrittenRHS = nullptr; 14154 switch (Predicate) { 14155 case CmpInst::ICMP_ULT: 14156 RewrittenRHS = 14157 getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 14158 break; 14159 case CmpInst::ICMP_SLT: 14160 RewrittenRHS = 14161 getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 14162 break; 14163 case CmpInst::ICMP_ULE: 14164 RewrittenRHS = getUMinExpr(RewrittenLHS, RHS); 14165 break; 14166 case CmpInst::ICMP_SLE: 14167 RewrittenRHS = getSMinExpr(RewrittenLHS, RHS); 14168 break; 14169 case CmpInst::ICMP_UGT: 14170 RewrittenRHS = 14171 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 14172 break; 14173 case CmpInst::ICMP_SGT: 14174 RewrittenRHS = 14175 getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 14176 break; 14177 case CmpInst::ICMP_UGE: 14178 RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS); 14179 break; 14180 case CmpInst::ICMP_SGE: 14181 RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS); 14182 break; 14183 case CmpInst::ICMP_EQ: 14184 if (isa<SCEVConstant>(RHS)) 14185 RewrittenRHS = RHS; 14186 break; 14187 case CmpInst::ICMP_NE: 14188 if (isa<SCEVConstant>(RHS) && 14189 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 14190 RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 14191 break; 14192 default: 14193 break; 14194 } 14195 14196 if (RewrittenRHS) { 14197 RewriteMap[LHS] = RewrittenRHS; 14198 if (LHS == RewrittenLHS) 14199 ExprsToRewrite.push_back(LHS); 14200 } 14201 }; 14202 // First, collect conditions from dominating branches. Starting at the loop 14203 // predecessor, climb up the predecessor chain, as long as there are 14204 // predecessors that can be found that have unique successors leading to the 14205 // original header. 14206 // TODO: share this logic with isLoopEntryGuardedByCond. 14207 SmallVector<std::pair<Value *, bool>> Terms; 14208 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 14209 L->getLoopPredecessor(), L->getHeader()); 14210 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 14211 14212 const BranchInst *LoopEntryPredicate = 14213 dyn_cast<BranchInst>(Pair.first->getTerminator()); 14214 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 14215 continue; 14216 14217 Terms.emplace_back(LoopEntryPredicate->getCondition(), 14218 LoopEntryPredicate->getSuccessor(0) == Pair.second); 14219 } 14220 14221 // Now apply the information from the collected conditions to RewriteMap. 14222 // Conditions are processed in reverse order, so the earliest conditions is 14223 // processed first. This ensures the SCEVs with the shortest dependency chains 14224 // are constructed first. 14225 DenseMap<const SCEV *, const SCEV *> RewriteMap; 14226 for (auto &E : reverse(Terms)) { 14227 bool EnterIfTrue = E.second; 14228 SmallVector<Value *, 8> Worklist; 14229 SmallPtrSet<Value *, 8> Visited; 14230 Worklist.push_back(E.first); 14231 while (!Worklist.empty()) { 14232 Value *Cond = Worklist.pop_back_val(); 14233 if (!Visited.insert(Cond).second) 14234 continue; 14235 14236 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 14237 auto Predicate = 14238 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 14239 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 14240 getSCEV(Cmp->getOperand(1)), RewriteMap); 14241 continue; 14242 } 14243 14244 Value *L, *R; 14245 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 14246 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 14247 Worklist.push_back(L); 14248 Worklist.push_back(R); 14249 } 14250 } 14251 } 14252 14253 // Also collect information from assumptions dominating the loop. 14254 for (auto &AssumeVH : AC.assumptions()) { 14255 if (!AssumeVH) 14256 continue; 14257 auto *AssumeI = cast<CallInst>(AssumeVH); 14258 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 14259 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 14260 continue; 14261 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 14262 getSCEV(Cmp->getOperand(1)), RewriteMap); 14263 } 14264 14265 if (RewriteMap.empty()) 14266 return Expr; 14267 14268 // Now that all rewrite information is collect, rewrite the collected 14269 // expressions with the information in the map. This applies information to 14270 // sub-expressions. 14271 if (ExprsToRewrite.size() > 1) { 14272 for (const SCEV *Expr : ExprsToRewrite) { 14273 const SCEV *RewriteTo = RewriteMap[Expr]; 14274 RewriteMap.erase(Expr); 14275 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 14276 RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)}); 14277 } 14278 } 14279 14280 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 14281 return Rewriter.visit(Expr); 14282 } 14283