1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution analysis 10 // engine, which is used primarily to analyze expressions involving induction 11 // variables in loops. 12 // 13 // There are several aspects to this library. First is the representation of 14 // scalar expressions, which are represented as subclasses of the SCEV class. 15 // These classes are used to represent certain types of subexpressions that we 16 // can handle. We only create one SCEV of a particular shape, so 17 // pointer-comparisons for equality are legal. 18 // 19 // One important aspect of the SCEV objects is that they are never cyclic, even 20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 22 // recurrence) then we represent it directly as a recurrence node, otherwise we 23 // represent it as a SCEVUnknown node. 24 // 25 // In addition to being able to represent expressions of various types, we also 26 // have folders that are used to build the *canonical* representation for a 27 // particular expression. These folders are capable of using a variety of 28 // rewrite rules to simplify the expressions. 29 // 30 // Once the folders are defined, we can implement the more interesting 31 // higher-level code, such as the code that recognizes PHI nodes of various 32 // types, computes the execution count of a loop, etc. 33 // 34 // TODO: We should use these routines and value representations to implement 35 // dependence analysis! 36 // 37 //===----------------------------------------------------------------------===// 38 // 39 // There are several good references for the techniques used in this analysis. 40 // 41 // Chains of recurrences -- a method to expedite the evaluation 42 // of closed-form functions 43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 44 // 45 // On computational properties of chains of recurrences 46 // Eugene V. Zima 47 // 48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 49 // Robert A. van Engelen 50 // 51 // Efficient Symbolic Analysis for Optimizing Compilers 52 // Robert A. van Engelen 53 // 54 // Using the chains of recurrences algebra for data dependence testing and 55 // induction variable substitution 56 // MS Thesis, Johnie Birch 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 83 #include "llvm/Analysis/TargetLibraryInfo.h" 84 #include "llvm/Analysis/ValueTracking.h" 85 #include "llvm/Config/llvm-config.h" 86 #include "llvm/IR/Argument.h" 87 #include "llvm/IR/BasicBlock.h" 88 #include "llvm/IR/CFG.h" 89 #include "llvm/IR/Constant.h" 90 #include "llvm/IR/ConstantRange.h" 91 #include "llvm/IR/Constants.h" 92 #include "llvm/IR/DataLayout.h" 93 #include "llvm/IR/DerivedTypes.h" 94 #include "llvm/IR/Dominators.h" 95 #include "llvm/IR/Function.h" 96 #include "llvm/IR/GlobalAlias.h" 97 #include "llvm/IR/GlobalValue.h" 98 #include "llvm/IR/InstIterator.h" 99 #include "llvm/IR/InstrTypes.h" 100 #include "llvm/IR/Instruction.h" 101 #include "llvm/IR/Instructions.h" 102 #include "llvm/IR/IntrinsicInst.h" 103 #include "llvm/IR/Intrinsics.h" 104 #include "llvm/IR/LLVMContext.h" 105 #include "llvm/IR/Operator.h" 106 #include "llvm/IR/PatternMatch.h" 107 #include "llvm/IR/Type.h" 108 #include "llvm/IR/Use.h" 109 #include "llvm/IR/User.h" 110 #include "llvm/IR/Value.h" 111 #include "llvm/IR/Verifier.h" 112 #include "llvm/InitializePasses.h" 113 #include "llvm/Pass.h" 114 #include "llvm/Support/Casting.h" 115 #include "llvm/Support/CommandLine.h" 116 #include "llvm/Support/Compiler.h" 117 #include "llvm/Support/Debug.h" 118 #include "llvm/Support/ErrorHandling.h" 119 #include "llvm/Support/KnownBits.h" 120 #include "llvm/Support/SaveAndRestore.h" 121 #include "llvm/Support/raw_ostream.h" 122 #include <algorithm> 123 #include <cassert> 124 #include <climits> 125 #include <cstdint> 126 #include <cstdlib> 127 #include <map> 128 #include <memory> 129 #include <tuple> 130 #include <utility> 131 #include <vector> 132 133 using namespace llvm; 134 using namespace PatternMatch; 135 136 #define DEBUG_TYPE "scalar-evolution" 137 138 STATISTIC(NumTripCountsComputed, 139 "Number of loops with predictable loop counts"); 140 STATISTIC(NumTripCountsNotComputed, 141 "Number of loops without predictable loop counts"); 142 STATISTIC(NumBruteForceTripCountsComputed, 143 "Number of loops with trip counts computed by force"); 144 145 #ifdef EXPENSIVE_CHECKS 146 bool llvm::VerifySCEV = true; 147 #else 148 bool llvm::VerifySCEV = false; 149 #endif 150 151 static cl::opt<unsigned> 152 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 153 cl::ZeroOrMore, 154 cl::desc("Maximum number of iterations SCEV will " 155 "symbolically execute a constant " 156 "derived loop"), 157 cl::init(100)); 158 159 static cl::opt<bool, true> VerifySCEVOpt( 160 "verify-scev", cl::Hidden, cl::location(VerifySCEV), 161 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 162 static cl::opt<bool> VerifySCEVStrict( 163 "verify-scev-strict", cl::Hidden, 164 cl::desc("Enable stricter verification with -verify-scev is passed")); 165 static cl::opt<bool> 166 VerifySCEVMap("verify-scev-maps", cl::Hidden, 167 cl::desc("Verify no dangling value in ScalarEvolution's " 168 "ExprValueMap (slow)")); 169 170 static cl::opt<bool> VerifyIR( 171 "scev-verify-ir", cl::Hidden, 172 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 173 cl::init(false)); 174 175 static cl::opt<unsigned> MulOpsInlineThreshold( 176 "scev-mulops-inline-threshold", cl::Hidden, 177 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 178 cl::init(32)); 179 180 static cl::opt<unsigned> AddOpsInlineThreshold( 181 "scev-addops-inline-threshold", cl::Hidden, 182 cl::desc("Threshold for inlining addition operands into a SCEV"), 183 cl::init(500)); 184 185 static cl::opt<unsigned> MaxSCEVCompareDepth( 186 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 187 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 188 cl::init(32)); 189 190 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 191 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 192 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 193 cl::init(2)); 194 195 static cl::opt<unsigned> MaxValueCompareDepth( 196 "scalar-evolution-max-value-compare-depth", cl::Hidden, 197 cl::desc("Maximum depth of recursive value complexity comparisons"), 198 cl::init(2)); 199 200 static cl::opt<unsigned> 201 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 202 cl::desc("Maximum depth of recursive arithmetics"), 203 cl::init(32)); 204 205 static cl::opt<unsigned> MaxConstantEvolvingDepth( 206 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 207 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 208 209 static cl::opt<unsigned> 210 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 211 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 212 cl::init(8)); 213 214 static cl::opt<unsigned> 215 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 216 cl::desc("Max coefficients in AddRec during evolving"), 217 cl::init(8)); 218 219 static cl::opt<unsigned> 220 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 221 cl::desc("Size of the expression which is considered huge"), 222 cl::init(4096)); 223 224 static cl::opt<bool> 225 ClassifyExpressions("scalar-evolution-classify-expressions", 226 cl::Hidden, cl::init(true), 227 cl::desc("When printing analysis, include information on every instruction")); 228 229 static cl::opt<bool> UseExpensiveRangeSharpening( 230 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden, 231 cl::init(false), 232 cl::desc("Use more powerful methods of sharpening expression ranges. May " 233 "be costly in terms of compile time")); 234 235 static cl::opt<unsigned> MaxPhiSCCAnalysisSize( 236 "scalar-evolution-max-scc-analysis-depth", cl::Hidden, 237 cl::desc("Maximum amount of nodes to process while searching SCEVUnknown " 238 "Phi strongly connected components"), 239 cl::init(8)); 240 241 static cl::opt<bool> 242 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden, 243 cl::desc("Handle <= and >= in finite loops"), 244 cl::init(true)); 245 246 //===----------------------------------------------------------------------===// 247 // SCEV class definitions 248 //===----------------------------------------------------------------------===// 249 250 //===----------------------------------------------------------------------===// 251 // Implementation of the SCEV class. 252 // 253 254 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 255 LLVM_DUMP_METHOD void SCEV::dump() const { 256 print(dbgs()); 257 dbgs() << '\n'; 258 } 259 #endif 260 261 void SCEV::print(raw_ostream &OS) const { 262 switch (getSCEVType()) { 263 case scConstant: 264 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 265 return; 266 case scPtrToInt: { 267 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this); 268 const SCEV *Op = PtrToInt->getOperand(); 269 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to " 270 << *PtrToInt->getType() << ")"; 271 return; 272 } 273 case scTruncate: { 274 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 275 const SCEV *Op = Trunc->getOperand(); 276 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 277 << *Trunc->getType() << ")"; 278 return; 279 } 280 case scZeroExtend: { 281 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 282 const SCEV *Op = ZExt->getOperand(); 283 OS << "(zext " << *Op->getType() << " " << *Op << " to " 284 << *ZExt->getType() << ")"; 285 return; 286 } 287 case scSignExtend: { 288 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 289 const SCEV *Op = SExt->getOperand(); 290 OS << "(sext " << *Op->getType() << " " << *Op << " to " 291 << *SExt->getType() << ")"; 292 return; 293 } 294 case scAddRecExpr: { 295 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 296 OS << "{" << *AR->getOperand(0); 297 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 298 OS << ",+," << *AR->getOperand(i); 299 OS << "}<"; 300 if (AR->hasNoUnsignedWrap()) 301 OS << "nuw><"; 302 if (AR->hasNoSignedWrap()) 303 OS << "nsw><"; 304 if (AR->hasNoSelfWrap() && 305 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 306 OS << "nw><"; 307 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 308 OS << ">"; 309 return; 310 } 311 case scAddExpr: 312 case scMulExpr: 313 case scUMaxExpr: 314 case scSMaxExpr: 315 case scUMinExpr: 316 case scSMinExpr: 317 case scSequentialUMinExpr: { 318 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 319 const char *OpStr = nullptr; 320 switch (NAry->getSCEVType()) { 321 case scAddExpr: OpStr = " + "; break; 322 case scMulExpr: OpStr = " * "; break; 323 case scUMaxExpr: OpStr = " umax "; break; 324 case scSMaxExpr: OpStr = " smax "; break; 325 case scUMinExpr: 326 OpStr = " umin "; 327 break; 328 case scSMinExpr: 329 OpStr = " smin "; 330 break; 331 case scSequentialUMinExpr: 332 OpStr = " umin_seq "; 333 break; 334 default: 335 llvm_unreachable("There are no other nary expression types."); 336 } 337 OS << "("; 338 ListSeparator LS(OpStr); 339 for (const SCEV *Op : NAry->operands()) 340 OS << LS << *Op; 341 OS << ")"; 342 switch (NAry->getSCEVType()) { 343 case scAddExpr: 344 case scMulExpr: 345 if (NAry->hasNoUnsignedWrap()) 346 OS << "<nuw>"; 347 if (NAry->hasNoSignedWrap()) 348 OS << "<nsw>"; 349 break; 350 default: 351 // Nothing to print for other nary expressions. 352 break; 353 } 354 return; 355 } 356 case scUDivExpr: { 357 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 358 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 359 return; 360 } 361 case scUnknown: { 362 const SCEVUnknown *U = cast<SCEVUnknown>(this); 363 Type *AllocTy; 364 if (U->isSizeOf(AllocTy)) { 365 OS << "sizeof(" << *AllocTy << ")"; 366 return; 367 } 368 if (U->isAlignOf(AllocTy)) { 369 OS << "alignof(" << *AllocTy << ")"; 370 return; 371 } 372 373 Type *CTy; 374 Constant *FieldNo; 375 if (U->isOffsetOf(CTy, FieldNo)) { 376 OS << "offsetof(" << *CTy << ", "; 377 FieldNo->printAsOperand(OS, false); 378 OS << ")"; 379 return; 380 } 381 382 // Otherwise just print it normally. 383 U->getValue()->printAsOperand(OS, false); 384 return; 385 } 386 case scCouldNotCompute: 387 OS << "***COULDNOTCOMPUTE***"; 388 return; 389 } 390 llvm_unreachable("Unknown SCEV kind!"); 391 } 392 393 Type *SCEV::getType() const { 394 switch (getSCEVType()) { 395 case scConstant: 396 return cast<SCEVConstant>(this)->getType(); 397 case scPtrToInt: 398 case scTruncate: 399 case scZeroExtend: 400 case scSignExtend: 401 return cast<SCEVCastExpr>(this)->getType(); 402 case scAddRecExpr: 403 return cast<SCEVAddRecExpr>(this)->getType(); 404 case scMulExpr: 405 return cast<SCEVMulExpr>(this)->getType(); 406 case scUMaxExpr: 407 case scSMaxExpr: 408 case scUMinExpr: 409 case scSMinExpr: 410 return cast<SCEVMinMaxExpr>(this)->getType(); 411 case scSequentialUMinExpr: 412 return cast<SCEVSequentialMinMaxExpr>(this)->getType(); 413 case scAddExpr: 414 return cast<SCEVAddExpr>(this)->getType(); 415 case scUDivExpr: 416 return cast<SCEVUDivExpr>(this)->getType(); 417 case scUnknown: 418 return cast<SCEVUnknown>(this)->getType(); 419 case scCouldNotCompute: 420 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 421 } 422 llvm_unreachable("Unknown SCEV kind!"); 423 } 424 425 bool SCEV::isZero() const { 426 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 427 return SC->getValue()->isZero(); 428 return false; 429 } 430 431 bool SCEV::isOne() const { 432 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 433 return SC->getValue()->isOne(); 434 return false; 435 } 436 437 bool SCEV::isAllOnesValue() const { 438 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 439 return SC->getValue()->isMinusOne(); 440 return false; 441 } 442 443 bool SCEV::isNonConstantNegative() const { 444 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 445 if (!Mul) return false; 446 447 // If there is a constant factor, it will be first. 448 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 449 if (!SC) return false; 450 451 // Return true if the value is negative, this matches things like (-42 * V). 452 return SC->getAPInt().isNegative(); 453 } 454 455 SCEVCouldNotCompute::SCEVCouldNotCompute() : 456 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 457 458 bool SCEVCouldNotCompute::classof(const SCEV *S) { 459 return S->getSCEVType() == scCouldNotCompute; 460 } 461 462 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 463 FoldingSetNodeID ID; 464 ID.AddInteger(scConstant); 465 ID.AddPointer(V); 466 void *IP = nullptr; 467 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 468 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 469 UniqueSCEVs.InsertNode(S, IP); 470 return S; 471 } 472 473 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 474 return getConstant(ConstantInt::get(getContext(), Val)); 475 } 476 477 const SCEV * 478 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 479 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 480 return getConstant(ConstantInt::get(ITy, V, isSigned)); 481 } 482 483 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, 484 const SCEV *op, Type *ty) 485 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 486 Operands[0] = op; 487 } 488 489 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, 490 Type *ITy) 491 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) { 492 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && 493 "Must be a non-bit-width-changing pointer-to-integer cast!"); 494 } 495 496 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, 497 SCEVTypes SCEVTy, const SCEV *op, 498 Type *ty) 499 : SCEVCastExpr(ID, SCEVTy, op, ty) {} 500 501 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, 502 Type *ty) 503 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) { 504 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 505 "Cannot truncate non-integer value!"); 506 } 507 508 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 509 const SCEV *op, Type *ty) 510 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) { 511 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 512 "Cannot zero extend non-integer value!"); 513 } 514 515 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 516 const SCEV *op, Type *ty) 517 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) { 518 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 519 "Cannot sign extend non-integer value!"); 520 } 521 522 void SCEVUnknown::deleted() { 523 // Clear this SCEVUnknown from various maps. 524 SE->forgetMemoizedResults(this); 525 526 // Remove this SCEVUnknown from the uniquing map. 527 SE->UniqueSCEVs.RemoveNode(this); 528 529 // Release the value. 530 setValPtr(nullptr); 531 } 532 533 void SCEVUnknown::allUsesReplacedWith(Value *New) { 534 // Clear this SCEVUnknown from various maps. 535 SE->forgetMemoizedResults(this); 536 537 // Remove this SCEVUnknown from the uniquing map. 538 SE->UniqueSCEVs.RemoveNode(this); 539 540 // Replace the value pointer in case someone is still using this SCEVUnknown. 541 setValPtr(New); 542 } 543 544 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 545 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 546 if (VCE->getOpcode() == Instruction::PtrToInt) 547 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 548 if (CE->getOpcode() == Instruction::GetElementPtr && 549 CE->getOperand(0)->isNullValue() && 550 CE->getNumOperands() == 2) 551 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 552 if (CI->isOne()) { 553 AllocTy = cast<GEPOperator>(CE)->getSourceElementType(); 554 return true; 555 } 556 557 return false; 558 } 559 560 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 561 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 562 if (VCE->getOpcode() == Instruction::PtrToInt) 563 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 564 if (CE->getOpcode() == Instruction::GetElementPtr && 565 CE->getOperand(0)->isNullValue()) { 566 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 567 if (StructType *STy = dyn_cast<StructType>(Ty)) 568 if (!STy->isPacked() && 569 CE->getNumOperands() == 3 && 570 CE->getOperand(1)->isNullValue()) { 571 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 572 if (CI->isOne() && 573 STy->getNumElements() == 2 && 574 STy->getElementType(0)->isIntegerTy(1)) { 575 AllocTy = STy->getElementType(1); 576 return true; 577 } 578 } 579 } 580 581 return false; 582 } 583 584 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 585 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 586 if (VCE->getOpcode() == Instruction::PtrToInt) 587 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 588 if (CE->getOpcode() == Instruction::GetElementPtr && 589 CE->getNumOperands() == 3 && 590 CE->getOperand(0)->isNullValue() && 591 CE->getOperand(1)->isNullValue()) { 592 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 593 // Ignore vector types here so that ScalarEvolutionExpander doesn't 594 // emit getelementptrs that index into vectors. 595 if (Ty->isStructTy() || Ty->isArrayTy()) { 596 CTy = Ty; 597 FieldNo = CE->getOperand(2); 598 return true; 599 } 600 } 601 602 return false; 603 } 604 605 //===----------------------------------------------------------------------===// 606 // SCEV Utilities 607 //===----------------------------------------------------------------------===// 608 609 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 610 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 611 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 612 /// have been previously deemed to be "equally complex" by this routine. It is 613 /// intended to avoid exponential time complexity in cases like: 614 /// 615 /// %a = f(%x, %y) 616 /// %b = f(%a, %a) 617 /// %c = f(%b, %b) 618 /// 619 /// %d = f(%x, %y) 620 /// %e = f(%d, %d) 621 /// %f = f(%e, %e) 622 /// 623 /// CompareValueComplexity(%f, %c) 624 /// 625 /// Since we do not continue running this routine on expression trees once we 626 /// have seen unequal values, there is no need to track them in the cache. 627 static int 628 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 629 const LoopInfo *const LI, Value *LV, Value *RV, 630 unsigned Depth) { 631 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 632 return 0; 633 634 // Order pointer values after integer values. This helps SCEVExpander form 635 // GEPs. 636 bool LIsPointer = LV->getType()->isPointerTy(), 637 RIsPointer = RV->getType()->isPointerTy(); 638 if (LIsPointer != RIsPointer) 639 return (int)LIsPointer - (int)RIsPointer; 640 641 // Compare getValueID values. 642 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 643 if (LID != RID) 644 return (int)LID - (int)RID; 645 646 // Sort arguments by their position. 647 if (const auto *LA = dyn_cast<Argument>(LV)) { 648 const auto *RA = cast<Argument>(RV); 649 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 650 return (int)LArgNo - (int)RArgNo; 651 } 652 653 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 654 const auto *RGV = cast<GlobalValue>(RV); 655 656 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 657 auto LT = GV->getLinkage(); 658 return !(GlobalValue::isPrivateLinkage(LT) || 659 GlobalValue::isInternalLinkage(LT)); 660 }; 661 662 // Use the names to distinguish the two values, but only if the 663 // names are semantically important. 664 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 665 return LGV->getName().compare(RGV->getName()); 666 } 667 668 // For instructions, compare their loop depth, and their operand count. This 669 // is pretty loose. 670 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 671 const auto *RInst = cast<Instruction>(RV); 672 673 // Compare loop depths. 674 const BasicBlock *LParent = LInst->getParent(), 675 *RParent = RInst->getParent(); 676 if (LParent != RParent) { 677 unsigned LDepth = LI->getLoopDepth(LParent), 678 RDepth = LI->getLoopDepth(RParent); 679 if (LDepth != RDepth) 680 return (int)LDepth - (int)RDepth; 681 } 682 683 // Compare the number of operands. 684 unsigned LNumOps = LInst->getNumOperands(), 685 RNumOps = RInst->getNumOperands(); 686 if (LNumOps != RNumOps) 687 return (int)LNumOps - (int)RNumOps; 688 689 for (unsigned Idx : seq(0u, LNumOps)) { 690 int Result = 691 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 692 RInst->getOperand(Idx), Depth + 1); 693 if (Result != 0) 694 return Result; 695 } 696 } 697 698 EqCacheValue.unionSets(LV, RV); 699 return 0; 700 } 701 702 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 703 // than RHS, respectively. A three-way result allows recursive comparisons to be 704 // more efficient. 705 // If the max analysis depth was reached, return None, assuming we do not know 706 // if they are equivalent for sure. 707 static Optional<int> 708 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV, 709 EquivalenceClasses<const Value *> &EqCacheValue, 710 const LoopInfo *const LI, const SCEV *LHS, 711 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) { 712 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 713 if (LHS == RHS) 714 return 0; 715 716 // Primarily, sort the SCEVs by their getSCEVType(). 717 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 718 if (LType != RType) 719 return (int)LType - (int)RType; 720 721 if (EqCacheSCEV.isEquivalent(LHS, RHS)) 722 return 0; 723 724 if (Depth > MaxSCEVCompareDepth) 725 return None; 726 727 // Aside from the getSCEVType() ordering, the particular ordering 728 // isn't very important except that it's beneficial to be consistent, 729 // so that (a + b) and (b + a) don't end up as different expressions. 730 switch (LType) { 731 case scUnknown: { 732 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 733 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 734 735 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 736 RU->getValue(), Depth + 1); 737 if (X == 0) 738 EqCacheSCEV.unionSets(LHS, RHS); 739 return X; 740 } 741 742 case scConstant: { 743 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 744 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 745 746 // Compare constant values. 747 const APInt &LA = LC->getAPInt(); 748 const APInt &RA = RC->getAPInt(); 749 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 750 if (LBitWidth != RBitWidth) 751 return (int)LBitWidth - (int)RBitWidth; 752 return LA.ult(RA) ? -1 : 1; 753 } 754 755 case scAddRecExpr: { 756 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 757 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 758 759 // There is always a dominance between two recs that are used by one SCEV, 760 // so we can safely sort recs by loop header dominance. We require such 761 // order in getAddExpr. 762 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 763 if (LLoop != RLoop) { 764 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 765 assert(LHead != RHead && "Two loops share the same header?"); 766 if (DT.dominates(LHead, RHead)) 767 return 1; 768 else 769 assert(DT.dominates(RHead, LHead) && 770 "No dominance between recurrences used by one SCEV?"); 771 return -1; 772 } 773 774 // Addrec complexity grows with operand count. 775 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 776 if (LNumOps != RNumOps) 777 return (int)LNumOps - (int)RNumOps; 778 779 // Lexicographically compare. 780 for (unsigned i = 0; i != LNumOps; ++i) { 781 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 782 LA->getOperand(i), RA->getOperand(i), DT, 783 Depth + 1); 784 if (X != 0) 785 return X; 786 } 787 EqCacheSCEV.unionSets(LHS, RHS); 788 return 0; 789 } 790 791 case scAddExpr: 792 case scMulExpr: 793 case scSMaxExpr: 794 case scUMaxExpr: 795 case scSMinExpr: 796 case scUMinExpr: 797 case scSequentialUMinExpr: { 798 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 799 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 800 801 // Lexicographically compare n-ary expressions. 802 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 803 if (LNumOps != RNumOps) 804 return (int)LNumOps - (int)RNumOps; 805 806 for (unsigned i = 0; i != LNumOps; ++i) { 807 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 808 LC->getOperand(i), RC->getOperand(i), DT, 809 Depth + 1); 810 if (X != 0) 811 return X; 812 } 813 EqCacheSCEV.unionSets(LHS, RHS); 814 return 0; 815 } 816 817 case scUDivExpr: { 818 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 819 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 820 821 // Lexicographically compare udiv expressions. 822 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 823 RC->getLHS(), DT, Depth + 1); 824 if (X != 0) 825 return X; 826 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 827 RC->getRHS(), DT, Depth + 1); 828 if (X == 0) 829 EqCacheSCEV.unionSets(LHS, RHS); 830 return X; 831 } 832 833 case scPtrToInt: 834 case scTruncate: 835 case scZeroExtend: 836 case scSignExtend: { 837 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 838 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 839 840 // Compare cast expressions by operand. 841 auto X = 842 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(), 843 RC->getOperand(), DT, Depth + 1); 844 if (X == 0) 845 EqCacheSCEV.unionSets(LHS, RHS); 846 return X; 847 } 848 849 case scCouldNotCompute: 850 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 851 } 852 llvm_unreachable("Unknown SCEV kind!"); 853 } 854 855 /// Given a list of SCEV objects, order them by their complexity, and group 856 /// objects of the same complexity together by value. When this routine is 857 /// finished, we know that any duplicates in the vector are consecutive and that 858 /// complexity is monotonically increasing. 859 /// 860 /// Note that we go take special precautions to ensure that we get deterministic 861 /// results from this routine. In other words, we don't want the results of 862 /// this to depend on where the addresses of various SCEV objects happened to 863 /// land in memory. 864 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 865 LoopInfo *LI, DominatorTree &DT) { 866 if (Ops.size() < 2) return; // Noop 867 868 EquivalenceClasses<const SCEV *> EqCacheSCEV; 869 EquivalenceClasses<const Value *> EqCacheValue; 870 871 // Whether LHS has provably less complexity than RHS. 872 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) { 873 auto Complexity = 874 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT); 875 return Complexity && *Complexity < 0; 876 }; 877 if (Ops.size() == 2) { 878 // This is the common case, which also happens to be trivially simple. 879 // Special case it. 880 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 881 if (IsLessComplex(RHS, LHS)) 882 std::swap(LHS, RHS); 883 return; 884 } 885 886 // Do the rough sort by complexity. 887 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 888 return IsLessComplex(LHS, RHS); 889 }); 890 891 // Now that we are sorted by complexity, group elements of the same 892 // complexity. Note that this is, at worst, N^2, but the vector is likely to 893 // be extremely short in practice. Note that we take this approach because we 894 // do not want to depend on the addresses of the objects we are grouping. 895 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 896 const SCEV *S = Ops[i]; 897 unsigned Complexity = S->getSCEVType(); 898 899 // If there are any objects of the same complexity and same value as this 900 // one, group them. 901 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 902 if (Ops[j] == S) { // Found a duplicate. 903 // Move it to immediately after i'th element. 904 std::swap(Ops[i+1], Ops[j]); 905 ++i; // no need to rescan it. 906 if (i == e-2) return; // Done! 907 } 908 } 909 } 910 } 911 912 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 913 /// least HugeExprThreshold nodes). 914 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 915 return any_of(Ops, [](const SCEV *S) { 916 return S->getExpressionSize() >= HugeExprThreshold; 917 }); 918 } 919 920 //===----------------------------------------------------------------------===// 921 // Simple SCEV method implementations 922 //===----------------------------------------------------------------------===// 923 924 /// Compute BC(It, K). The result has width W. Assume, K > 0. 925 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 926 ScalarEvolution &SE, 927 Type *ResultTy) { 928 // Handle the simplest case efficiently. 929 if (K == 1) 930 return SE.getTruncateOrZeroExtend(It, ResultTy); 931 932 // We are using the following formula for BC(It, K): 933 // 934 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 935 // 936 // Suppose, W is the bitwidth of the return value. We must be prepared for 937 // overflow. Hence, we must assure that the result of our computation is 938 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 939 // safe in modular arithmetic. 940 // 941 // However, this code doesn't use exactly that formula; the formula it uses 942 // is something like the following, where T is the number of factors of 2 in 943 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 944 // exponentiation: 945 // 946 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 947 // 948 // This formula is trivially equivalent to the previous formula. However, 949 // this formula can be implemented much more efficiently. The trick is that 950 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 951 // arithmetic. To do exact division in modular arithmetic, all we have 952 // to do is multiply by the inverse. Therefore, this step can be done at 953 // width W. 954 // 955 // The next issue is how to safely do the division by 2^T. The way this 956 // is done is by doing the multiplication step at a width of at least W + T 957 // bits. This way, the bottom W+T bits of the product are accurate. Then, 958 // when we perform the division by 2^T (which is equivalent to a right shift 959 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 960 // truncated out after the division by 2^T. 961 // 962 // In comparison to just directly using the first formula, this technique 963 // is much more efficient; using the first formula requires W * K bits, 964 // but this formula less than W + K bits. Also, the first formula requires 965 // a division step, whereas this formula only requires multiplies and shifts. 966 // 967 // It doesn't matter whether the subtraction step is done in the calculation 968 // width or the input iteration count's width; if the subtraction overflows, 969 // the result must be zero anyway. We prefer here to do it in the width of 970 // the induction variable because it helps a lot for certain cases; CodeGen 971 // isn't smart enough to ignore the overflow, which leads to much less 972 // efficient code if the width of the subtraction is wider than the native 973 // register width. 974 // 975 // (It's possible to not widen at all by pulling out factors of 2 before 976 // the multiplication; for example, K=2 can be calculated as 977 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 978 // extra arithmetic, so it's not an obvious win, and it gets 979 // much more complicated for K > 3.) 980 981 // Protection from insane SCEVs; this bound is conservative, 982 // but it probably doesn't matter. 983 if (K > 1000) 984 return SE.getCouldNotCompute(); 985 986 unsigned W = SE.getTypeSizeInBits(ResultTy); 987 988 // Calculate K! / 2^T and T; we divide out the factors of two before 989 // multiplying for calculating K! / 2^T to avoid overflow. 990 // Other overflow doesn't matter because we only care about the bottom 991 // W bits of the result. 992 APInt OddFactorial(W, 1); 993 unsigned T = 1; 994 for (unsigned i = 3; i <= K; ++i) { 995 APInt Mult(W, i); 996 unsigned TwoFactors = Mult.countTrailingZeros(); 997 T += TwoFactors; 998 Mult.lshrInPlace(TwoFactors); 999 OddFactorial *= Mult; 1000 } 1001 1002 // We need at least W + T bits for the multiplication step 1003 unsigned CalculationBits = W + T; 1004 1005 // Calculate 2^T, at width T+W. 1006 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1007 1008 // Calculate the multiplicative inverse of K! / 2^T; 1009 // this multiplication factor will perform the exact division by 1010 // K! / 2^T. 1011 APInt Mod = APInt::getSignedMinValue(W+1); 1012 APInt MultiplyFactor = OddFactorial.zext(W+1); 1013 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1014 MultiplyFactor = MultiplyFactor.trunc(W); 1015 1016 // Calculate the product, at width T+W 1017 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1018 CalculationBits); 1019 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1020 for (unsigned i = 1; i != K; ++i) { 1021 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1022 Dividend = SE.getMulExpr(Dividend, 1023 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1024 } 1025 1026 // Divide by 2^T 1027 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1028 1029 // Truncate the result, and divide by K! / 2^T. 1030 1031 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1032 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1033 } 1034 1035 /// Return the value of this chain of recurrences at the specified iteration 1036 /// number. We can evaluate this recurrence by multiplying each element in the 1037 /// chain by the binomial coefficient corresponding to it. In other words, we 1038 /// can evaluate {A,+,B,+,C,+,D} as: 1039 /// 1040 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1041 /// 1042 /// where BC(It, k) stands for binomial coefficient. 1043 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1044 ScalarEvolution &SE) const { 1045 return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE); 1046 } 1047 1048 const SCEV * 1049 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands, 1050 const SCEV *It, ScalarEvolution &SE) { 1051 assert(Operands.size() > 0); 1052 const SCEV *Result = Operands[0]; 1053 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 1054 // The computation is correct in the face of overflow provided that the 1055 // multiplication is performed _after_ the evaluation of the binomial 1056 // coefficient. 1057 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType()); 1058 if (isa<SCEVCouldNotCompute>(Coeff)) 1059 return Coeff; 1060 1061 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff)); 1062 } 1063 return Result; 1064 } 1065 1066 //===----------------------------------------------------------------------===// 1067 // SCEV Expression folder implementations 1068 //===----------------------------------------------------------------------===// 1069 1070 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op, 1071 unsigned Depth) { 1072 assert(Depth <= 1 && 1073 "getLosslessPtrToIntExpr() should self-recurse at most once."); 1074 1075 // We could be called with an integer-typed operands during SCEV rewrites. 1076 // Since the operand is an integer already, just perform zext/trunc/self cast. 1077 if (!Op->getType()->isPointerTy()) 1078 return Op; 1079 1080 // What would be an ID for such a SCEV cast expression? 1081 FoldingSetNodeID ID; 1082 ID.AddInteger(scPtrToInt); 1083 ID.AddPointer(Op); 1084 1085 void *IP = nullptr; 1086 1087 // Is there already an expression for such a cast? 1088 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1089 return S; 1090 1091 // It isn't legal for optimizations to construct new ptrtoint expressions 1092 // for non-integral pointers. 1093 if (getDataLayout().isNonIntegralPointerType(Op->getType())) 1094 return getCouldNotCompute(); 1095 1096 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType()); 1097 1098 // We can only trivially model ptrtoint if SCEV's effective (integer) type 1099 // is sufficiently wide to represent all possible pointer values. 1100 // We could theoretically teach SCEV to truncate wider pointers, but 1101 // that isn't implemented for now. 1102 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) != 1103 getDataLayout().getTypeSizeInBits(IntPtrTy)) 1104 return getCouldNotCompute(); 1105 1106 // If not, is this expression something we can't reduce any further? 1107 if (auto *U = dyn_cast<SCEVUnknown>(Op)) { 1108 // Perform some basic constant folding. If the operand of the ptr2int cast 1109 // is a null pointer, don't create a ptr2int SCEV expression (that will be 1110 // left as-is), but produce a zero constant. 1111 // NOTE: We could handle a more general case, but lack motivational cases. 1112 if (isa<ConstantPointerNull>(U->getValue())) 1113 return getZero(IntPtrTy); 1114 1115 // Create an explicit cast node. 1116 // We can reuse the existing insert position since if we get here, 1117 // we won't have made any changes which would invalidate it. 1118 SCEV *S = new (SCEVAllocator) 1119 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy); 1120 UniqueSCEVs.InsertNode(S, IP); 1121 registerUser(S, Op); 1122 return S; 1123 } 1124 1125 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for " 1126 "non-SCEVUnknown's."); 1127 1128 // Otherwise, we've got some expression that is more complex than just a 1129 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an 1130 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown 1131 // only, and the expressions must otherwise be integer-typed. 1132 // So sink the cast down to the SCEVUnknown's. 1133 1134 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression, 1135 /// which computes a pointer-typed value, and rewrites the whole expression 1136 /// tree so that *all* the computations are done on integers, and the only 1137 /// pointer-typed operands in the expression are SCEVUnknown. 1138 class SCEVPtrToIntSinkingRewriter 1139 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> { 1140 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>; 1141 1142 public: 1143 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {} 1144 1145 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) { 1146 SCEVPtrToIntSinkingRewriter Rewriter(SE); 1147 return Rewriter.visit(Scev); 1148 } 1149 1150 const SCEV *visit(const SCEV *S) { 1151 Type *STy = S->getType(); 1152 // If the expression is not pointer-typed, just keep it as-is. 1153 if (!STy->isPointerTy()) 1154 return S; 1155 // Else, recursively sink the cast down into it. 1156 return Base::visit(S); 1157 } 1158 1159 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) { 1160 SmallVector<const SCEV *, 2> Operands; 1161 bool Changed = false; 1162 for (auto *Op : Expr->operands()) { 1163 Operands.push_back(visit(Op)); 1164 Changed |= Op != Operands.back(); 1165 } 1166 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags()); 1167 } 1168 1169 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) { 1170 SmallVector<const SCEV *, 2> Operands; 1171 bool Changed = false; 1172 for (auto *Op : Expr->operands()) { 1173 Operands.push_back(visit(Op)); 1174 Changed |= Op != Operands.back(); 1175 } 1176 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags()); 1177 } 1178 1179 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 1180 assert(Expr->getType()->isPointerTy() && 1181 "Should only reach pointer-typed SCEVUnknown's."); 1182 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1); 1183 } 1184 }; 1185 1186 // And actually perform the cast sinking. 1187 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this); 1188 assert(IntOp->getType()->isIntegerTy() && 1189 "We must have succeeded in sinking the cast, " 1190 "and ending up with an integer-typed expression!"); 1191 return IntOp; 1192 } 1193 1194 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) { 1195 assert(Ty->isIntegerTy() && "Target type must be an integer type!"); 1196 1197 const SCEV *IntOp = getLosslessPtrToIntExpr(Op); 1198 if (isa<SCEVCouldNotCompute>(IntOp)) 1199 return IntOp; 1200 1201 return getTruncateOrZeroExtend(IntOp, Ty); 1202 } 1203 1204 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1205 unsigned Depth) { 1206 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1207 "This is not a truncating conversion!"); 1208 assert(isSCEVable(Ty) && 1209 "This is not a conversion to a SCEVable type!"); 1210 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!"); 1211 Ty = getEffectiveSCEVType(Ty); 1212 1213 FoldingSetNodeID ID; 1214 ID.AddInteger(scTruncate); 1215 ID.AddPointer(Op); 1216 ID.AddPointer(Ty); 1217 void *IP = nullptr; 1218 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1219 1220 // Fold if the operand is constant. 1221 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1222 return getConstant( 1223 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1224 1225 // trunc(trunc(x)) --> trunc(x) 1226 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1227 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1228 1229 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1230 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1231 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1232 1233 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1234 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1235 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1236 1237 if (Depth > MaxCastDepth) { 1238 SCEV *S = 1239 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1240 UniqueSCEVs.InsertNode(S, IP); 1241 registerUser(S, Op); 1242 return S; 1243 } 1244 1245 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1246 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1247 // if after transforming we have at most one truncate, not counting truncates 1248 // that replace other casts. 1249 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1250 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1251 SmallVector<const SCEV *, 4> Operands; 1252 unsigned numTruncs = 0; 1253 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1254 ++i) { 1255 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1256 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) && 1257 isa<SCEVTruncateExpr>(S)) 1258 numTruncs++; 1259 Operands.push_back(S); 1260 } 1261 if (numTruncs < 2) { 1262 if (isa<SCEVAddExpr>(Op)) 1263 return getAddExpr(Operands); 1264 else if (isa<SCEVMulExpr>(Op)) 1265 return getMulExpr(Operands); 1266 else 1267 llvm_unreachable("Unexpected SCEV type for Op."); 1268 } 1269 // Although we checked in the beginning that ID is not in the cache, it is 1270 // possible that during recursion and different modification ID was inserted 1271 // into the cache. So if we find it, just return it. 1272 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1273 return S; 1274 } 1275 1276 // If the input value is a chrec scev, truncate the chrec's operands. 1277 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1278 SmallVector<const SCEV *, 4> Operands; 1279 for (const SCEV *Op : AddRec->operands()) 1280 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1281 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1282 } 1283 1284 // Return zero if truncating to known zeros. 1285 uint32_t MinTrailingZeros = GetMinTrailingZeros(Op); 1286 if (MinTrailingZeros >= getTypeSizeInBits(Ty)) 1287 return getZero(Ty); 1288 1289 // The cast wasn't folded; create an explicit cast node. We can reuse 1290 // the existing insert position since if we get here, we won't have 1291 // made any changes which would invalidate it. 1292 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1293 Op, Ty); 1294 UniqueSCEVs.InsertNode(S, IP); 1295 registerUser(S, Op); 1296 return S; 1297 } 1298 1299 // Get the limit of a recurrence such that incrementing by Step cannot cause 1300 // signed overflow as long as the value of the recurrence within the 1301 // loop does not exceed this limit before incrementing. 1302 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1303 ICmpInst::Predicate *Pred, 1304 ScalarEvolution *SE) { 1305 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1306 if (SE->isKnownPositive(Step)) { 1307 *Pred = ICmpInst::ICMP_SLT; 1308 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1309 SE->getSignedRangeMax(Step)); 1310 } 1311 if (SE->isKnownNegative(Step)) { 1312 *Pred = ICmpInst::ICMP_SGT; 1313 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1314 SE->getSignedRangeMin(Step)); 1315 } 1316 return nullptr; 1317 } 1318 1319 // Get the limit of a recurrence such that incrementing by Step cannot cause 1320 // unsigned overflow as long as the value of the recurrence within the loop does 1321 // not exceed this limit before incrementing. 1322 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1323 ICmpInst::Predicate *Pred, 1324 ScalarEvolution *SE) { 1325 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1326 *Pred = ICmpInst::ICMP_ULT; 1327 1328 return SE->getConstant(APInt::getMinValue(BitWidth) - 1329 SE->getUnsignedRangeMax(Step)); 1330 } 1331 1332 namespace { 1333 1334 struct ExtendOpTraitsBase { 1335 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1336 unsigned); 1337 }; 1338 1339 // Used to make code generic over signed and unsigned overflow. 1340 template <typename ExtendOp> struct ExtendOpTraits { 1341 // Members present: 1342 // 1343 // static const SCEV::NoWrapFlags WrapType; 1344 // 1345 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1346 // 1347 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1348 // ICmpInst::Predicate *Pred, 1349 // ScalarEvolution *SE); 1350 }; 1351 1352 template <> 1353 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1354 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1355 1356 static const GetExtendExprTy GetExtendExpr; 1357 1358 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1359 ICmpInst::Predicate *Pred, 1360 ScalarEvolution *SE) { 1361 return getSignedOverflowLimitForStep(Step, Pred, SE); 1362 } 1363 }; 1364 1365 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1366 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1367 1368 template <> 1369 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1370 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1371 1372 static const GetExtendExprTy GetExtendExpr; 1373 1374 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1375 ICmpInst::Predicate *Pred, 1376 ScalarEvolution *SE) { 1377 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1378 } 1379 }; 1380 1381 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1382 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1383 1384 } // end anonymous namespace 1385 1386 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1387 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1388 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1389 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1390 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1391 // expression "Step + sext/zext(PreIncAR)" is congruent with 1392 // "sext/zext(PostIncAR)" 1393 template <typename ExtendOpTy> 1394 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1395 ScalarEvolution *SE, unsigned Depth) { 1396 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1397 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1398 1399 const Loop *L = AR->getLoop(); 1400 const SCEV *Start = AR->getStart(); 1401 const SCEV *Step = AR->getStepRecurrence(*SE); 1402 1403 // Check for a simple looking step prior to loop entry. 1404 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1405 if (!SA) 1406 return nullptr; 1407 1408 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1409 // subtraction is expensive. For this purpose, perform a quick and dirty 1410 // difference, by checking for Step in the operand list. 1411 SmallVector<const SCEV *, 4> DiffOps; 1412 for (const SCEV *Op : SA->operands()) 1413 if (Op != Step) 1414 DiffOps.push_back(Op); 1415 1416 if (DiffOps.size() == SA->getNumOperands()) 1417 return nullptr; 1418 1419 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1420 // `Step`: 1421 1422 // 1. NSW/NUW flags on the step increment. 1423 auto PreStartFlags = 1424 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1425 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1426 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1427 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1428 1429 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1430 // "S+X does not sign/unsign-overflow". 1431 // 1432 1433 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1434 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1435 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1436 return PreStart; 1437 1438 // 2. Direct overflow check on the step operation's expression. 1439 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1440 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1441 const SCEV *OperandExtendedStart = 1442 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1443 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1444 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1445 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1446 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1447 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1448 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1449 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType); 1450 } 1451 return PreStart; 1452 } 1453 1454 // 3. Loop precondition. 1455 ICmpInst::Predicate Pred; 1456 const SCEV *OverflowLimit = 1457 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1458 1459 if (OverflowLimit && 1460 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1461 return PreStart; 1462 1463 return nullptr; 1464 } 1465 1466 // Get the normalized zero or sign extended expression for this AddRec's Start. 1467 template <typename ExtendOpTy> 1468 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1469 ScalarEvolution *SE, 1470 unsigned Depth) { 1471 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1472 1473 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1474 if (!PreStart) 1475 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1476 1477 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1478 Depth), 1479 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1480 } 1481 1482 // Try to prove away overflow by looking at "nearby" add recurrences. A 1483 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1484 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1485 // 1486 // Formally: 1487 // 1488 // {S,+,X} == {S-T,+,X} + T 1489 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1490 // 1491 // If ({S-T,+,X} + T) does not overflow ... (1) 1492 // 1493 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1494 // 1495 // If {S-T,+,X} does not overflow ... (2) 1496 // 1497 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1498 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1499 // 1500 // If (S-T)+T does not overflow ... (3) 1501 // 1502 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1503 // == {Ext(S),+,Ext(X)} == LHS 1504 // 1505 // Thus, if (1), (2) and (3) are true for some T, then 1506 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1507 // 1508 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1509 // does not overflow" restricted to the 0th iteration. Therefore we only need 1510 // to check for (1) and (2). 1511 // 1512 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1513 // is `Delta` (defined below). 1514 template <typename ExtendOpTy> 1515 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1516 const SCEV *Step, 1517 const Loop *L) { 1518 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1519 1520 // We restrict `Start` to a constant to prevent SCEV from spending too much 1521 // time here. It is correct (but more expensive) to continue with a 1522 // non-constant `Start` and do a general SCEV subtraction to compute 1523 // `PreStart` below. 1524 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1525 if (!StartC) 1526 return false; 1527 1528 APInt StartAI = StartC->getAPInt(); 1529 1530 for (unsigned Delta : {-2, -1, 1, 2}) { 1531 const SCEV *PreStart = getConstant(StartAI - Delta); 1532 1533 FoldingSetNodeID ID; 1534 ID.AddInteger(scAddRecExpr); 1535 ID.AddPointer(PreStart); 1536 ID.AddPointer(Step); 1537 ID.AddPointer(L); 1538 void *IP = nullptr; 1539 const auto *PreAR = 1540 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1541 1542 // Give up if we don't already have the add recurrence we need because 1543 // actually constructing an add recurrence is relatively expensive. 1544 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1545 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1546 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1547 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1548 DeltaS, &Pred, this); 1549 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1550 return true; 1551 } 1552 } 1553 1554 return false; 1555 } 1556 1557 // Finds an integer D for an expression (C + x + y + ...) such that the top 1558 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1559 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1560 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1561 // the (C + x + y + ...) expression is \p WholeAddExpr. 1562 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1563 const SCEVConstant *ConstantTerm, 1564 const SCEVAddExpr *WholeAddExpr) { 1565 const APInt &C = ConstantTerm->getAPInt(); 1566 const unsigned BitWidth = C.getBitWidth(); 1567 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1568 uint32_t TZ = BitWidth; 1569 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1570 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1571 if (TZ) { 1572 // Set D to be as many least significant bits of C as possible while still 1573 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1574 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1575 } 1576 return APInt(BitWidth, 0); 1577 } 1578 1579 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1580 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1581 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1582 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1583 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1584 const APInt &ConstantStart, 1585 const SCEV *Step) { 1586 const unsigned BitWidth = ConstantStart.getBitWidth(); 1587 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1588 if (TZ) 1589 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1590 : ConstantStart; 1591 return APInt(BitWidth, 0); 1592 } 1593 1594 const SCEV * 1595 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1596 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1597 "This is not an extending conversion!"); 1598 assert(isSCEVable(Ty) && 1599 "This is not a conversion to a SCEVable type!"); 1600 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1601 Ty = getEffectiveSCEVType(Ty); 1602 1603 // Fold if the operand is constant. 1604 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1605 return getConstant( 1606 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1607 1608 // zext(zext(x)) --> zext(x) 1609 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1610 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1611 1612 // Before doing any expensive analysis, check to see if we've already 1613 // computed a SCEV for this Op and Ty. 1614 FoldingSetNodeID ID; 1615 ID.AddInteger(scZeroExtend); 1616 ID.AddPointer(Op); 1617 ID.AddPointer(Ty); 1618 void *IP = nullptr; 1619 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1620 if (Depth > MaxCastDepth) { 1621 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1622 Op, Ty); 1623 UniqueSCEVs.InsertNode(S, IP); 1624 registerUser(S, Op); 1625 return S; 1626 } 1627 1628 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1629 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1630 // It's possible the bits taken off by the truncate were all zero bits. If 1631 // so, we should be able to simplify this further. 1632 const SCEV *X = ST->getOperand(); 1633 ConstantRange CR = getUnsignedRange(X); 1634 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1635 unsigned NewBits = getTypeSizeInBits(Ty); 1636 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1637 CR.zextOrTrunc(NewBits))) 1638 return getTruncateOrZeroExtend(X, Ty, Depth); 1639 } 1640 1641 // If the input value is a chrec scev, and we can prove that the value 1642 // did not overflow the old, smaller, value, we can zero extend all of the 1643 // operands (often constants). This allows analysis of something like 1644 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1645 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1646 if (AR->isAffine()) { 1647 const SCEV *Start = AR->getStart(); 1648 const SCEV *Step = AR->getStepRecurrence(*this); 1649 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1650 const Loop *L = AR->getLoop(); 1651 1652 if (!AR->hasNoUnsignedWrap()) { 1653 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1654 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1655 } 1656 1657 // If we have special knowledge that this addrec won't overflow, 1658 // we don't need to do any further analysis. 1659 if (AR->hasNoUnsignedWrap()) 1660 return getAddRecExpr( 1661 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1662 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1663 1664 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1665 // Note that this serves two purposes: It filters out loops that are 1666 // simply not analyzable, and it covers the case where this code is 1667 // being called from within backedge-taken count analysis, such that 1668 // attempting to ask for the backedge-taken count would likely result 1669 // in infinite recursion. In the later case, the analysis code will 1670 // cope with a conservative value, and it will take care to purge 1671 // that value once it has finished. 1672 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1673 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1674 // Manually compute the final value for AR, checking for overflow. 1675 1676 // Check whether the backedge-taken count can be losslessly casted to 1677 // the addrec's type. The count is always unsigned. 1678 const SCEV *CastedMaxBECount = 1679 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1680 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1681 CastedMaxBECount, MaxBECount->getType(), Depth); 1682 if (MaxBECount == RecastedMaxBECount) { 1683 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1684 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1685 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1686 SCEV::FlagAnyWrap, Depth + 1); 1687 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1688 SCEV::FlagAnyWrap, 1689 Depth + 1), 1690 WideTy, Depth + 1); 1691 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1692 const SCEV *WideMaxBECount = 1693 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1694 const SCEV *OperandExtendedAdd = 1695 getAddExpr(WideStart, 1696 getMulExpr(WideMaxBECount, 1697 getZeroExtendExpr(Step, WideTy, Depth + 1), 1698 SCEV::FlagAnyWrap, Depth + 1), 1699 SCEV::FlagAnyWrap, Depth + 1); 1700 if (ZAdd == OperandExtendedAdd) { 1701 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1702 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1703 // Return the expression with the addrec on the outside. 1704 return getAddRecExpr( 1705 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1706 Depth + 1), 1707 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1708 AR->getNoWrapFlags()); 1709 } 1710 // Similar to above, only this time treat the step value as signed. 1711 // This covers loops that count down. 1712 OperandExtendedAdd = 1713 getAddExpr(WideStart, 1714 getMulExpr(WideMaxBECount, 1715 getSignExtendExpr(Step, WideTy, Depth + 1), 1716 SCEV::FlagAnyWrap, Depth + 1), 1717 SCEV::FlagAnyWrap, Depth + 1); 1718 if (ZAdd == OperandExtendedAdd) { 1719 // Cache knowledge of AR NW, which is propagated to this AddRec. 1720 // Negative step causes unsigned wrap, but it still can't self-wrap. 1721 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1722 // Return the expression with the addrec on the outside. 1723 return getAddRecExpr( 1724 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1725 Depth + 1), 1726 getSignExtendExpr(Step, Ty, Depth + 1), L, 1727 AR->getNoWrapFlags()); 1728 } 1729 } 1730 } 1731 1732 // Normally, in the cases we can prove no-overflow via a 1733 // backedge guarding condition, we can also compute a backedge 1734 // taken count for the loop. The exceptions are assumptions and 1735 // guards present in the loop -- SCEV is not great at exploiting 1736 // these to compute max backedge taken counts, but can still use 1737 // these to prove lack of overflow. Use this fact to avoid 1738 // doing extra work that may not pay off. 1739 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1740 !AC.assumptions().empty()) { 1741 1742 auto NewFlags = proveNoUnsignedWrapViaInduction(AR); 1743 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1744 if (AR->hasNoUnsignedWrap()) { 1745 // Same as nuw case above - duplicated here to avoid a compile time 1746 // issue. It's not clear that the order of checks does matter, but 1747 // it's one of two issue possible causes for a change which was 1748 // reverted. Be conservative for the moment. 1749 return getAddRecExpr( 1750 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1751 Depth + 1), 1752 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1753 AR->getNoWrapFlags()); 1754 } 1755 1756 // For a negative step, we can extend the operands iff doing so only 1757 // traverses values in the range zext([0,UINT_MAX]). 1758 if (isKnownNegative(Step)) { 1759 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1760 getSignedRangeMin(Step)); 1761 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1762 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1763 // Cache knowledge of AR NW, which is propagated to this 1764 // AddRec. Negative step causes unsigned wrap, but it 1765 // still can't self-wrap. 1766 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1767 // Return the expression with the addrec on the outside. 1768 return getAddRecExpr( 1769 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1770 Depth + 1), 1771 getSignExtendExpr(Step, Ty, Depth + 1), L, 1772 AR->getNoWrapFlags()); 1773 } 1774 } 1775 } 1776 1777 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1778 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1779 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1780 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1781 const APInt &C = SC->getAPInt(); 1782 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1783 if (D != 0) { 1784 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1785 const SCEV *SResidual = 1786 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1787 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1788 return getAddExpr(SZExtD, SZExtR, 1789 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1790 Depth + 1); 1791 } 1792 } 1793 1794 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1795 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1796 return getAddRecExpr( 1797 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1798 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1799 } 1800 } 1801 1802 // zext(A % B) --> zext(A) % zext(B) 1803 { 1804 const SCEV *LHS; 1805 const SCEV *RHS; 1806 if (matchURem(Op, LHS, RHS)) 1807 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1808 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1809 } 1810 1811 // zext(A / B) --> zext(A) / zext(B). 1812 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1813 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1814 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1815 1816 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1817 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1818 if (SA->hasNoUnsignedWrap()) { 1819 // If the addition does not unsign overflow then we can, by definition, 1820 // commute the zero extension with the addition operation. 1821 SmallVector<const SCEV *, 4> Ops; 1822 for (const auto *Op : SA->operands()) 1823 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1824 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1825 } 1826 1827 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1828 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1829 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1830 // 1831 // Often address arithmetics contain expressions like 1832 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1833 // This transformation is useful while proving that such expressions are 1834 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1835 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1836 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1837 if (D != 0) { 1838 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1839 const SCEV *SResidual = 1840 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1841 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1842 return getAddExpr(SZExtD, SZExtR, 1843 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1844 Depth + 1); 1845 } 1846 } 1847 } 1848 1849 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1850 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1851 if (SM->hasNoUnsignedWrap()) { 1852 // If the multiply does not unsign overflow then we can, by definition, 1853 // commute the zero extension with the multiply operation. 1854 SmallVector<const SCEV *, 4> Ops; 1855 for (const auto *Op : SM->operands()) 1856 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1857 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1858 } 1859 1860 // zext(2^K * (trunc X to iN)) to iM -> 1861 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1862 // 1863 // Proof: 1864 // 1865 // zext(2^K * (trunc X to iN)) to iM 1866 // = zext((trunc X to iN) << K) to iM 1867 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1868 // (because shl removes the top K bits) 1869 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1870 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1871 // 1872 if (SM->getNumOperands() == 2) 1873 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1874 if (MulLHS->getAPInt().isPowerOf2()) 1875 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1876 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1877 MulLHS->getAPInt().logBase2(); 1878 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1879 return getMulExpr( 1880 getZeroExtendExpr(MulLHS, Ty), 1881 getZeroExtendExpr( 1882 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1883 SCEV::FlagNUW, Depth + 1); 1884 } 1885 } 1886 1887 // The cast wasn't folded; create an explicit cast node. 1888 // Recompute the insert position, as it may have been invalidated. 1889 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1890 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1891 Op, Ty); 1892 UniqueSCEVs.InsertNode(S, IP); 1893 registerUser(S, Op); 1894 return S; 1895 } 1896 1897 const SCEV * 1898 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1899 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1900 "This is not an extending conversion!"); 1901 assert(isSCEVable(Ty) && 1902 "This is not a conversion to a SCEVable type!"); 1903 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1904 Ty = getEffectiveSCEVType(Ty); 1905 1906 // Fold if the operand is constant. 1907 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1908 return getConstant( 1909 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1910 1911 // sext(sext(x)) --> sext(x) 1912 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1913 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1914 1915 // sext(zext(x)) --> zext(x) 1916 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1917 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1918 1919 // Before doing any expensive analysis, check to see if we've already 1920 // computed a SCEV for this Op and Ty. 1921 FoldingSetNodeID ID; 1922 ID.AddInteger(scSignExtend); 1923 ID.AddPointer(Op); 1924 ID.AddPointer(Ty); 1925 void *IP = nullptr; 1926 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1927 // Limit recursion depth. 1928 if (Depth > MaxCastDepth) { 1929 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1930 Op, Ty); 1931 UniqueSCEVs.InsertNode(S, IP); 1932 registerUser(S, Op); 1933 return S; 1934 } 1935 1936 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1937 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1938 // It's possible the bits taken off by the truncate were all sign bits. If 1939 // so, we should be able to simplify this further. 1940 const SCEV *X = ST->getOperand(); 1941 ConstantRange CR = getSignedRange(X); 1942 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1943 unsigned NewBits = getTypeSizeInBits(Ty); 1944 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1945 CR.sextOrTrunc(NewBits))) 1946 return getTruncateOrSignExtend(X, Ty, Depth); 1947 } 1948 1949 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1950 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1951 if (SA->hasNoSignedWrap()) { 1952 // If the addition does not sign overflow then we can, by definition, 1953 // commute the sign extension with the addition operation. 1954 SmallVector<const SCEV *, 4> Ops; 1955 for (const auto *Op : SA->operands()) 1956 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1957 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1958 } 1959 1960 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1961 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1962 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1963 // 1964 // For instance, this will bring two seemingly different expressions: 1965 // 1 + sext(5 + 20 * %x + 24 * %y) and 1966 // sext(6 + 20 * %x + 24 * %y) 1967 // to the same form: 1968 // 2 + sext(4 + 20 * %x + 24 * %y) 1969 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1970 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1971 if (D != 0) { 1972 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1973 const SCEV *SResidual = 1974 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1975 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1976 return getAddExpr(SSExtD, SSExtR, 1977 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1978 Depth + 1); 1979 } 1980 } 1981 } 1982 // If the input value is a chrec scev, and we can prove that the value 1983 // did not overflow the old, smaller, value, we can sign extend all of the 1984 // operands (often constants). This allows analysis of something like 1985 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1986 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1987 if (AR->isAffine()) { 1988 const SCEV *Start = AR->getStart(); 1989 const SCEV *Step = AR->getStepRecurrence(*this); 1990 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1991 const Loop *L = AR->getLoop(); 1992 1993 if (!AR->hasNoSignedWrap()) { 1994 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1995 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1996 } 1997 1998 // If we have special knowledge that this addrec won't overflow, 1999 // we don't need to do any further analysis. 2000 if (AR->hasNoSignedWrap()) 2001 return getAddRecExpr( 2002 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2003 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 2004 2005 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2006 // Note that this serves two purposes: It filters out loops that are 2007 // simply not analyzable, and it covers the case where this code is 2008 // being called from within backedge-taken count analysis, such that 2009 // attempting to ask for the backedge-taken count would likely result 2010 // in infinite recursion. In the later case, the analysis code will 2011 // cope with a conservative value, and it will take care to purge 2012 // that value once it has finished. 2013 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 2014 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2015 // Manually compute the final value for AR, checking for 2016 // overflow. 2017 2018 // Check whether the backedge-taken count can be losslessly casted to 2019 // the addrec's type. The count is always unsigned. 2020 const SCEV *CastedMaxBECount = 2021 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2022 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2023 CastedMaxBECount, MaxBECount->getType(), Depth); 2024 if (MaxBECount == RecastedMaxBECount) { 2025 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2026 // Check whether Start+Step*MaxBECount has no signed overflow. 2027 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2028 SCEV::FlagAnyWrap, Depth + 1); 2029 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2030 SCEV::FlagAnyWrap, 2031 Depth + 1), 2032 WideTy, Depth + 1); 2033 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2034 const SCEV *WideMaxBECount = 2035 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2036 const SCEV *OperandExtendedAdd = 2037 getAddExpr(WideStart, 2038 getMulExpr(WideMaxBECount, 2039 getSignExtendExpr(Step, WideTy, Depth + 1), 2040 SCEV::FlagAnyWrap, Depth + 1), 2041 SCEV::FlagAnyWrap, Depth + 1); 2042 if (SAdd == OperandExtendedAdd) { 2043 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2044 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2045 // Return the expression with the addrec on the outside. 2046 return getAddRecExpr( 2047 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2048 Depth + 1), 2049 getSignExtendExpr(Step, Ty, Depth + 1), L, 2050 AR->getNoWrapFlags()); 2051 } 2052 // Similar to above, only this time treat the step value as unsigned. 2053 // This covers loops that count up with an unsigned step. 2054 OperandExtendedAdd = 2055 getAddExpr(WideStart, 2056 getMulExpr(WideMaxBECount, 2057 getZeroExtendExpr(Step, WideTy, Depth + 1), 2058 SCEV::FlagAnyWrap, Depth + 1), 2059 SCEV::FlagAnyWrap, Depth + 1); 2060 if (SAdd == OperandExtendedAdd) { 2061 // If AR wraps around then 2062 // 2063 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2064 // => SAdd != OperandExtendedAdd 2065 // 2066 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2067 // (SAdd == OperandExtendedAdd => AR is NW) 2068 2069 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 2070 2071 // Return the expression with the addrec on the outside. 2072 return getAddRecExpr( 2073 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2074 Depth + 1), 2075 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2076 AR->getNoWrapFlags()); 2077 } 2078 } 2079 } 2080 2081 auto NewFlags = proveNoSignedWrapViaInduction(AR); 2082 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 2083 if (AR->hasNoSignedWrap()) { 2084 // Same as nsw case above - duplicated here to avoid a compile time 2085 // issue. It's not clear that the order of checks does matter, but 2086 // it's one of two issue possible causes for a change which was 2087 // reverted. Be conservative for the moment. 2088 return getAddRecExpr( 2089 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2090 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2091 } 2092 2093 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2094 // if D + (C - D + Step * n) could be proven to not signed wrap 2095 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2096 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2097 const APInt &C = SC->getAPInt(); 2098 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2099 if (D != 0) { 2100 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2101 const SCEV *SResidual = 2102 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2103 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2104 return getAddExpr(SSExtD, SSExtR, 2105 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2106 Depth + 1); 2107 } 2108 } 2109 2110 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2111 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2112 return getAddRecExpr( 2113 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2114 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2115 } 2116 } 2117 2118 // If the input value is provably positive and we could not simplify 2119 // away the sext build a zext instead. 2120 if (isKnownNonNegative(Op)) 2121 return getZeroExtendExpr(Op, Ty, Depth + 1); 2122 2123 // The cast wasn't folded; create an explicit cast node. 2124 // Recompute the insert position, as it may have been invalidated. 2125 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2126 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2127 Op, Ty); 2128 UniqueSCEVs.InsertNode(S, IP); 2129 registerUser(S, { Op }); 2130 return S; 2131 } 2132 2133 const SCEV *ScalarEvolution::getCastExpr(SCEVTypes Kind, const SCEV *Op, 2134 Type *Ty) { 2135 switch (Kind) { 2136 case scTruncate: 2137 return getTruncateExpr(Op, Ty); 2138 case scZeroExtend: 2139 return getZeroExtendExpr(Op, Ty); 2140 case scSignExtend: 2141 return getSignExtendExpr(Op, Ty); 2142 case scPtrToInt: 2143 return getPtrToIntExpr(Op, Ty); 2144 default: 2145 llvm_unreachable("Not a SCEV cast expression!"); 2146 } 2147 } 2148 2149 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2150 /// unspecified bits out to the given type. 2151 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2152 Type *Ty) { 2153 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2154 "This is not an extending conversion!"); 2155 assert(isSCEVable(Ty) && 2156 "This is not a conversion to a SCEVable type!"); 2157 Ty = getEffectiveSCEVType(Ty); 2158 2159 // Sign-extend negative constants. 2160 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2161 if (SC->getAPInt().isNegative()) 2162 return getSignExtendExpr(Op, Ty); 2163 2164 // Peel off a truncate cast. 2165 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2166 const SCEV *NewOp = T->getOperand(); 2167 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2168 return getAnyExtendExpr(NewOp, Ty); 2169 return getTruncateOrNoop(NewOp, Ty); 2170 } 2171 2172 // Next try a zext cast. If the cast is folded, use it. 2173 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2174 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2175 return ZExt; 2176 2177 // Next try a sext cast. If the cast is folded, use it. 2178 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2179 if (!isa<SCEVSignExtendExpr>(SExt)) 2180 return SExt; 2181 2182 // Force the cast to be folded into the operands of an addrec. 2183 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2184 SmallVector<const SCEV *, 4> Ops; 2185 for (const SCEV *Op : AR->operands()) 2186 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2187 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2188 } 2189 2190 // If the expression is obviously signed, use the sext cast value. 2191 if (isa<SCEVSMaxExpr>(Op)) 2192 return SExt; 2193 2194 // Absent any other information, use the zext cast value. 2195 return ZExt; 2196 } 2197 2198 /// Process the given Ops list, which is a list of operands to be added under 2199 /// the given scale, update the given map. This is a helper function for 2200 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2201 /// that would form an add expression like this: 2202 /// 2203 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2204 /// 2205 /// where A and B are constants, update the map with these values: 2206 /// 2207 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2208 /// 2209 /// and add 13 + A*B*29 to AccumulatedConstant. 2210 /// This will allow getAddRecExpr to produce this: 2211 /// 2212 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2213 /// 2214 /// This form often exposes folding opportunities that are hidden in 2215 /// the original operand list. 2216 /// 2217 /// Return true iff it appears that any interesting folding opportunities 2218 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2219 /// the common case where no interesting opportunities are present, and 2220 /// is also used as a check to avoid infinite recursion. 2221 static bool 2222 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2223 SmallVectorImpl<const SCEV *> &NewOps, 2224 APInt &AccumulatedConstant, 2225 const SCEV *const *Ops, size_t NumOperands, 2226 const APInt &Scale, 2227 ScalarEvolution &SE) { 2228 bool Interesting = false; 2229 2230 // Iterate over the add operands. They are sorted, with constants first. 2231 unsigned i = 0; 2232 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2233 ++i; 2234 // Pull a buried constant out to the outside. 2235 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2236 Interesting = true; 2237 AccumulatedConstant += Scale * C->getAPInt(); 2238 } 2239 2240 // Next comes everything else. We're especially interested in multiplies 2241 // here, but they're in the middle, so just visit the rest with one loop. 2242 for (; i != NumOperands; ++i) { 2243 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2244 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2245 APInt NewScale = 2246 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2247 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2248 // A multiplication of a constant with another add; recurse. 2249 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2250 Interesting |= 2251 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2252 Add->op_begin(), Add->getNumOperands(), 2253 NewScale, SE); 2254 } else { 2255 // A multiplication of a constant with some other value. Update 2256 // the map. 2257 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands())); 2258 const SCEV *Key = SE.getMulExpr(MulOps); 2259 auto Pair = M.insert({Key, NewScale}); 2260 if (Pair.second) { 2261 NewOps.push_back(Pair.first->first); 2262 } else { 2263 Pair.first->second += NewScale; 2264 // The map already had an entry for this value, which may indicate 2265 // a folding opportunity. 2266 Interesting = true; 2267 } 2268 } 2269 } else { 2270 // An ordinary operand. Update the map. 2271 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2272 M.insert({Ops[i], Scale}); 2273 if (Pair.second) { 2274 NewOps.push_back(Pair.first->first); 2275 } else { 2276 Pair.first->second += Scale; 2277 // The map already had an entry for this value, which may indicate 2278 // a folding opportunity. 2279 Interesting = true; 2280 } 2281 } 2282 } 2283 2284 return Interesting; 2285 } 2286 2287 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, 2288 const SCEV *LHS, const SCEV *RHS) { 2289 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *, 2290 SCEV::NoWrapFlags, unsigned); 2291 switch (BinOp) { 2292 default: 2293 llvm_unreachable("Unsupported binary op"); 2294 case Instruction::Add: 2295 Operation = &ScalarEvolution::getAddExpr; 2296 break; 2297 case Instruction::Sub: 2298 Operation = &ScalarEvolution::getMinusSCEV; 2299 break; 2300 case Instruction::Mul: 2301 Operation = &ScalarEvolution::getMulExpr; 2302 break; 2303 } 2304 2305 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) = 2306 Signed ? &ScalarEvolution::getSignExtendExpr 2307 : &ScalarEvolution::getZeroExtendExpr; 2308 2309 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS) 2310 auto *NarrowTy = cast<IntegerType>(LHS->getType()); 2311 auto *WideTy = 2312 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2); 2313 2314 const SCEV *A = (this->*Extension)( 2315 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0); 2316 const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0), 2317 (this->*Extension)(RHS, WideTy, 0), 2318 SCEV::FlagAnyWrap, 0); 2319 return A == B; 2320 } 2321 2322 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/> 2323 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp( 2324 const OverflowingBinaryOperator *OBO) { 2325 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap; 2326 2327 if (OBO->hasNoUnsignedWrap()) 2328 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2329 if (OBO->hasNoSignedWrap()) 2330 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2331 2332 bool Deduced = false; 2333 2334 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap()) 2335 return {Flags, Deduced}; 2336 2337 if (OBO->getOpcode() != Instruction::Add && 2338 OBO->getOpcode() != Instruction::Sub && 2339 OBO->getOpcode() != Instruction::Mul) 2340 return {Flags, Deduced}; 2341 2342 const SCEV *LHS = getSCEV(OBO->getOperand(0)); 2343 const SCEV *RHS = getSCEV(OBO->getOperand(1)); 2344 2345 if (!OBO->hasNoUnsignedWrap() && 2346 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2347 /* Signed */ false, LHS, RHS)) { 2348 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2349 Deduced = true; 2350 } 2351 2352 if (!OBO->hasNoSignedWrap() && 2353 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2354 /* Signed */ true, LHS, RHS)) { 2355 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2356 Deduced = true; 2357 } 2358 2359 return {Flags, Deduced}; 2360 } 2361 2362 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2363 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2364 // can't-overflow flags for the operation if possible. 2365 static SCEV::NoWrapFlags 2366 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2367 const ArrayRef<const SCEV *> Ops, 2368 SCEV::NoWrapFlags Flags) { 2369 using namespace std::placeholders; 2370 2371 using OBO = OverflowingBinaryOperator; 2372 2373 bool CanAnalyze = 2374 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2375 (void)CanAnalyze; 2376 assert(CanAnalyze && "don't call from other places!"); 2377 2378 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2379 SCEV::NoWrapFlags SignOrUnsignWrap = 2380 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2381 2382 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2383 auto IsKnownNonNegative = [&](const SCEV *S) { 2384 return SE->isKnownNonNegative(S); 2385 }; 2386 2387 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2388 Flags = 2389 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2390 2391 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2392 2393 if (SignOrUnsignWrap != SignOrUnsignMask && 2394 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2395 isa<SCEVConstant>(Ops[0])) { 2396 2397 auto Opcode = [&] { 2398 switch (Type) { 2399 case scAddExpr: 2400 return Instruction::Add; 2401 case scMulExpr: 2402 return Instruction::Mul; 2403 default: 2404 llvm_unreachable("Unexpected SCEV op."); 2405 } 2406 }(); 2407 2408 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2409 2410 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2411 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2412 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2413 Opcode, C, OBO::NoSignedWrap); 2414 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2415 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2416 } 2417 2418 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2419 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2420 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2421 Opcode, C, OBO::NoUnsignedWrap); 2422 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2423 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2424 } 2425 } 2426 2427 // <0,+,nonnegative><nw> is also nuw 2428 // TODO: Add corresponding nsw case 2429 if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) && 2430 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 && 2431 Ops[0]->isZero() && IsKnownNonNegative(Ops[1])) 2432 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2433 2434 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW 2435 if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && 2436 Ops.size() == 2) { 2437 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0])) 2438 if (UDiv->getOperand(1) == Ops[1]) 2439 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2440 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1])) 2441 if (UDiv->getOperand(1) == Ops[0]) 2442 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2443 } 2444 2445 return Flags; 2446 } 2447 2448 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2449 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2450 } 2451 2452 /// Get a canonical add expression, or something simpler if possible. 2453 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2454 SCEV::NoWrapFlags OrigFlags, 2455 unsigned Depth) { 2456 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2457 "only nuw or nsw allowed"); 2458 assert(!Ops.empty() && "Cannot get empty add!"); 2459 if (Ops.size() == 1) return Ops[0]; 2460 #ifndef NDEBUG 2461 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2462 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2463 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2464 "SCEVAddExpr operand types don't match!"); 2465 unsigned NumPtrs = count_if( 2466 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); }); 2467 assert(NumPtrs <= 1 && "add has at most one pointer operand"); 2468 #endif 2469 2470 // Sort by complexity, this groups all similar expression types together. 2471 GroupByComplexity(Ops, &LI, DT); 2472 2473 // If there are any constants, fold them together. 2474 unsigned Idx = 0; 2475 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2476 ++Idx; 2477 assert(Idx < Ops.size()); 2478 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2479 // We found two constants, fold them together! 2480 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2481 if (Ops.size() == 2) return Ops[0]; 2482 Ops.erase(Ops.begin()+1); // Erase the folded element 2483 LHSC = cast<SCEVConstant>(Ops[0]); 2484 } 2485 2486 // If we are left with a constant zero being added, strip it off. 2487 if (LHSC->getValue()->isZero()) { 2488 Ops.erase(Ops.begin()); 2489 --Idx; 2490 } 2491 2492 if (Ops.size() == 1) return Ops[0]; 2493 } 2494 2495 // Delay expensive flag strengthening until necessary. 2496 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2497 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2498 }; 2499 2500 // Limit recursion calls depth. 2501 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2502 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2503 2504 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) { 2505 // Don't strengthen flags if we have no new information. 2506 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2507 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2508 Add->setNoWrapFlags(ComputeFlags(Ops)); 2509 return S; 2510 } 2511 2512 // Okay, check to see if the same value occurs in the operand list more than 2513 // once. If so, merge them together into an multiply expression. Since we 2514 // sorted the list, these values are required to be adjacent. 2515 Type *Ty = Ops[0]->getType(); 2516 bool FoundMatch = false; 2517 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2518 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2519 // Scan ahead to count how many equal operands there are. 2520 unsigned Count = 2; 2521 while (i+Count != e && Ops[i+Count] == Ops[i]) 2522 ++Count; 2523 // Merge the values into a multiply. 2524 const SCEV *Scale = getConstant(Ty, Count); 2525 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2526 if (Ops.size() == Count) 2527 return Mul; 2528 Ops[i] = Mul; 2529 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2530 --i; e -= Count - 1; 2531 FoundMatch = true; 2532 } 2533 if (FoundMatch) 2534 return getAddExpr(Ops, OrigFlags, Depth + 1); 2535 2536 // Check for truncates. If all the operands are truncated from the same 2537 // type, see if factoring out the truncate would permit the result to be 2538 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2539 // if the contents of the resulting outer trunc fold to something simple. 2540 auto FindTruncSrcType = [&]() -> Type * { 2541 // We're ultimately looking to fold an addrec of truncs and muls of only 2542 // constants and truncs, so if we find any other types of SCEV 2543 // as operands of the addrec then we bail and return nullptr here. 2544 // Otherwise, we return the type of the operand of a trunc that we find. 2545 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2546 return T->getOperand()->getType(); 2547 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2548 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2549 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2550 return T->getOperand()->getType(); 2551 } 2552 return nullptr; 2553 }; 2554 if (auto *SrcType = FindTruncSrcType()) { 2555 SmallVector<const SCEV *, 8> LargeOps; 2556 bool Ok = true; 2557 // Check all the operands to see if they can be represented in the 2558 // source type of the truncate. 2559 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2560 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2561 if (T->getOperand()->getType() != SrcType) { 2562 Ok = false; 2563 break; 2564 } 2565 LargeOps.push_back(T->getOperand()); 2566 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2567 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2568 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2569 SmallVector<const SCEV *, 8> LargeMulOps; 2570 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2571 if (const SCEVTruncateExpr *T = 2572 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2573 if (T->getOperand()->getType() != SrcType) { 2574 Ok = false; 2575 break; 2576 } 2577 LargeMulOps.push_back(T->getOperand()); 2578 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2579 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2580 } else { 2581 Ok = false; 2582 break; 2583 } 2584 } 2585 if (Ok) 2586 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2587 } else { 2588 Ok = false; 2589 break; 2590 } 2591 } 2592 if (Ok) { 2593 // Evaluate the expression in the larger type. 2594 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2595 // If it folds to something simple, use it. Otherwise, don't. 2596 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2597 return getTruncateExpr(Fold, Ty); 2598 } 2599 } 2600 2601 if (Ops.size() == 2) { 2602 // Check if we have an expression of the form ((X + C1) - C2), where C1 and 2603 // C2 can be folded in a way that allows retaining wrapping flags of (X + 2604 // C1). 2605 const SCEV *A = Ops[0]; 2606 const SCEV *B = Ops[1]; 2607 auto *AddExpr = dyn_cast<SCEVAddExpr>(B); 2608 auto *C = dyn_cast<SCEVConstant>(A); 2609 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) { 2610 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt(); 2611 auto C2 = C->getAPInt(); 2612 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap; 2613 2614 APInt ConstAdd = C1 + C2; 2615 auto AddFlags = AddExpr->getNoWrapFlags(); 2616 // Adding a smaller constant is NUW if the original AddExpr was NUW. 2617 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) && 2618 ConstAdd.ule(C1)) { 2619 PreservedFlags = 2620 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW); 2621 } 2622 2623 // Adding a constant with the same sign and small magnitude is NSW, if the 2624 // original AddExpr was NSW. 2625 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) && 2626 C1.isSignBitSet() == ConstAdd.isSignBitSet() && 2627 ConstAdd.abs().ule(C1.abs())) { 2628 PreservedFlags = 2629 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW); 2630 } 2631 2632 if (PreservedFlags != SCEV::FlagAnyWrap) { 2633 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands()); 2634 NewOps[0] = getConstant(ConstAdd); 2635 return getAddExpr(NewOps, PreservedFlags); 2636 } 2637 } 2638 } 2639 2640 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y) 2641 if (Ops.size() == 2) { 2642 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]); 2643 if (Mul && Mul->getNumOperands() == 2 && 2644 Mul->getOperand(0)->isAllOnesValue()) { 2645 const SCEV *X; 2646 const SCEV *Y; 2647 if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) { 2648 return getMulExpr(Y, getUDivExpr(X, Y)); 2649 } 2650 } 2651 } 2652 2653 // Skip past any other cast SCEVs. 2654 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2655 ++Idx; 2656 2657 // If there are add operands they would be next. 2658 if (Idx < Ops.size()) { 2659 bool DeletedAdd = false; 2660 // If the original flags and all inlined SCEVAddExprs are NUW, use the 2661 // common NUW flag for expression after inlining. Other flags cannot be 2662 // preserved, because they may depend on the original order of operations. 2663 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW); 2664 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2665 if (Ops.size() > AddOpsInlineThreshold || 2666 Add->getNumOperands() > AddOpsInlineThreshold) 2667 break; 2668 // If we have an add, expand the add operands onto the end of the operands 2669 // list. 2670 Ops.erase(Ops.begin()+Idx); 2671 Ops.append(Add->op_begin(), Add->op_end()); 2672 DeletedAdd = true; 2673 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags()); 2674 } 2675 2676 // If we deleted at least one add, we added operands to the end of the list, 2677 // and they are not necessarily sorted. Recurse to resort and resimplify 2678 // any operands we just acquired. 2679 if (DeletedAdd) 2680 return getAddExpr(Ops, CommonFlags, Depth + 1); 2681 } 2682 2683 // Skip over the add expression until we get to a multiply. 2684 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2685 ++Idx; 2686 2687 // Check to see if there are any folding opportunities present with 2688 // operands multiplied by constant values. 2689 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2690 uint64_t BitWidth = getTypeSizeInBits(Ty); 2691 DenseMap<const SCEV *, APInt> M; 2692 SmallVector<const SCEV *, 8> NewOps; 2693 APInt AccumulatedConstant(BitWidth, 0); 2694 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2695 Ops.data(), Ops.size(), 2696 APInt(BitWidth, 1), *this)) { 2697 struct APIntCompare { 2698 bool operator()(const APInt &LHS, const APInt &RHS) const { 2699 return LHS.ult(RHS); 2700 } 2701 }; 2702 2703 // Some interesting folding opportunity is present, so its worthwhile to 2704 // re-generate the operands list. Group the operands by constant scale, 2705 // to avoid multiplying by the same constant scale multiple times. 2706 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2707 for (const SCEV *NewOp : NewOps) 2708 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2709 // Re-generate the operands list. 2710 Ops.clear(); 2711 if (AccumulatedConstant != 0) 2712 Ops.push_back(getConstant(AccumulatedConstant)); 2713 for (auto &MulOp : MulOpLists) { 2714 if (MulOp.first == 1) { 2715 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)); 2716 } else if (MulOp.first != 0) { 2717 Ops.push_back(getMulExpr( 2718 getConstant(MulOp.first), 2719 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2720 SCEV::FlagAnyWrap, Depth + 1)); 2721 } 2722 } 2723 if (Ops.empty()) 2724 return getZero(Ty); 2725 if (Ops.size() == 1) 2726 return Ops[0]; 2727 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2728 } 2729 } 2730 2731 // If we are adding something to a multiply expression, make sure the 2732 // something is not already an operand of the multiply. If so, merge it into 2733 // the multiply. 2734 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2735 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2736 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2737 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2738 if (isa<SCEVConstant>(MulOpSCEV)) 2739 continue; 2740 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2741 if (MulOpSCEV == Ops[AddOp]) { 2742 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2743 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2744 if (Mul->getNumOperands() != 2) { 2745 // If the multiply has more than two operands, we must get the 2746 // Y*Z term. 2747 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2748 Mul->op_begin()+MulOp); 2749 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2750 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2751 } 2752 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2753 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2754 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2755 SCEV::FlagAnyWrap, Depth + 1); 2756 if (Ops.size() == 2) return OuterMul; 2757 if (AddOp < Idx) { 2758 Ops.erase(Ops.begin()+AddOp); 2759 Ops.erase(Ops.begin()+Idx-1); 2760 } else { 2761 Ops.erase(Ops.begin()+Idx); 2762 Ops.erase(Ops.begin()+AddOp-1); 2763 } 2764 Ops.push_back(OuterMul); 2765 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2766 } 2767 2768 // Check this multiply against other multiplies being added together. 2769 for (unsigned OtherMulIdx = Idx+1; 2770 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2771 ++OtherMulIdx) { 2772 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2773 // If MulOp occurs in OtherMul, we can fold the two multiplies 2774 // together. 2775 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2776 OMulOp != e; ++OMulOp) 2777 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2778 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2779 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2780 if (Mul->getNumOperands() != 2) { 2781 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2782 Mul->op_begin()+MulOp); 2783 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2784 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2785 } 2786 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2787 if (OtherMul->getNumOperands() != 2) { 2788 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2789 OtherMul->op_begin()+OMulOp); 2790 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2791 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2792 } 2793 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2794 const SCEV *InnerMulSum = 2795 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2796 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2797 SCEV::FlagAnyWrap, Depth + 1); 2798 if (Ops.size() == 2) return OuterMul; 2799 Ops.erase(Ops.begin()+Idx); 2800 Ops.erase(Ops.begin()+OtherMulIdx-1); 2801 Ops.push_back(OuterMul); 2802 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2803 } 2804 } 2805 } 2806 } 2807 2808 // If there are any add recurrences in the operands list, see if any other 2809 // added values are loop invariant. If so, we can fold them into the 2810 // recurrence. 2811 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2812 ++Idx; 2813 2814 // Scan over all recurrences, trying to fold loop invariants into them. 2815 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2816 // Scan all of the other operands to this add and add them to the vector if 2817 // they are loop invariant w.r.t. the recurrence. 2818 SmallVector<const SCEV *, 8> LIOps; 2819 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2820 const Loop *AddRecLoop = AddRec->getLoop(); 2821 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2822 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2823 LIOps.push_back(Ops[i]); 2824 Ops.erase(Ops.begin()+i); 2825 --i; --e; 2826 } 2827 2828 // If we found some loop invariants, fold them into the recurrence. 2829 if (!LIOps.empty()) { 2830 // Compute nowrap flags for the addition of the loop-invariant ops and 2831 // the addrec. Temporarily push it as an operand for that purpose. These 2832 // flags are valid in the scope of the addrec only. 2833 LIOps.push_back(AddRec); 2834 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2835 LIOps.pop_back(); 2836 2837 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2838 LIOps.push_back(AddRec->getStart()); 2839 2840 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2841 2842 // It is not in general safe to propagate flags valid on an add within 2843 // the addrec scope to one outside it. We must prove that the inner 2844 // scope is guaranteed to execute if the outer one does to be able to 2845 // safely propagate. We know the program is undefined if poison is 2846 // produced on the inner scoped addrec. We also know that *for this use* 2847 // the outer scoped add can't overflow (because of the flags we just 2848 // computed for the inner scoped add) without the program being undefined. 2849 // Proving that entry to the outer scope neccesitates entry to the inner 2850 // scope, thus proves the program undefined if the flags would be violated 2851 // in the outer scope. 2852 SCEV::NoWrapFlags AddFlags = Flags; 2853 if (AddFlags != SCEV::FlagAnyWrap) { 2854 auto *DefI = getDefiningScopeBound(LIOps); 2855 auto *ReachI = &*AddRecLoop->getHeader()->begin(); 2856 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI)) 2857 AddFlags = SCEV::FlagAnyWrap; 2858 } 2859 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1); 2860 2861 // Build the new addrec. Propagate the NUW and NSW flags if both the 2862 // outer add and the inner addrec are guaranteed to have no overflow. 2863 // Always propagate NW. 2864 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2865 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2866 2867 // If all of the other operands were loop invariant, we are done. 2868 if (Ops.size() == 1) return NewRec; 2869 2870 // Otherwise, add the folded AddRec by the non-invariant parts. 2871 for (unsigned i = 0;; ++i) 2872 if (Ops[i] == AddRec) { 2873 Ops[i] = NewRec; 2874 break; 2875 } 2876 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2877 } 2878 2879 // Okay, if there weren't any loop invariants to be folded, check to see if 2880 // there are multiple AddRec's with the same loop induction variable being 2881 // added together. If so, we can fold them. 2882 for (unsigned OtherIdx = Idx+1; 2883 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2884 ++OtherIdx) { 2885 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2886 // so that the 1st found AddRecExpr is dominated by all others. 2887 assert(DT.dominates( 2888 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2889 AddRec->getLoop()->getHeader()) && 2890 "AddRecExprs are not sorted in reverse dominance order?"); 2891 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2892 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2893 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2894 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2895 ++OtherIdx) { 2896 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2897 if (OtherAddRec->getLoop() == AddRecLoop) { 2898 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2899 i != e; ++i) { 2900 if (i >= AddRecOps.size()) { 2901 AddRecOps.append(OtherAddRec->op_begin()+i, 2902 OtherAddRec->op_end()); 2903 break; 2904 } 2905 SmallVector<const SCEV *, 2> TwoOps = { 2906 AddRecOps[i], OtherAddRec->getOperand(i)}; 2907 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2908 } 2909 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2910 } 2911 } 2912 // Step size has changed, so we cannot guarantee no self-wraparound. 2913 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2914 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2915 } 2916 } 2917 2918 // Otherwise couldn't fold anything into this recurrence. Move onto the 2919 // next one. 2920 } 2921 2922 // Okay, it looks like we really DO need an add expr. Check to see if we 2923 // already have one, otherwise create a new one. 2924 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2925 } 2926 2927 const SCEV * 2928 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2929 SCEV::NoWrapFlags Flags) { 2930 FoldingSetNodeID ID; 2931 ID.AddInteger(scAddExpr); 2932 for (const SCEV *Op : Ops) 2933 ID.AddPointer(Op); 2934 void *IP = nullptr; 2935 SCEVAddExpr *S = 2936 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2937 if (!S) { 2938 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2939 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2940 S = new (SCEVAllocator) 2941 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2942 UniqueSCEVs.InsertNode(S, IP); 2943 registerUser(S, Ops); 2944 } 2945 S->setNoWrapFlags(Flags); 2946 return S; 2947 } 2948 2949 const SCEV * 2950 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2951 const Loop *L, SCEV::NoWrapFlags Flags) { 2952 FoldingSetNodeID ID; 2953 ID.AddInteger(scAddRecExpr); 2954 for (const SCEV *Op : Ops) 2955 ID.AddPointer(Op); 2956 ID.AddPointer(L); 2957 void *IP = nullptr; 2958 SCEVAddRecExpr *S = 2959 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2960 if (!S) { 2961 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2962 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2963 S = new (SCEVAllocator) 2964 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2965 UniqueSCEVs.InsertNode(S, IP); 2966 LoopUsers[L].push_back(S); 2967 registerUser(S, Ops); 2968 } 2969 setNoWrapFlags(S, Flags); 2970 return S; 2971 } 2972 2973 const SCEV * 2974 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2975 SCEV::NoWrapFlags Flags) { 2976 FoldingSetNodeID ID; 2977 ID.AddInteger(scMulExpr); 2978 for (const SCEV *Op : Ops) 2979 ID.AddPointer(Op); 2980 void *IP = nullptr; 2981 SCEVMulExpr *S = 2982 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2983 if (!S) { 2984 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2985 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2986 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2987 O, Ops.size()); 2988 UniqueSCEVs.InsertNode(S, IP); 2989 registerUser(S, Ops); 2990 } 2991 S->setNoWrapFlags(Flags); 2992 return S; 2993 } 2994 2995 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2996 uint64_t k = i*j; 2997 if (j > 1 && k / j != i) Overflow = true; 2998 return k; 2999 } 3000 3001 /// Compute the result of "n choose k", the binomial coefficient. If an 3002 /// intermediate computation overflows, Overflow will be set and the return will 3003 /// be garbage. Overflow is not cleared on absence of overflow. 3004 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 3005 // We use the multiplicative formula: 3006 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 3007 // At each iteration, we take the n-th term of the numeral and divide by the 3008 // (k-n)th term of the denominator. This division will always produce an 3009 // integral result, and helps reduce the chance of overflow in the 3010 // intermediate computations. However, we can still overflow even when the 3011 // final result would fit. 3012 3013 if (n == 0 || n == k) return 1; 3014 if (k > n) return 0; 3015 3016 if (k > n/2) 3017 k = n-k; 3018 3019 uint64_t r = 1; 3020 for (uint64_t i = 1; i <= k; ++i) { 3021 r = umul_ov(r, n-(i-1), Overflow); 3022 r /= i; 3023 } 3024 return r; 3025 } 3026 3027 /// Determine if any of the operands in this SCEV are a constant or if 3028 /// any of the add or multiply expressions in this SCEV contain a constant. 3029 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 3030 struct FindConstantInAddMulChain { 3031 bool FoundConstant = false; 3032 3033 bool follow(const SCEV *S) { 3034 FoundConstant |= isa<SCEVConstant>(S); 3035 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 3036 } 3037 3038 bool isDone() const { 3039 return FoundConstant; 3040 } 3041 }; 3042 3043 FindConstantInAddMulChain F; 3044 SCEVTraversal<FindConstantInAddMulChain> ST(F); 3045 ST.visitAll(StartExpr); 3046 return F.FoundConstant; 3047 } 3048 3049 /// Get a canonical multiply expression, or something simpler if possible. 3050 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 3051 SCEV::NoWrapFlags OrigFlags, 3052 unsigned Depth) { 3053 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 3054 "only nuw or nsw allowed"); 3055 assert(!Ops.empty() && "Cannot get empty mul!"); 3056 if (Ops.size() == 1) return Ops[0]; 3057 #ifndef NDEBUG 3058 Type *ETy = Ops[0]->getType(); 3059 assert(!ETy->isPointerTy()); 3060 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3061 assert(Ops[i]->getType() == ETy && 3062 "SCEVMulExpr operand types don't match!"); 3063 #endif 3064 3065 // Sort by complexity, this groups all similar expression types together. 3066 GroupByComplexity(Ops, &LI, DT); 3067 3068 // If there are any constants, fold them together. 3069 unsigned Idx = 0; 3070 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3071 ++Idx; 3072 assert(Idx < Ops.size()); 3073 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3074 // We found two constants, fold them together! 3075 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 3076 if (Ops.size() == 2) return Ops[0]; 3077 Ops.erase(Ops.begin()+1); // Erase the folded element 3078 LHSC = cast<SCEVConstant>(Ops[0]); 3079 } 3080 3081 // If we have a multiply of zero, it will always be zero. 3082 if (LHSC->getValue()->isZero()) 3083 return LHSC; 3084 3085 // If we are left with a constant one being multiplied, strip it off. 3086 if (LHSC->getValue()->isOne()) { 3087 Ops.erase(Ops.begin()); 3088 --Idx; 3089 } 3090 3091 if (Ops.size() == 1) 3092 return Ops[0]; 3093 } 3094 3095 // Delay expensive flag strengthening until necessary. 3096 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 3097 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 3098 }; 3099 3100 // Limit recursion calls depth. 3101 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 3102 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3103 3104 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) { 3105 // Don't strengthen flags if we have no new information. 3106 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 3107 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 3108 Mul->setNoWrapFlags(ComputeFlags(Ops)); 3109 return S; 3110 } 3111 3112 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3113 if (Ops.size() == 2) { 3114 // C1*(C2+V) -> C1*C2 + C1*V 3115 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 3116 // If any of Add's ops are Adds or Muls with a constant, apply this 3117 // transformation as well. 3118 // 3119 // TODO: There are some cases where this transformation is not 3120 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 3121 // this transformation should be narrowed down. 3122 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 3123 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 3124 SCEV::FlagAnyWrap, Depth + 1), 3125 getMulExpr(LHSC, Add->getOperand(1), 3126 SCEV::FlagAnyWrap, Depth + 1), 3127 SCEV::FlagAnyWrap, Depth + 1); 3128 3129 if (Ops[0]->isAllOnesValue()) { 3130 // If we have a mul by -1 of an add, try distributing the -1 among the 3131 // add operands. 3132 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 3133 SmallVector<const SCEV *, 4> NewOps; 3134 bool AnyFolded = false; 3135 for (const SCEV *AddOp : Add->operands()) { 3136 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 3137 Depth + 1); 3138 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 3139 NewOps.push_back(Mul); 3140 } 3141 if (AnyFolded) 3142 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 3143 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 3144 // Negation preserves a recurrence's no self-wrap property. 3145 SmallVector<const SCEV *, 4> Operands; 3146 for (const SCEV *AddRecOp : AddRec->operands()) 3147 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3148 Depth + 1)); 3149 3150 return getAddRecExpr(Operands, AddRec->getLoop(), 3151 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3152 } 3153 } 3154 } 3155 } 3156 3157 // Skip over the add expression until we get to a multiply. 3158 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3159 ++Idx; 3160 3161 // If there are mul operands inline them all into this expression. 3162 if (Idx < Ops.size()) { 3163 bool DeletedMul = false; 3164 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3165 if (Ops.size() > MulOpsInlineThreshold) 3166 break; 3167 // If we have an mul, expand the mul operands onto the end of the 3168 // operands list. 3169 Ops.erase(Ops.begin()+Idx); 3170 Ops.append(Mul->op_begin(), Mul->op_end()); 3171 DeletedMul = true; 3172 } 3173 3174 // If we deleted at least one mul, we added operands to the end of the 3175 // list, and they are not necessarily sorted. Recurse to resort and 3176 // resimplify any operands we just acquired. 3177 if (DeletedMul) 3178 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3179 } 3180 3181 // If there are any add recurrences in the operands list, see if any other 3182 // added values are loop invariant. If so, we can fold them into the 3183 // recurrence. 3184 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3185 ++Idx; 3186 3187 // Scan over all recurrences, trying to fold loop invariants into them. 3188 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3189 // Scan all of the other operands to this mul and add them to the vector 3190 // if they are loop invariant w.r.t. the recurrence. 3191 SmallVector<const SCEV *, 8> LIOps; 3192 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3193 const Loop *AddRecLoop = AddRec->getLoop(); 3194 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3195 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3196 LIOps.push_back(Ops[i]); 3197 Ops.erase(Ops.begin()+i); 3198 --i; --e; 3199 } 3200 3201 // If we found some loop invariants, fold them into the recurrence. 3202 if (!LIOps.empty()) { 3203 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3204 SmallVector<const SCEV *, 4> NewOps; 3205 NewOps.reserve(AddRec->getNumOperands()); 3206 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3207 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3208 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3209 SCEV::FlagAnyWrap, Depth + 1)); 3210 3211 // Build the new addrec. Propagate the NUW and NSW flags if both the 3212 // outer mul and the inner addrec are guaranteed to have no overflow. 3213 // 3214 // No self-wrap cannot be guaranteed after changing the step size, but 3215 // will be inferred if either NUW or NSW is true. 3216 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 3217 const SCEV *NewRec = getAddRecExpr( 3218 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 3219 3220 // If all of the other operands were loop invariant, we are done. 3221 if (Ops.size() == 1) return NewRec; 3222 3223 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3224 for (unsigned i = 0;; ++i) 3225 if (Ops[i] == AddRec) { 3226 Ops[i] = NewRec; 3227 break; 3228 } 3229 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3230 } 3231 3232 // Okay, if there weren't any loop invariants to be folded, check to see 3233 // if there are multiple AddRec's with the same loop induction variable 3234 // being multiplied together. If so, we can fold them. 3235 3236 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3237 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3238 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3239 // ]]],+,...up to x=2n}. 3240 // Note that the arguments to choose() are always integers with values 3241 // known at compile time, never SCEV objects. 3242 // 3243 // The implementation avoids pointless extra computations when the two 3244 // addrec's are of different length (mathematically, it's equivalent to 3245 // an infinite stream of zeros on the right). 3246 bool OpsModified = false; 3247 for (unsigned OtherIdx = Idx+1; 3248 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3249 ++OtherIdx) { 3250 const SCEVAddRecExpr *OtherAddRec = 3251 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3252 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3253 continue; 3254 3255 // Limit max number of arguments to avoid creation of unreasonably big 3256 // SCEVAddRecs with very complex operands. 3257 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3258 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3259 continue; 3260 3261 bool Overflow = false; 3262 Type *Ty = AddRec->getType(); 3263 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3264 SmallVector<const SCEV*, 7> AddRecOps; 3265 for (int x = 0, xe = AddRec->getNumOperands() + 3266 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3267 SmallVector <const SCEV *, 7> SumOps; 3268 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3269 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3270 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3271 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3272 z < ze && !Overflow; ++z) { 3273 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3274 uint64_t Coeff; 3275 if (LargerThan64Bits) 3276 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3277 else 3278 Coeff = Coeff1*Coeff2; 3279 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3280 const SCEV *Term1 = AddRec->getOperand(y-z); 3281 const SCEV *Term2 = OtherAddRec->getOperand(z); 3282 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3283 SCEV::FlagAnyWrap, Depth + 1)); 3284 } 3285 } 3286 if (SumOps.empty()) 3287 SumOps.push_back(getZero(Ty)); 3288 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3289 } 3290 if (!Overflow) { 3291 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3292 SCEV::FlagAnyWrap); 3293 if (Ops.size() == 2) return NewAddRec; 3294 Ops[Idx] = NewAddRec; 3295 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3296 OpsModified = true; 3297 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3298 if (!AddRec) 3299 break; 3300 } 3301 } 3302 if (OpsModified) 3303 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3304 3305 // Otherwise couldn't fold anything into this recurrence. Move onto the 3306 // next one. 3307 } 3308 3309 // Okay, it looks like we really DO need an mul expr. Check to see if we 3310 // already have one, otherwise create a new one. 3311 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3312 } 3313 3314 /// Represents an unsigned remainder expression based on unsigned division. 3315 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3316 const SCEV *RHS) { 3317 assert(getEffectiveSCEVType(LHS->getType()) == 3318 getEffectiveSCEVType(RHS->getType()) && 3319 "SCEVURemExpr operand types don't match!"); 3320 3321 // Short-circuit easy cases 3322 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3323 // If constant is one, the result is trivial 3324 if (RHSC->getValue()->isOne()) 3325 return getZero(LHS->getType()); // X urem 1 --> 0 3326 3327 // If constant is a power of two, fold into a zext(trunc(LHS)). 3328 if (RHSC->getAPInt().isPowerOf2()) { 3329 Type *FullTy = LHS->getType(); 3330 Type *TruncTy = 3331 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3332 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3333 } 3334 } 3335 3336 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3337 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3338 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3339 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3340 } 3341 3342 /// Get a canonical unsigned division expression, or something simpler if 3343 /// possible. 3344 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3345 const SCEV *RHS) { 3346 assert(!LHS->getType()->isPointerTy() && 3347 "SCEVUDivExpr operand can't be pointer!"); 3348 assert(LHS->getType() == RHS->getType() && 3349 "SCEVUDivExpr operand types don't match!"); 3350 3351 FoldingSetNodeID ID; 3352 ID.AddInteger(scUDivExpr); 3353 ID.AddPointer(LHS); 3354 ID.AddPointer(RHS); 3355 void *IP = nullptr; 3356 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3357 return S; 3358 3359 // 0 udiv Y == 0 3360 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) 3361 if (LHSC->getValue()->isZero()) 3362 return LHS; 3363 3364 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3365 if (RHSC->getValue()->isOne()) 3366 return LHS; // X udiv 1 --> x 3367 // If the denominator is zero, the result of the udiv is undefined. Don't 3368 // try to analyze it, because the resolution chosen here may differ from 3369 // the resolution chosen in other parts of the compiler. 3370 if (!RHSC->getValue()->isZero()) { 3371 // Determine if the division can be folded into the operands of 3372 // its operands. 3373 // TODO: Generalize this to non-constants by using known-bits information. 3374 Type *Ty = LHS->getType(); 3375 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3376 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3377 // For non-power-of-two values, effectively round the value up to the 3378 // nearest power of two. 3379 if (!RHSC->getAPInt().isPowerOf2()) 3380 ++MaxShiftAmt; 3381 IntegerType *ExtTy = 3382 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3383 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3384 if (const SCEVConstant *Step = 3385 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3386 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3387 const APInt &StepInt = Step->getAPInt(); 3388 const APInt &DivInt = RHSC->getAPInt(); 3389 if (!StepInt.urem(DivInt) && 3390 getZeroExtendExpr(AR, ExtTy) == 3391 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3392 getZeroExtendExpr(Step, ExtTy), 3393 AR->getLoop(), SCEV::FlagAnyWrap)) { 3394 SmallVector<const SCEV *, 4> Operands; 3395 for (const SCEV *Op : AR->operands()) 3396 Operands.push_back(getUDivExpr(Op, RHS)); 3397 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3398 } 3399 /// Get a canonical UDivExpr for a recurrence. 3400 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3401 // We can currently only fold X%N if X is constant. 3402 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3403 if (StartC && !DivInt.urem(StepInt) && 3404 getZeroExtendExpr(AR, ExtTy) == 3405 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3406 getZeroExtendExpr(Step, ExtTy), 3407 AR->getLoop(), SCEV::FlagAnyWrap)) { 3408 const APInt &StartInt = StartC->getAPInt(); 3409 const APInt &StartRem = StartInt.urem(StepInt); 3410 if (StartRem != 0) { 3411 const SCEV *NewLHS = 3412 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3413 AR->getLoop(), SCEV::FlagNW); 3414 if (LHS != NewLHS) { 3415 LHS = NewLHS; 3416 3417 // Reset the ID to include the new LHS, and check if it is 3418 // already cached. 3419 ID.clear(); 3420 ID.AddInteger(scUDivExpr); 3421 ID.AddPointer(LHS); 3422 ID.AddPointer(RHS); 3423 IP = nullptr; 3424 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3425 return S; 3426 } 3427 } 3428 } 3429 } 3430 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3431 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3432 SmallVector<const SCEV *, 4> Operands; 3433 for (const SCEV *Op : M->operands()) 3434 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3435 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3436 // Find an operand that's safely divisible. 3437 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3438 const SCEV *Op = M->getOperand(i); 3439 const SCEV *Div = getUDivExpr(Op, RHSC); 3440 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3441 Operands = SmallVector<const SCEV *, 4>(M->operands()); 3442 Operands[i] = Div; 3443 return getMulExpr(Operands); 3444 } 3445 } 3446 } 3447 3448 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3449 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3450 if (auto *DivisorConstant = 3451 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3452 bool Overflow = false; 3453 APInt NewRHS = 3454 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3455 if (Overflow) { 3456 return getConstant(RHSC->getType(), 0, false); 3457 } 3458 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3459 } 3460 } 3461 3462 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3463 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3464 SmallVector<const SCEV *, 4> Operands; 3465 for (const SCEV *Op : A->operands()) 3466 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3467 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3468 Operands.clear(); 3469 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3470 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3471 if (isa<SCEVUDivExpr>(Op) || 3472 getMulExpr(Op, RHS) != A->getOperand(i)) 3473 break; 3474 Operands.push_back(Op); 3475 } 3476 if (Operands.size() == A->getNumOperands()) 3477 return getAddExpr(Operands); 3478 } 3479 } 3480 3481 // Fold if both operands are constant. 3482 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3483 Constant *LHSCV = LHSC->getValue(); 3484 Constant *RHSCV = RHSC->getValue(); 3485 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3486 RHSCV))); 3487 } 3488 } 3489 } 3490 3491 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3492 // changes). Make sure we get a new one. 3493 IP = nullptr; 3494 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3495 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3496 LHS, RHS); 3497 UniqueSCEVs.InsertNode(S, IP); 3498 registerUser(S, {LHS, RHS}); 3499 return S; 3500 } 3501 3502 APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3503 APInt A = C1->getAPInt().abs(); 3504 APInt B = C2->getAPInt().abs(); 3505 uint32_t ABW = A.getBitWidth(); 3506 uint32_t BBW = B.getBitWidth(); 3507 3508 if (ABW > BBW) 3509 B = B.zext(ABW); 3510 else if (ABW < BBW) 3511 A = A.zext(BBW); 3512 3513 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3514 } 3515 3516 /// Get a canonical unsigned division expression, or something simpler if 3517 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3518 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3519 /// it's not exact because the udiv may be clearing bits. 3520 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3521 const SCEV *RHS) { 3522 // TODO: we could try to find factors in all sorts of things, but for now we 3523 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3524 // end of this file for inspiration. 3525 3526 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3527 if (!Mul || !Mul->hasNoUnsignedWrap()) 3528 return getUDivExpr(LHS, RHS); 3529 3530 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3531 // If the mulexpr multiplies by a constant, then that constant must be the 3532 // first element of the mulexpr. 3533 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3534 if (LHSCst == RHSCst) { 3535 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands())); 3536 return getMulExpr(Operands); 3537 } 3538 3539 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3540 // that there's a factor provided by one of the other terms. We need to 3541 // check. 3542 APInt Factor = gcd(LHSCst, RHSCst); 3543 if (!Factor.isIntN(1)) { 3544 LHSCst = 3545 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3546 RHSCst = 3547 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3548 SmallVector<const SCEV *, 2> Operands; 3549 Operands.push_back(LHSCst); 3550 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3551 LHS = getMulExpr(Operands); 3552 RHS = RHSCst; 3553 Mul = dyn_cast<SCEVMulExpr>(LHS); 3554 if (!Mul) 3555 return getUDivExactExpr(LHS, RHS); 3556 } 3557 } 3558 } 3559 3560 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3561 if (Mul->getOperand(i) == RHS) { 3562 SmallVector<const SCEV *, 2> Operands; 3563 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3564 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3565 return getMulExpr(Operands); 3566 } 3567 } 3568 3569 return getUDivExpr(LHS, RHS); 3570 } 3571 3572 /// Get an add recurrence expression for the specified loop. Simplify the 3573 /// expression as much as possible. 3574 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3575 const Loop *L, 3576 SCEV::NoWrapFlags Flags) { 3577 SmallVector<const SCEV *, 4> Operands; 3578 Operands.push_back(Start); 3579 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3580 if (StepChrec->getLoop() == L) { 3581 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3582 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3583 } 3584 3585 Operands.push_back(Step); 3586 return getAddRecExpr(Operands, L, Flags); 3587 } 3588 3589 /// Get an add recurrence expression for the specified loop. Simplify the 3590 /// expression as much as possible. 3591 const SCEV * 3592 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3593 const Loop *L, SCEV::NoWrapFlags Flags) { 3594 if (Operands.size() == 1) return Operands[0]; 3595 #ifndef NDEBUG 3596 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3597 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 3598 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3599 "SCEVAddRecExpr operand types don't match!"); 3600 assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer"); 3601 } 3602 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3603 assert(isLoopInvariant(Operands[i], L) && 3604 "SCEVAddRecExpr operand is not loop-invariant!"); 3605 #endif 3606 3607 if (Operands.back()->isZero()) { 3608 Operands.pop_back(); 3609 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3610 } 3611 3612 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3613 // use that information to infer NUW and NSW flags. However, computing a 3614 // BE count requires calling getAddRecExpr, so we may not yet have a 3615 // meaningful BE count at this point (and if we don't, we'd be stuck 3616 // with a SCEVCouldNotCompute as the cached BE count). 3617 3618 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3619 3620 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3621 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3622 const Loop *NestedLoop = NestedAR->getLoop(); 3623 if (L->contains(NestedLoop) 3624 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3625 : (!NestedLoop->contains(L) && 3626 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3627 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands()); 3628 Operands[0] = NestedAR->getStart(); 3629 // AddRecs require their operands be loop-invariant with respect to their 3630 // loops. Don't perform this transformation if it would break this 3631 // requirement. 3632 bool AllInvariant = all_of( 3633 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3634 3635 if (AllInvariant) { 3636 // Create a recurrence for the outer loop with the same step size. 3637 // 3638 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3639 // inner recurrence has the same property. 3640 SCEV::NoWrapFlags OuterFlags = 3641 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3642 3643 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3644 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3645 return isLoopInvariant(Op, NestedLoop); 3646 }); 3647 3648 if (AllInvariant) { 3649 // Ok, both add recurrences are valid after the transformation. 3650 // 3651 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3652 // the outer recurrence has the same property. 3653 SCEV::NoWrapFlags InnerFlags = 3654 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3655 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3656 } 3657 } 3658 // Reset Operands to its original state. 3659 Operands[0] = NestedAR; 3660 } 3661 } 3662 3663 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3664 // already have one, otherwise create a new one. 3665 return getOrCreateAddRecExpr(Operands, L, Flags); 3666 } 3667 3668 const SCEV * 3669 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3670 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3671 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3672 // getSCEV(Base)->getType() has the same address space as Base->getType() 3673 // because SCEV::getType() preserves the address space. 3674 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3675 const bool AssumeInBoundsFlags = [&]() { 3676 if (!GEP->isInBounds()) 3677 return false; 3678 3679 // We'd like to propagate flags from the IR to the corresponding SCEV nodes, 3680 // but to do that, we have to ensure that said flag is valid in the entire 3681 // defined scope of the SCEV. 3682 auto *GEPI = dyn_cast<Instruction>(GEP); 3683 // TODO: non-instructions have global scope. We might be able to prove 3684 // some global scope cases 3685 return GEPI && isSCEVExprNeverPoison(GEPI); 3686 }(); 3687 3688 SCEV::NoWrapFlags OffsetWrap = 3689 AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3690 3691 Type *CurTy = GEP->getType(); 3692 bool FirstIter = true; 3693 SmallVector<const SCEV *, 4> Offsets; 3694 for (const SCEV *IndexExpr : IndexExprs) { 3695 // Compute the (potentially symbolic) offset in bytes for this index. 3696 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3697 // For a struct, add the member offset. 3698 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3699 unsigned FieldNo = Index->getZExtValue(); 3700 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3701 Offsets.push_back(FieldOffset); 3702 3703 // Update CurTy to the type of the field at Index. 3704 CurTy = STy->getTypeAtIndex(Index); 3705 } else { 3706 // Update CurTy to its element type. 3707 if (FirstIter) { 3708 assert(isa<PointerType>(CurTy) && 3709 "The first index of a GEP indexes a pointer"); 3710 CurTy = GEP->getSourceElementType(); 3711 FirstIter = false; 3712 } else { 3713 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3714 } 3715 // For an array, add the element offset, explicitly scaled. 3716 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3717 // Getelementptr indices are signed. 3718 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3719 3720 // Multiply the index by the element size to compute the element offset. 3721 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3722 Offsets.push_back(LocalOffset); 3723 } 3724 } 3725 3726 // Handle degenerate case of GEP without offsets. 3727 if (Offsets.empty()) 3728 return BaseExpr; 3729 3730 // Add the offsets together, assuming nsw if inbounds. 3731 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3732 // Add the base address and the offset. We cannot use the nsw flag, as the 3733 // base address is unsigned. However, if we know that the offset is 3734 // non-negative, we can use nuw. 3735 SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset) 3736 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3737 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap); 3738 assert(BaseExpr->getType() == GEPExpr->getType() && 3739 "GEP should not change type mid-flight."); 3740 return GEPExpr; 3741 } 3742 3743 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3744 ArrayRef<const SCEV *> Ops) { 3745 FoldingSetNodeID ID; 3746 ID.AddInteger(SCEVType); 3747 for (const SCEV *Op : Ops) 3748 ID.AddPointer(Op); 3749 void *IP = nullptr; 3750 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3751 } 3752 3753 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3754 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3755 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3756 } 3757 3758 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3759 SmallVectorImpl<const SCEV *> &Ops) { 3760 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!"); 3761 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3762 if (Ops.size() == 1) return Ops[0]; 3763 #ifndef NDEBUG 3764 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3765 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 3766 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3767 "Operand types don't match!"); 3768 assert(Ops[0]->getType()->isPointerTy() == 3769 Ops[i]->getType()->isPointerTy() && 3770 "min/max should be consistently pointerish"); 3771 } 3772 #endif 3773 3774 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3775 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3776 3777 // Sort by complexity, this groups all similar expression types together. 3778 GroupByComplexity(Ops, &LI, DT); 3779 3780 // Check if we have created the same expression before. 3781 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) { 3782 return S; 3783 } 3784 3785 // If there are any constants, fold them together. 3786 unsigned Idx = 0; 3787 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3788 ++Idx; 3789 assert(Idx < Ops.size()); 3790 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3791 if (Kind == scSMaxExpr) 3792 return APIntOps::smax(LHS, RHS); 3793 else if (Kind == scSMinExpr) 3794 return APIntOps::smin(LHS, RHS); 3795 else if (Kind == scUMaxExpr) 3796 return APIntOps::umax(LHS, RHS); 3797 else if (Kind == scUMinExpr) 3798 return APIntOps::umin(LHS, RHS); 3799 llvm_unreachable("Unknown SCEV min/max opcode"); 3800 }; 3801 3802 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3803 // We found two constants, fold them together! 3804 ConstantInt *Fold = ConstantInt::get( 3805 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3806 Ops[0] = getConstant(Fold); 3807 Ops.erase(Ops.begin()+1); // Erase the folded element 3808 if (Ops.size() == 1) return Ops[0]; 3809 LHSC = cast<SCEVConstant>(Ops[0]); 3810 } 3811 3812 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3813 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3814 3815 if (IsMax ? IsMinV : IsMaxV) { 3816 // If we are left with a constant minimum(/maximum)-int, strip it off. 3817 Ops.erase(Ops.begin()); 3818 --Idx; 3819 } else if (IsMax ? IsMaxV : IsMinV) { 3820 // If we have a max(/min) with a constant maximum(/minimum)-int, 3821 // it will always be the extremum. 3822 return LHSC; 3823 } 3824 3825 if (Ops.size() == 1) return Ops[0]; 3826 } 3827 3828 // Find the first operation of the same kind 3829 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3830 ++Idx; 3831 3832 // Check to see if one of the operands is of the same kind. If so, expand its 3833 // operands onto our operand list, and recurse to simplify. 3834 if (Idx < Ops.size()) { 3835 bool DeletedAny = false; 3836 while (Ops[Idx]->getSCEVType() == Kind) { 3837 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3838 Ops.erase(Ops.begin()+Idx); 3839 Ops.append(SMME->op_begin(), SMME->op_end()); 3840 DeletedAny = true; 3841 } 3842 3843 if (DeletedAny) 3844 return getMinMaxExpr(Kind, Ops); 3845 } 3846 3847 // Okay, check to see if the same value occurs in the operand list twice. If 3848 // so, delete one. Since we sorted the list, these values are required to 3849 // be adjacent. 3850 llvm::CmpInst::Predicate GEPred = 3851 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3852 llvm::CmpInst::Predicate LEPred = 3853 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3854 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3855 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3856 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3857 if (Ops[i] == Ops[i + 1] || 3858 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3859 // X op Y op Y --> X op Y 3860 // X op Y --> X, if we know X, Y are ordered appropriately 3861 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3862 --i; 3863 --e; 3864 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3865 Ops[i + 1])) { 3866 // X op Y --> Y, if we know X, Y are ordered appropriately 3867 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3868 --i; 3869 --e; 3870 } 3871 } 3872 3873 if (Ops.size() == 1) return Ops[0]; 3874 3875 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3876 3877 // Okay, it looks like we really DO need an expr. Check to see if we 3878 // already have one, otherwise create a new one. 3879 FoldingSetNodeID ID; 3880 ID.AddInteger(Kind); 3881 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3882 ID.AddPointer(Ops[i]); 3883 void *IP = nullptr; 3884 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3885 if (ExistingSCEV) 3886 return ExistingSCEV; 3887 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3888 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3889 SCEV *S = new (SCEVAllocator) 3890 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3891 3892 UniqueSCEVs.InsertNode(S, IP); 3893 registerUser(S, Ops); 3894 return S; 3895 } 3896 3897 namespace { 3898 3899 class SCEVSequentialMinMaxDeduplicatingVisitor final 3900 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, 3901 Optional<const SCEV *>> { 3902 using RetVal = Optional<const SCEV *>; 3903 using Base = SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, RetVal>; 3904 3905 ScalarEvolution &SE; 3906 const SCEVTypes RootKind; // Must be a sequential min/max expression. 3907 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind. 3908 SmallPtrSet<const SCEV *, 16> SeenOps; 3909 3910 bool canRecurseInto(SCEVTypes Kind) const { 3911 // We can only recurse into the SCEV expression of the same effective type 3912 // as the type of our root SCEV expression. 3913 return RootKind == Kind || NonSequentialRootKind == Kind; 3914 }; 3915 3916 RetVal visitAnyMinMaxExpr(const SCEV *S) { 3917 assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) && 3918 "Only for min/max expressions."); 3919 SCEVTypes Kind = S->getSCEVType(); 3920 3921 if (!canRecurseInto(Kind)) 3922 return S; 3923 3924 auto *NAry = cast<SCEVNAryExpr>(S); 3925 SmallVector<const SCEV *> NewOps; 3926 bool Changed = 3927 visit(Kind, makeArrayRef(NAry->op_begin(), NAry->op_end()), NewOps); 3928 3929 if (!Changed) 3930 return S; 3931 if (NewOps.empty()) 3932 return None; 3933 3934 return isa<SCEVSequentialMinMaxExpr>(S) 3935 ? SE.getSequentialMinMaxExpr(Kind, NewOps) 3936 : SE.getMinMaxExpr(Kind, NewOps); 3937 } 3938 3939 RetVal visit(const SCEV *S) { 3940 // Has the whole operand been seen already? 3941 if (!SeenOps.insert(S).second) 3942 return None; 3943 return Base::visit(S); 3944 } 3945 3946 public: 3947 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE, 3948 SCEVTypes RootKind) 3949 : SE(SE), RootKind(RootKind), 3950 NonSequentialRootKind( 3951 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType( 3952 RootKind)) {} 3953 3954 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps, 3955 SmallVectorImpl<const SCEV *> &NewOps) { 3956 bool Changed = false; 3957 SmallVector<const SCEV *> Ops; 3958 Ops.reserve(OrigOps.size()); 3959 3960 for (const SCEV *Op : OrigOps) { 3961 RetVal NewOp = visit(Op); 3962 if (NewOp != Op) 3963 Changed = true; 3964 if (NewOp) 3965 Ops.emplace_back(*NewOp); 3966 } 3967 3968 if (Changed) 3969 NewOps = std::move(Ops); 3970 return Changed; 3971 } 3972 3973 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; } 3974 3975 RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; } 3976 3977 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; } 3978 3979 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; } 3980 3981 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; } 3982 3983 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; } 3984 3985 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; } 3986 3987 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; } 3988 3989 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 3990 3991 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) { 3992 return visitAnyMinMaxExpr(Expr); 3993 } 3994 3995 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) { 3996 return visitAnyMinMaxExpr(Expr); 3997 } 3998 3999 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) { 4000 return visitAnyMinMaxExpr(Expr); 4001 } 4002 4003 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) { 4004 return visitAnyMinMaxExpr(Expr); 4005 } 4006 4007 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) { 4008 return visitAnyMinMaxExpr(Expr); 4009 } 4010 4011 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; } 4012 4013 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; } 4014 }; 4015 4016 } // namespace 4017 4018 /// Return true if V is poison given that AssumedPoison is already poison. 4019 static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) { 4020 // The only way poison may be introduced in a SCEV expression is from a 4021 // poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown, 4022 // not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not* 4023 // introduce poison -- they encode guaranteed, non-speculated knowledge. 4024 // 4025 // Additionally, all SCEV nodes propagate poison from inputs to outputs, 4026 // with the notable exception of umin_seq, where only poison from the first 4027 // operand is (unconditionally) propagated. 4028 struct SCEVPoisonCollector { 4029 bool LookThroughSeq; 4030 SmallPtrSet<const SCEV *, 4> MaybePoison; 4031 SCEVPoisonCollector(bool LookThroughSeq) : LookThroughSeq(LookThroughSeq) {} 4032 4033 bool follow(const SCEV *S) { 4034 // TODO: We can always follow the first operand, but the SCEVTraversal 4035 // API doesn't support this. 4036 if (!LookThroughSeq && isa<SCEVSequentialMinMaxExpr>(S)) 4037 return false; 4038 4039 if (auto *SU = dyn_cast<SCEVUnknown>(S)) { 4040 if (!isGuaranteedNotToBePoison(SU->getValue())) 4041 MaybePoison.insert(S); 4042 } 4043 return true; 4044 } 4045 bool isDone() const { return false; } 4046 }; 4047 4048 // First collect all SCEVs that might result in AssumedPoison to be poison. 4049 // We need to look through umin_seq here, because we want to find all SCEVs 4050 // that *might* result in poison, not only those that are *required* to. 4051 SCEVPoisonCollector PC1(/* LookThroughSeq */ true); 4052 visitAll(AssumedPoison, PC1); 4053 4054 // AssumedPoison is never poison. As the assumption is false, the implication 4055 // is true. Don't bother walking the other SCEV in this case. 4056 if (PC1.MaybePoison.empty()) 4057 return true; 4058 4059 // Collect all SCEVs in S that, if poison, *will* result in S being poison 4060 // as well. We cannot look through umin_seq here, as its argument only *may* 4061 // make the result poison. 4062 SCEVPoisonCollector PC2(/* LookThroughSeq */ false); 4063 visitAll(S, PC2); 4064 4065 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison, 4066 // it will also make S poison by being part of PC2.MaybePoison. 4067 return all_of(PC1.MaybePoison, 4068 [&](const SCEV *S) { return PC2.MaybePoison.contains(S); }); 4069 } 4070 4071 const SCEV * 4072 ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind, 4073 SmallVectorImpl<const SCEV *> &Ops) { 4074 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) && 4075 "Not a SCEVSequentialMinMaxExpr!"); 4076 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 4077 if (Ops.size() == 1) 4078 return Ops[0]; 4079 #ifndef NDEBUG 4080 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 4081 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 4082 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 4083 "Operand types don't match!"); 4084 assert(Ops[0]->getType()->isPointerTy() == 4085 Ops[i]->getType()->isPointerTy() && 4086 "min/max should be consistently pointerish"); 4087 } 4088 #endif 4089 4090 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative, 4091 // so we can *NOT* do any kind of sorting of the expressions! 4092 4093 // Check if we have created the same expression before. 4094 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) 4095 return S; 4096 4097 // FIXME: there are *some* simplifications that we can do here. 4098 4099 // Keep only the first instance of an operand. 4100 { 4101 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind); 4102 bool Changed = Deduplicator.visit(Kind, Ops, Ops); 4103 if (Changed) 4104 return getSequentialMinMaxExpr(Kind, Ops); 4105 } 4106 4107 // Check to see if one of the operands is of the same kind. If so, expand its 4108 // operands onto our operand list, and recurse to simplify. 4109 { 4110 unsigned Idx = 0; 4111 bool DeletedAny = false; 4112 while (Idx < Ops.size()) { 4113 if (Ops[Idx]->getSCEVType() != Kind) { 4114 ++Idx; 4115 continue; 4116 } 4117 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]); 4118 Ops.erase(Ops.begin() + Idx); 4119 Ops.insert(Ops.begin() + Idx, SMME->op_begin(), SMME->op_end()); 4120 DeletedAny = true; 4121 } 4122 4123 if (DeletedAny) 4124 return getSequentialMinMaxExpr(Kind, Ops); 4125 } 4126 4127 const SCEV *SaturationPoint; 4128 ICmpInst::Predicate Pred; 4129 switch (Kind) { 4130 case scSequentialUMinExpr: 4131 SaturationPoint = getZero(Ops[0]->getType()); 4132 Pred = ICmpInst::ICMP_ULE; 4133 break; 4134 default: 4135 llvm_unreachable("Not a sequential min/max type."); 4136 } 4137 4138 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 4139 // We can replace %x umin_seq %y with %x umin %y if either: 4140 // * %y being poison implies %x is also poison. 4141 // * %x cannot be the saturating value (e.g. zero for umin). 4142 if (::impliesPoison(Ops[i], Ops[i - 1]) || 4143 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1], 4144 SaturationPoint)) { 4145 SmallVector<const SCEV *> SeqOps = {Ops[i - 1], Ops[i]}; 4146 Ops[i - 1] = getMinMaxExpr( 4147 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind), 4148 SeqOps); 4149 Ops.erase(Ops.begin() + i); 4150 return getSequentialMinMaxExpr(Kind, Ops); 4151 } 4152 // Fold %x umin_seq %y to %x if %x ule %y. 4153 // TODO: We might be able to prove the predicate for a later operand. 4154 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) { 4155 Ops.erase(Ops.begin() + i); 4156 return getSequentialMinMaxExpr(Kind, Ops); 4157 } 4158 } 4159 4160 // Okay, it looks like we really DO need an expr. Check to see if we 4161 // already have one, otherwise create a new one. 4162 FoldingSetNodeID ID; 4163 ID.AddInteger(Kind); 4164 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 4165 ID.AddPointer(Ops[i]); 4166 void *IP = nullptr; 4167 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 4168 if (ExistingSCEV) 4169 return ExistingSCEV; 4170 4171 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 4172 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 4173 SCEV *S = new (SCEVAllocator) 4174 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 4175 4176 UniqueSCEVs.InsertNode(S, IP); 4177 registerUser(S, Ops); 4178 return S; 4179 } 4180 4181 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 4182 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 4183 return getSMaxExpr(Ops); 4184 } 4185 4186 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 4187 return getMinMaxExpr(scSMaxExpr, Ops); 4188 } 4189 4190 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 4191 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 4192 return getUMaxExpr(Ops); 4193 } 4194 4195 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 4196 return getMinMaxExpr(scUMaxExpr, Ops); 4197 } 4198 4199 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 4200 const SCEV *RHS) { 4201 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4202 return getSMinExpr(Ops); 4203 } 4204 4205 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 4206 return getMinMaxExpr(scSMinExpr, Ops); 4207 } 4208 4209 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS, 4210 bool Sequential) { 4211 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4212 return getUMinExpr(Ops, Sequential); 4213 } 4214 4215 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops, 4216 bool Sequential) { 4217 return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops) 4218 : getMinMaxExpr(scUMinExpr, Ops); 4219 } 4220 4221 const SCEV * 4222 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 4223 ScalableVectorType *ScalableTy) { 4224 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 4225 Constant *One = ConstantInt::get(IntTy, 1); 4226 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 4227 // Note that the expression we created is the final expression, we don't 4228 // want to simplify it any further Also, if we call a normal getSCEV(), 4229 // we'll end up in an endless recursion. So just create an SCEVUnknown. 4230 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 4231 } 4232 4233 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 4234 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 4235 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 4236 // We can bypass creating a target-independent constant expression and then 4237 // folding it back into a ConstantInt. This is just a compile-time 4238 // optimization. 4239 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 4240 } 4241 4242 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 4243 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 4244 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 4245 // We can bypass creating a target-independent constant expression and then 4246 // folding it back into a ConstantInt. This is just a compile-time 4247 // optimization. 4248 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 4249 } 4250 4251 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 4252 StructType *STy, 4253 unsigned FieldNo) { 4254 // We can bypass creating a target-independent constant expression and then 4255 // folding it back into a ConstantInt. This is just a compile-time 4256 // optimization. 4257 return getConstant( 4258 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 4259 } 4260 4261 const SCEV *ScalarEvolution::getUnknown(Value *V) { 4262 // Don't attempt to do anything other than create a SCEVUnknown object 4263 // here. createSCEV only calls getUnknown after checking for all other 4264 // interesting possibilities, and any other code that calls getUnknown 4265 // is doing so in order to hide a value from SCEV canonicalization. 4266 4267 FoldingSetNodeID ID; 4268 ID.AddInteger(scUnknown); 4269 ID.AddPointer(V); 4270 void *IP = nullptr; 4271 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 4272 assert(cast<SCEVUnknown>(S)->getValue() == V && 4273 "Stale SCEVUnknown in uniquing map!"); 4274 return S; 4275 } 4276 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 4277 FirstUnknown); 4278 FirstUnknown = cast<SCEVUnknown>(S); 4279 UniqueSCEVs.InsertNode(S, IP); 4280 return S; 4281 } 4282 4283 //===----------------------------------------------------------------------===// 4284 // Basic SCEV Analysis and PHI Idiom Recognition Code 4285 // 4286 4287 /// Test if values of the given type are analyzable within the SCEV 4288 /// framework. This primarily includes integer types, and it can optionally 4289 /// include pointer types if the ScalarEvolution class has access to 4290 /// target-specific information. 4291 bool ScalarEvolution::isSCEVable(Type *Ty) const { 4292 // Integers and pointers are always SCEVable. 4293 return Ty->isIntOrPtrTy(); 4294 } 4295 4296 /// Return the size in bits of the specified type, for which isSCEVable must 4297 /// return true. 4298 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 4299 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 4300 if (Ty->isPointerTy()) 4301 return getDataLayout().getIndexTypeSizeInBits(Ty); 4302 return getDataLayout().getTypeSizeInBits(Ty); 4303 } 4304 4305 /// Return a type with the same bitwidth as the given type and which represents 4306 /// how SCEV will treat the given type, for which isSCEVable must return 4307 /// true. For pointer types, this is the pointer index sized integer type. 4308 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 4309 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 4310 4311 if (Ty->isIntegerTy()) 4312 return Ty; 4313 4314 // The only other support type is pointer. 4315 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 4316 return getDataLayout().getIndexType(Ty); 4317 } 4318 4319 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 4320 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 4321 } 4322 4323 bool ScalarEvolution::instructionCouldExistWitthOperands(const SCEV *A, 4324 const SCEV *B) { 4325 /// For a valid use point to exist, the defining scope of one operand 4326 /// must dominate the other. 4327 bool PreciseA, PreciseB; 4328 auto *ScopeA = getDefiningScopeBound({A}, PreciseA); 4329 auto *ScopeB = getDefiningScopeBound({B}, PreciseB); 4330 if (!PreciseA || !PreciseB) 4331 // Can't tell. 4332 return false; 4333 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) || 4334 DT.dominates(ScopeB, ScopeA); 4335 } 4336 4337 4338 const SCEV *ScalarEvolution::getCouldNotCompute() { 4339 return CouldNotCompute.get(); 4340 } 4341 4342 bool ScalarEvolution::checkValidity(const SCEV *S) const { 4343 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 4344 auto *SU = dyn_cast<SCEVUnknown>(S); 4345 return SU && SU->getValue() == nullptr; 4346 }); 4347 4348 return !ContainsNulls; 4349 } 4350 4351 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 4352 HasRecMapType::iterator I = HasRecMap.find(S); 4353 if (I != HasRecMap.end()) 4354 return I->second; 4355 4356 bool FoundAddRec = 4357 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 4358 HasRecMap.insert({S, FoundAddRec}); 4359 return FoundAddRec; 4360 } 4361 4362 /// Return the ValueOffsetPair set for \p S. \p S can be represented 4363 /// by the value and offset from any ValueOffsetPair in the set. 4364 ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) { 4365 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 4366 if (SI == ExprValueMap.end()) 4367 return None; 4368 #ifndef NDEBUG 4369 if (VerifySCEVMap) { 4370 // Check there is no dangling Value in the set returned. 4371 for (Value *V : SI->second) 4372 assert(ValueExprMap.count(V)); 4373 } 4374 #endif 4375 return SI->second.getArrayRef(); 4376 } 4377 4378 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 4379 /// cannot be used separately. eraseValueFromMap should be used to remove 4380 /// V from ValueExprMap and ExprValueMap at the same time. 4381 void ScalarEvolution::eraseValueFromMap(Value *V) { 4382 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4383 if (I != ValueExprMap.end()) { 4384 auto EVIt = ExprValueMap.find(I->second); 4385 bool Removed = EVIt->second.remove(V); 4386 (void) Removed; 4387 assert(Removed && "Value not in ExprValueMap?"); 4388 ValueExprMap.erase(I); 4389 } 4390 } 4391 4392 void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) { 4393 // A recursive query may have already computed the SCEV. It should be 4394 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily 4395 // inferred nowrap flags. 4396 auto It = ValueExprMap.find_as(V); 4397 if (It == ValueExprMap.end()) { 4398 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4399 ExprValueMap[S].insert(V); 4400 } 4401 } 4402 4403 /// Return an existing SCEV if it exists, otherwise analyze the expression and 4404 /// create a new one. 4405 const SCEV *ScalarEvolution::getSCEV(Value *V) { 4406 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4407 4408 const SCEV *S = getExistingSCEV(V); 4409 if (S == nullptr) { 4410 S = createSCEV(V); 4411 // During PHI resolution, it is possible to create two SCEVs for the same 4412 // V, so it is needed to double check whether V->S is inserted into 4413 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 4414 std::pair<ValueExprMapType::iterator, bool> Pair = 4415 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4416 if (Pair.second) 4417 ExprValueMap[S].insert(V); 4418 } 4419 return S; 4420 } 4421 4422 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 4423 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4424 4425 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4426 if (I != ValueExprMap.end()) { 4427 const SCEV *S = I->second; 4428 assert(checkValidity(S) && 4429 "existing SCEV has not been properly invalidated"); 4430 return S; 4431 } 4432 return nullptr; 4433 } 4434 4435 /// Return a SCEV corresponding to -V = -1*V 4436 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4437 SCEV::NoWrapFlags Flags) { 4438 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4439 return getConstant( 4440 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4441 4442 Type *Ty = V->getType(); 4443 Ty = getEffectiveSCEVType(Ty); 4444 return getMulExpr(V, getMinusOne(Ty), Flags); 4445 } 4446 4447 /// If Expr computes ~A, return A else return nullptr 4448 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4449 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4450 if (!Add || Add->getNumOperands() != 2 || 4451 !Add->getOperand(0)->isAllOnesValue()) 4452 return nullptr; 4453 4454 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4455 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4456 !AddRHS->getOperand(0)->isAllOnesValue()) 4457 return nullptr; 4458 4459 return AddRHS->getOperand(1); 4460 } 4461 4462 /// Return a SCEV corresponding to ~V = -1-V 4463 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4464 assert(!V->getType()->isPointerTy() && "Can't negate pointer"); 4465 4466 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4467 return getConstant( 4468 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4469 4470 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4471 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4472 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4473 SmallVector<const SCEV *, 2> MatchedOperands; 4474 for (const SCEV *Operand : MME->operands()) { 4475 const SCEV *Matched = MatchNotExpr(Operand); 4476 if (!Matched) 4477 return (const SCEV *)nullptr; 4478 MatchedOperands.push_back(Matched); 4479 } 4480 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 4481 MatchedOperands); 4482 }; 4483 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4484 return Replaced; 4485 } 4486 4487 Type *Ty = V->getType(); 4488 Ty = getEffectiveSCEVType(Ty); 4489 return getMinusSCEV(getMinusOne(Ty), V); 4490 } 4491 4492 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) { 4493 assert(P->getType()->isPointerTy()); 4494 4495 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) { 4496 // The base of an AddRec is the first operand. 4497 SmallVector<const SCEV *> Ops{AddRec->operands()}; 4498 Ops[0] = removePointerBase(Ops[0]); 4499 // Don't try to transfer nowrap flags for now. We could in some cases 4500 // (for example, if pointer operand of the AddRec is a SCEVUnknown). 4501 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap); 4502 } 4503 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) { 4504 // The base of an Add is the pointer operand. 4505 SmallVector<const SCEV *> Ops{Add->operands()}; 4506 const SCEV **PtrOp = nullptr; 4507 for (const SCEV *&AddOp : Ops) { 4508 if (AddOp->getType()->isPointerTy()) { 4509 assert(!PtrOp && "Cannot have multiple pointer ops"); 4510 PtrOp = &AddOp; 4511 } 4512 } 4513 *PtrOp = removePointerBase(*PtrOp); 4514 // Don't try to transfer nowrap flags for now. We could in some cases 4515 // (for example, if the pointer operand of the Add is a SCEVUnknown). 4516 return getAddExpr(Ops); 4517 } 4518 // Any other expression must be a pointer base. 4519 return getZero(P->getType()); 4520 } 4521 4522 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4523 SCEV::NoWrapFlags Flags, 4524 unsigned Depth) { 4525 // Fast path: X - X --> 0. 4526 if (LHS == RHS) 4527 return getZero(LHS->getType()); 4528 4529 // If we subtract two pointers with different pointer bases, bail. 4530 // Eventually, we're going to add an assertion to getMulExpr that we 4531 // can't multiply by a pointer. 4532 if (RHS->getType()->isPointerTy()) { 4533 if (!LHS->getType()->isPointerTy() || 4534 getPointerBase(LHS) != getPointerBase(RHS)) 4535 return getCouldNotCompute(); 4536 LHS = removePointerBase(LHS); 4537 RHS = removePointerBase(RHS); 4538 } 4539 4540 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4541 // makes it so that we cannot make much use of NUW. 4542 auto AddFlags = SCEV::FlagAnyWrap; 4543 const bool RHSIsNotMinSigned = 4544 !getSignedRangeMin(RHS).isMinSignedValue(); 4545 if (hasFlags(Flags, SCEV::FlagNSW)) { 4546 // Let M be the minimum representable signed value. Then (-1)*RHS 4547 // signed-wraps if and only if RHS is M. That can happen even for 4548 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4549 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4550 // (-1)*RHS, we need to prove that RHS != M. 4551 // 4552 // If LHS is non-negative and we know that LHS - RHS does not 4553 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4554 // either by proving that RHS > M or that LHS >= 0. 4555 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4556 AddFlags = SCEV::FlagNSW; 4557 } 4558 } 4559 4560 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4561 // RHS is NSW and LHS >= 0. 4562 // 4563 // The difficulty here is that the NSW flag may have been proven 4564 // relative to a loop that is to be found in a recurrence in LHS and 4565 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4566 // larger scope than intended. 4567 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4568 4569 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4570 } 4571 4572 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4573 unsigned Depth) { 4574 Type *SrcTy = V->getType(); 4575 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4576 "Cannot truncate or zero extend with non-integer arguments!"); 4577 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4578 return V; // No conversion 4579 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4580 return getTruncateExpr(V, Ty, Depth); 4581 return getZeroExtendExpr(V, Ty, Depth); 4582 } 4583 4584 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4585 unsigned Depth) { 4586 Type *SrcTy = V->getType(); 4587 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4588 "Cannot truncate or zero extend with non-integer arguments!"); 4589 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4590 return V; // No conversion 4591 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4592 return getTruncateExpr(V, Ty, Depth); 4593 return getSignExtendExpr(V, Ty, Depth); 4594 } 4595 4596 const SCEV * 4597 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4598 Type *SrcTy = V->getType(); 4599 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4600 "Cannot noop or zero extend with non-integer arguments!"); 4601 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4602 "getNoopOrZeroExtend cannot truncate!"); 4603 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4604 return V; // No conversion 4605 return getZeroExtendExpr(V, Ty); 4606 } 4607 4608 const SCEV * 4609 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4610 Type *SrcTy = V->getType(); 4611 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4612 "Cannot noop or sign extend with non-integer arguments!"); 4613 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4614 "getNoopOrSignExtend cannot truncate!"); 4615 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4616 return V; // No conversion 4617 return getSignExtendExpr(V, Ty); 4618 } 4619 4620 const SCEV * 4621 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4622 Type *SrcTy = V->getType(); 4623 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4624 "Cannot noop or any extend with non-integer arguments!"); 4625 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4626 "getNoopOrAnyExtend cannot truncate!"); 4627 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4628 return V; // No conversion 4629 return getAnyExtendExpr(V, Ty); 4630 } 4631 4632 const SCEV * 4633 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4634 Type *SrcTy = V->getType(); 4635 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4636 "Cannot truncate or noop with non-integer arguments!"); 4637 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4638 "getTruncateOrNoop cannot extend!"); 4639 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4640 return V; // No conversion 4641 return getTruncateExpr(V, Ty); 4642 } 4643 4644 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4645 const SCEV *RHS) { 4646 const SCEV *PromotedLHS = LHS; 4647 const SCEV *PromotedRHS = RHS; 4648 4649 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4650 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4651 else 4652 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4653 4654 return getUMaxExpr(PromotedLHS, PromotedRHS); 4655 } 4656 4657 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4658 const SCEV *RHS, 4659 bool Sequential) { 4660 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4661 return getUMinFromMismatchedTypes(Ops, Sequential); 4662 } 4663 4664 const SCEV * 4665 ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops, 4666 bool Sequential) { 4667 assert(!Ops.empty() && "At least one operand must be!"); 4668 // Trivial case. 4669 if (Ops.size() == 1) 4670 return Ops[0]; 4671 4672 // Find the max type first. 4673 Type *MaxType = nullptr; 4674 for (auto *S : Ops) 4675 if (MaxType) 4676 MaxType = getWiderType(MaxType, S->getType()); 4677 else 4678 MaxType = S->getType(); 4679 assert(MaxType && "Failed to find maximum type!"); 4680 4681 // Extend all ops to max type. 4682 SmallVector<const SCEV *, 2> PromotedOps; 4683 for (auto *S : Ops) 4684 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4685 4686 // Generate umin. 4687 return getUMinExpr(PromotedOps, Sequential); 4688 } 4689 4690 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4691 // A pointer operand may evaluate to a nonpointer expression, such as null. 4692 if (!V->getType()->isPointerTy()) 4693 return V; 4694 4695 while (true) { 4696 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 4697 V = AddRec->getStart(); 4698 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) { 4699 const SCEV *PtrOp = nullptr; 4700 for (const SCEV *AddOp : Add->operands()) { 4701 if (AddOp->getType()->isPointerTy()) { 4702 assert(!PtrOp && "Cannot have multiple pointer ops"); 4703 PtrOp = AddOp; 4704 } 4705 } 4706 assert(PtrOp && "Must have pointer op"); 4707 V = PtrOp; 4708 } else // Not something we can look further into. 4709 return V; 4710 } 4711 } 4712 4713 /// Push users of the given Instruction onto the given Worklist. 4714 static void PushDefUseChildren(Instruction *I, 4715 SmallVectorImpl<Instruction *> &Worklist, 4716 SmallPtrSetImpl<Instruction *> &Visited) { 4717 // Push the def-use children onto the Worklist stack. 4718 for (User *U : I->users()) { 4719 auto *UserInsn = cast<Instruction>(U); 4720 if (Visited.insert(UserInsn).second) 4721 Worklist.push_back(UserInsn); 4722 } 4723 } 4724 4725 namespace { 4726 4727 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4728 /// expression in case its Loop is L. If it is not L then 4729 /// if IgnoreOtherLoops is true then use AddRec itself 4730 /// otherwise rewrite cannot be done. 4731 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4732 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4733 public: 4734 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4735 bool IgnoreOtherLoops = true) { 4736 SCEVInitRewriter Rewriter(L, SE); 4737 const SCEV *Result = Rewriter.visit(S); 4738 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4739 return SE.getCouldNotCompute(); 4740 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4741 ? SE.getCouldNotCompute() 4742 : Result; 4743 } 4744 4745 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4746 if (!SE.isLoopInvariant(Expr, L)) 4747 SeenLoopVariantSCEVUnknown = true; 4748 return Expr; 4749 } 4750 4751 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4752 // Only re-write AddRecExprs for this loop. 4753 if (Expr->getLoop() == L) 4754 return Expr->getStart(); 4755 SeenOtherLoops = true; 4756 return Expr; 4757 } 4758 4759 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4760 4761 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4762 4763 private: 4764 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4765 : SCEVRewriteVisitor(SE), L(L) {} 4766 4767 const Loop *L; 4768 bool SeenLoopVariantSCEVUnknown = false; 4769 bool SeenOtherLoops = false; 4770 }; 4771 4772 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4773 /// increment expression in case its Loop is L. If it is not L then 4774 /// use AddRec itself. 4775 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4776 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4777 public: 4778 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4779 SCEVPostIncRewriter Rewriter(L, SE); 4780 const SCEV *Result = Rewriter.visit(S); 4781 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4782 ? SE.getCouldNotCompute() 4783 : Result; 4784 } 4785 4786 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4787 if (!SE.isLoopInvariant(Expr, L)) 4788 SeenLoopVariantSCEVUnknown = true; 4789 return Expr; 4790 } 4791 4792 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4793 // Only re-write AddRecExprs for this loop. 4794 if (Expr->getLoop() == L) 4795 return Expr->getPostIncExpr(SE); 4796 SeenOtherLoops = true; 4797 return Expr; 4798 } 4799 4800 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4801 4802 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4803 4804 private: 4805 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4806 : SCEVRewriteVisitor(SE), L(L) {} 4807 4808 const Loop *L; 4809 bool SeenLoopVariantSCEVUnknown = false; 4810 bool SeenOtherLoops = false; 4811 }; 4812 4813 /// This class evaluates the compare condition by matching it against the 4814 /// condition of loop latch. If there is a match we assume a true value 4815 /// for the condition while building SCEV nodes. 4816 class SCEVBackedgeConditionFolder 4817 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4818 public: 4819 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4820 ScalarEvolution &SE) { 4821 bool IsPosBECond = false; 4822 Value *BECond = nullptr; 4823 if (BasicBlock *Latch = L->getLoopLatch()) { 4824 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4825 if (BI && BI->isConditional()) { 4826 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4827 "Both outgoing branches should not target same header!"); 4828 BECond = BI->getCondition(); 4829 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4830 } else { 4831 return S; 4832 } 4833 } 4834 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4835 return Rewriter.visit(S); 4836 } 4837 4838 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4839 const SCEV *Result = Expr; 4840 bool InvariantF = SE.isLoopInvariant(Expr, L); 4841 4842 if (!InvariantF) { 4843 Instruction *I = cast<Instruction>(Expr->getValue()); 4844 switch (I->getOpcode()) { 4845 case Instruction::Select: { 4846 SelectInst *SI = cast<SelectInst>(I); 4847 Optional<const SCEV *> Res = 4848 compareWithBackedgeCondition(SI->getCondition()); 4849 if (Res.hasValue()) { 4850 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4851 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4852 } 4853 break; 4854 } 4855 default: { 4856 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4857 if (Res.hasValue()) 4858 Result = Res.getValue(); 4859 break; 4860 } 4861 } 4862 } 4863 return Result; 4864 } 4865 4866 private: 4867 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4868 bool IsPosBECond, ScalarEvolution &SE) 4869 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4870 IsPositiveBECond(IsPosBECond) {} 4871 4872 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4873 4874 const Loop *L; 4875 /// Loop back condition. 4876 Value *BackedgeCond = nullptr; 4877 /// Set to true if loop back is on positive branch condition. 4878 bool IsPositiveBECond; 4879 }; 4880 4881 Optional<const SCEV *> 4882 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4883 4884 // If value matches the backedge condition for loop latch, 4885 // then return a constant evolution node based on loopback 4886 // branch taken. 4887 if (BackedgeCond == IC) 4888 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4889 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4890 return None; 4891 } 4892 4893 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4894 public: 4895 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4896 ScalarEvolution &SE) { 4897 SCEVShiftRewriter Rewriter(L, SE); 4898 const SCEV *Result = Rewriter.visit(S); 4899 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4900 } 4901 4902 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4903 // Only allow AddRecExprs for this loop. 4904 if (!SE.isLoopInvariant(Expr, L)) 4905 Valid = false; 4906 return Expr; 4907 } 4908 4909 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4910 if (Expr->getLoop() == L && Expr->isAffine()) 4911 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4912 Valid = false; 4913 return Expr; 4914 } 4915 4916 bool isValid() { return Valid; } 4917 4918 private: 4919 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4920 : SCEVRewriteVisitor(SE), L(L) {} 4921 4922 const Loop *L; 4923 bool Valid = true; 4924 }; 4925 4926 } // end anonymous namespace 4927 4928 SCEV::NoWrapFlags 4929 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4930 if (!AR->isAffine()) 4931 return SCEV::FlagAnyWrap; 4932 4933 using OBO = OverflowingBinaryOperator; 4934 4935 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4936 4937 if (!AR->hasNoSignedWrap()) { 4938 ConstantRange AddRecRange = getSignedRange(AR); 4939 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4940 4941 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4942 Instruction::Add, IncRange, OBO::NoSignedWrap); 4943 if (NSWRegion.contains(AddRecRange)) 4944 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4945 } 4946 4947 if (!AR->hasNoUnsignedWrap()) { 4948 ConstantRange AddRecRange = getUnsignedRange(AR); 4949 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4950 4951 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4952 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4953 if (NUWRegion.contains(AddRecRange)) 4954 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4955 } 4956 4957 return Result; 4958 } 4959 4960 SCEV::NoWrapFlags 4961 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4962 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4963 4964 if (AR->hasNoSignedWrap()) 4965 return Result; 4966 4967 if (!AR->isAffine()) 4968 return Result; 4969 4970 const SCEV *Step = AR->getStepRecurrence(*this); 4971 const Loop *L = AR->getLoop(); 4972 4973 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4974 // Note that this serves two purposes: It filters out loops that are 4975 // simply not analyzable, and it covers the case where this code is 4976 // being called from within backedge-taken count analysis, such that 4977 // attempting to ask for the backedge-taken count would likely result 4978 // in infinite recursion. In the later case, the analysis code will 4979 // cope with a conservative value, and it will take care to purge 4980 // that value once it has finished. 4981 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4982 4983 // Normally, in the cases we can prove no-overflow via a 4984 // backedge guarding condition, we can also compute a backedge 4985 // taken count for the loop. The exceptions are assumptions and 4986 // guards present in the loop -- SCEV is not great at exploiting 4987 // these to compute max backedge taken counts, but can still use 4988 // these to prove lack of overflow. Use this fact to avoid 4989 // doing extra work that may not pay off. 4990 4991 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4992 AC.assumptions().empty()) 4993 return Result; 4994 4995 // If the backedge is guarded by a comparison with the pre-inc value the 4996 // addrec is safe. Also, if the entry is guarded by a comparison with the 4997 // start value and the backedge is guarded by a comparison with the post-inc 4998 // value, the addrec is safe. 4999 ICmpInst::Predicate Pred; 5000 const SCEV *OverflowLimit = 5001 getSignedOverflowLimitForStep(Step, &Pred, this); 5002 if (OverflowLimit && 5003 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 5004 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 5005 Result = setFlags(Result, SCEV::FlagNSW); 5006 } 5007 return Result; 5008 } 5009 SCEV::NoWrapFlags 5010 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 5011 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 5012 5013 if (AR->hasNoUnsignedWrap()) 5014 return Result; 5015 5016 if (!AR->isAffine()) 5017 return Result; 5018 5019 const SCEV *Step = AR->getStepRecurrence(*this); 5020 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 5021 const Loop *L = AR->getLoop(); 5022 5023 // Check whether the backedge-taken count is SCEVCouldNotCompute. 5024 // Note that this serves two purposes: It filters out loops that are 5025 // simply not analyzable, and it covers the case where this code is 5026 // being called from within backedge-taken count analysis, such that 5027 // attempting to ask for the backedge-taken count would likely result 5028 // in infinite recursion. In the later case, the analysis code will 5029 // cope with a conservative value, and it will take care to purge 5030 // that value once it has finished. 5031 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 5032 5033 // Normally, in the cases we can prove no-overflow via a 5034 // backedge guarding condition, we can also compute a backedge 5035 // taken count for the loop. The exceptions are assumptions and 5036 // guards present in the loop -- SCEV is not great at exploiting 5037 // these to compute max backedge taken counts, but can still use 5038 // these to prove lack of overflow. Use this fact to avoid 5039 // doing extra work that may not pay off. 5040 5041 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 5042 AC.assumptions().empty()) 5043 return Result; 5044 5045 // If the backedge is guarded by a comparison with the pre-inc value the 5046 // addrec is safe. Also, if the entry is guarded by a comparison with the 5047 // start value and the backedge is guarded by a comparison with the post-inc 5048 // value, the addrec is safe. 5049 if (isKnownPositive(Step)) { 5050 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 5051 getUnsignedRangeMax(Step)); 5052 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 5053 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 5054 Result = setFlags(Result, SCEV::FlagNUW); 5055 } 5056 } 5057 5058 return Result; 5059 } 5060 5061 namespace { 5062 5063 /// Represents an abstract binary operation. This may exist as a 5064 /// normal instruction or constant expression, or may have been 5065 /// derived from an expression tree. 5066 struct BinaryOp { 5067 unsigned Opcode; 5068 Value *LHS; 5069 Value *RHS; 5070 bool IsNSW = false; 5071 bool IsNUW = false; 5072 5073 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 5074 /// constant expression. 5075 Operator *Op = nullptr; 5076 5077 explicit BinaryOp(Operator *Op) 5078 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 5079 Op(Op) { 5080 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 5081 IsNSW = OBO->hasNoSignedWrap(); 5082 IsNUW = OBO->hasNoUnsignedWrap(); 5083 } 5084 } 5085 5086 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 5087 bool IsNUW = false) 5088 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 5089 }; 5090 5091 } // end anonymous namespace 5092 5093 /// Try to map \p V into a BinaryOp, and return \c None on failure. 5094 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 5095 auto *Op = dyn_cast<Operator>(V); 5096 if (!Op) 5097 return None; 5098 5099 // Implementation detail: all the cleverness here should happen without 5100 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 5101 // SCEV expressions when possible, and we should not break that. 5102 5103 switch (Op->getOpcode()) { 5104 case Instruction::Add: 5105 case Instruction::Sub: 5106 case Instruction::Mul: 5107 case Instruction::UDiv: 5108 case Instruction::URem: 5109 case Instruction::And: 5110 case Instruction::Or: 5111 case Instruction::AShr: 5112 case Instruction::Shl: 5113 return BinaryOp(Op); 5114 5115 case Instruction::Xor: 5116 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 5117 // If the RHS of the xor is a signmask, then this is just an add. 5118 // Instcombine turns add of signmask into xor as a strength reduction step. 5119 if (RHSC->getValue().isSignMask()) 5120 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 5121 // Binary `xor` is a bit-wise `add`. 5122 if (V->getType()->isIntegerTy(1)) 5123 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 5124 return BinaryOp(Op); 5125 5126 case Instruction::LShr: 5127 // Turn logical shift right of a constant into a unsigned divide. 5128 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 5129 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 5130 5131 // If the shift count is not less than the bitwidth, the result of 5132 // the shift is undefined. Don't try to analyze it, because the 5133 // resolution chosen here may differ from the resolution chosen in 5134 // other parts of the compiler. 5135 if (SA->getValue().ult(BitWidth)) { 5136 Constant *X = 5137 ConstantInt::get(SA->getContext(), 5138 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5139 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 5140 } 5141 } 5142 return BinaryOp(Op); 5143 5144 case Instruction::ExtractValue: { 5145 auto *EVI = cast<ExtractValueInst>(Op); 5146 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 5147 break; 5148 5149 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 5150 if (!WO) 5151 break; 5152 5153 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 5154 bool Signed = WO->isSigned(); 5155 // TODO: Should add nuw/nsw flags for mul as well. 5156 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 5157 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 5158 5159 // Now that we know that all uses of the arithmetic-result component of 5160 // CI are guarded by the overflow check, we can go ahead and pretend 5161 // that the arithmetic is non-overflowing. 5162 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 5163 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 5164 } 5165 5166 default: 5167 break; 5168 } 5169 5170 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 5171 // semantics as a Sub, return a binary sub expression. 5172 if (auto *II = dyn_cast<IntrinsicInst>(V)) 5173 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 5174 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 5175 5176 return None; 5177 } 5178 5179 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 5180 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 5181 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 5182 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 5183 /// follows one of the following patterns: 5184 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 5185 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 5186 /// If the SCEV expression of \p Op conforms with one of the expected patterns 5187 /// we return the type of the truncation operation, and indicate whether the 5188 /// truncated type should be treated as signed/unsigned by setting 5189 /// \p Signed to true/false, respectively. 5190 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 5191 bool &Signed, ScalarEvolution &SE) { 5192 // The case where Op == SymbolicPHI (that is, with no type conversions on 5193 // the way) is handled by the regular add recurrence creating logic and 5194 // would have already been triggered in createAddRecForPHI. Reaching it here 5195 // means that createAddRecFromPHI had failed for this PHI before (e.g., 5196 // because one of the other operands of the SCEVAddExpr updating this PHI is 5197 // not invariant). 5198 // 5199 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 5200 // this case predicates that allow us to prove that Op == SymbolicPHI will 5201 // be added. 5202 if (Op == SymbolicPHI) 5203 return nullptr; 5204 5205 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 5206 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 5207 if (SourceBits != NewBits) 5208 return nullptr; 5209 5210 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 5211 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 5212 if (!SExt && !ZExt) 5213 return nullptr; 5214 const SCEVTruncateExpr *Trunc = 5215 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 5216 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 5217 if (!Trunc) 5218 return nullptr; 5219 const SCEV *X = Trunc->getOperand(); 5220 if (X != SymbolicPHI) 5221 return nullptr; 5222 Signed = SExt != nullptr; 5223 return Trunc->getType(); 5224 } 5225 5226 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 5227 if (!PN->getType()->isIntegerTy()) 5228 return nullptr; 5229 const Loop *L = LI.getLoopFor(PN->getParent()); 5230 if (!L || L->getHeader() != PN->getParent()) 5231 return nullptr; 5232 return L; 5233 } 5234 5235 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 5236 // computation that updates the phi follows the following pattern: 5237 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 5238 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 5239 // If so, try to see if it can be rewritten as an AddRecExpr under some 5240 // Predicates. If successful, return them as a pair. Also cache the results 5241 // of the analysis. 5242 // 5243 // Example usage scenario: 5244 // Say the Rewriter is called for the following SCEV: 5245 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 5246 // where: 5247 // %X = phi i64 (%Start, %BEValue) 5248 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 5249 // and call this function with %SymbolicPHI = %X. 5250 // 5251 // The analysis will find that the value coming around the backedge has 5252 // the following SCEV: 5253 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 5254 // Upon concluding that this matches the desired pattern, the function 5255 // will return the pair {NewAddRec, SmallPredsVec} where: 5256 // NewAddRec = {%Start,+,%Step} 5257 // SmallPredsVec = {P1, P2, P3} as follows: 5258 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 5259 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 5260 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 5261 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 5262 // under the predicates {P1,P2,P3}. 5263 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 5264 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 5265 // 5266 // TODO's: 5267 // 5268 // 1) Extend the Induction descriptor to also support inductions that involve 5269 // casts: When needed (namely, when we are called in the context of the 5270 // vectorizer induction analysis), a Set of cast instructions will be 5271 // populated by this method, and provided back to isInductionPHI. This is 5272 // needed to allow the vectorizer to properly record them to be ignored by 5273 // the cost model and to avoid vectorizing them (otherwise these casts, 5274 // which are redundant under the runtime overflow checks, will be 5275 // vectorized, which can be costly). 5276 // 5277 // 2) Support additional induction/PHISCEV patterns: We also want to support 5278 // inductions where the sext-trunc / zext-trunc operations (partly) occur 5279 // after the induction update operation (the induction increment): 5280 // 5281 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 5282 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 5283 // 5284 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 5285 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 5286 // 5287 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 5288 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5289 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 5290 SmallVector<const SCEVPredicate *, 3> Predicates; 5291 5292 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 5293 // return an AddRec expression under some predicate. 5294 5295 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5296 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5297 assert(L && "Expecting an integer loop header phi"); 5298 5299 // The loop may have multiple entrances or multiple exits; we can analyze 5300 // this phi as an addrec if it has a unique entry value and a unique 5301 // backedge value. 5302 Value *BEValueV = nullptr, *StartValueV = nullptr; 5303 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5304 Value *V = PN->getIncomingValue(i); 5305 if (L->contains(PN->getIncomingBlock(i))) { 5306 if (!BEValueV) { 5307 BEValueV = V; 5308 } else if (BEValueV != V) { 5309 BEValueV = nullptr; 5310 break; 5311 } 5312 } else if (!StartValueV) { 5313 StartValueV = V; 5314 } else if (StartValueV != V) { 5315 StartValueV = nullptr; 5316 break; 5317 } 5318 } 5319 if (!BEValueV || !StartValueV) 5320 return None; 5321 5322 const SCEV *BEValue = getSCEV(BEValueV); 5323 5324 // If the value coming around the backedge is an add with the symbolic 5325 // value we just inserted, possibly with casts that we can ignore under 5326 // an appropriate runtime guard, then we found a simple induction variable! 5327 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 5328 if (!Add) 5329 return None; 5330 5331 // If there is a single occurrence of the symbolic value, possibly 5332 // casted, replace it with a recurrence. 5333 unsigned FoundIndex = Add->getNumOperands(); 5334 Type *TruncTy = nullptr; 5335 bool Signed; 5336 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5337 if ((TruncTy = 5338 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 5339 if (FoundIndex == e) { 5340 FoundIndex = i; 5341 break; 5342 } 5343 5344 if (FoundIndex == Add->getNumOperands()) 5345 return None; 5346 5347 // Create an add with everything but the specified operand. 5348 SmallVector<const SCEV *, 8> Ops; 5349 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5350 if (i != FoundIndex) 5351 Ops.push_back(Add->getOperand(i)); 5352 const SCEV *Accum = getAddExpr(Ops); 5353 5354 // The runtime checks will not be valid if the step amount is 5355 // varying inside the loop. 5356 if (!isLoopInvariant(Accum, L)) 5357 return None; 5358 5359 // *** Part2: Create the predicates 5360 5361 // Analysis was successful: we have a phi-with-cast pattern for which we 5362 // can return an AddRec expression under the following predicates: 5363 // 5364 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 5365 // fits within the truncated type (does not overflow) for i = 0 to n-1. 5366 // P2: An Equal predicate that guarantees that 5367 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 5368 // P3: An Equal predicate that guarantees that 5369 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 5370 // 5371 // As we next prove, the above predicates guarantee that: 5372 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 5373 // 5374 // 5375 // More formally, we want to prove that: 5376 // Expr(i+1) = Start + (i+1) * Accum 5377 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5378 // 5379 // Given that: 5380 // 1) Expr(0) = Start 5381 // 2) Expr(1) = Start + Accum 5382 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 5383 // 3) Induction hypothesis (step i): 5384 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 5385 // 5386 // Proof: 5387 // Expr(i+1) = 5388 // = Start + (i+1)*Accum 5389 // = (Start + i*Accum) + Accum 5390 // = Expr(i) + Accum 5391 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 5392 // :: from step i 5393 // 5394 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 5395 // 5396 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 5397 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 5398 // + Accum :: from P3 5399 // 5400 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 5401 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 5402 // 5403 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 5404 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5405 // 5406 // By induction, the same applies to all iterations 1<=i<n: 5407 // 5408 5409 // Create a truncated addrec for which we will add a no overflow check (P1). 5410 const SCEV *StartVal = getSCEV(StartValueV); 5411 const SCEV *PHISCEV = 5412 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 5413 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 5414 5415 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 5416 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 5417 // will be constant. 5418 // 5419 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 5420 // add P1. 5421 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 5422 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 5423 Signed ? SCEVWrapPredicate::IncrementNSSW 5424 : SCEVWrapPredicate::IncrementNUSW; 5425 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 5426 Predicates.push_back(AddRecPred); 5427 } 5428 5429 // Create the Equal Predicates P2,P3: 5430 5431 // It is possible that the predicates P2 and/or P3 are computable at 5432 // compile time due to StartVal and/or Accum being constants. 5433 // If either one is, then we can check that now and escape if either P2 5434 // or P3 is false. 5435 5436 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 5437 // for each of StartVal and Accum 5438 auto getExtendedExpr = [&](const SCEV *Expr, 5439 bool CreateSignExtend) -> const SCEV * { 5440 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 5441 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 5442 const SCEV *ExtendedExpr = 5443 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 5444 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 5445 return ExtendedExpr; 5446 }; 5447 5448 // Given: 5449 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 5450 // = getExtendedExpr(Expr) 5451 // Determine whether the predicate P: Expr == ExtendedExpr 5452 // is known to be false at compile time 5453 auto PredIsKnownFalse = [&](const SCEV *Expr, 5454 const SCEV *ExtendedExpr) -> bool { 5455 return Expr != ExtendedExpr && 5456 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 5457 }; 5458 5459 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 5460 if (PredIsKnownFalse(StartVal, StartExtended)) { 5461 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 5462 return None; 5463 } 5464 5465 // The Step is always Signed (because the overflow checks are either 5466 // NSSW or NUSW) 5467 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 5468 if (PredIsKnownFalse(Accum, AccumExtended)) { 5469 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 5470 return None; 5471 } 5472 5473 auto AppendPredicate = [&](const SCEV *Expr, 5474 const SCEV *ExtendedExpr) -> void { 5475 if (Expr != ExtendedExpr && 5476 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 5477 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 5478 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 5479 Predicates.push_back(Pred); 5480 } 5481 }; 5482 5483 AppendPredicate(StartVal, StartExtended); 5484 AppendPredicate(Accum, AccumExtended); 5485 5486 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 5487 // which the casts had been folded away. The caller can rewrite SymbolicPHI 5488 // into NewAR if it will also add the runtime overflow checks specified in 5489 // Predicates. 5490 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 5491 5492 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 5493 std::make_pair(NewAR, Predicates); 5494 // Remember the result of the analysis for this SCEV at this locayyytion. 5495 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 5496 return PredRewrite; 5497 } 5498 5499 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5500 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5501 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5502 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5503 if (!L) 5504 return None; 5505 5506 // Check to see if we already analyzed this PHI. 5507 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5508 if (I != PredicatedSCEVRewrites.end()) { 5509 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5510 I->second; 5511 // Analysis was done before and failed to create an AddRec: 5512 if (Rewrite.first == SymbolicPHI) 5513 return None; 5514 // Analysis was done before and succeeded to create an AddRec under 5515 // a predicate: 5516 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5517 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5518 return Rewrite; 5519 } 5520 5521 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5522 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5523 5524 // Record in the cache that the analysis failed 5525 if (!Rewrite) { 5526 SmallVector<const SCEVPredicate *, 3> Predicates; 5527 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5528 return None; 5529 } 5530 5531 return Rewrite; 5532 } 5533 5534 // FIXME: This utility is currently required because the Rewriter currently 5535 // does not rewrite this expression: 5536 // {0, +, (sext ix (trunc iy to ix) to iy)} 5537 // into {0, +, %step}, 5538 // even when the following Equal predicate exists: 5539 // "%step == (sext ix (trunc iy to ix) to iy)". 5540 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5541 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5542 if (AR1 == AR2) 5543 return true; 5544 5545 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5546 if (Expr1 != Expr2 && !Preds->implies(SE.getEqualPredicate(Expr1, Expr2)) && 5547 !Preds->implies(SE.getEqualPredicate(Expr2, Expr1))) 5548 return false; 5549 return true; 5550 }; 5551 5552 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5553 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5554 return false; 5555 return true; 5556 } 5557 5558 /// A helper function for createAddRecFromPHI to handle simple cases. 5559 /// 5560 /// This function tries to find an AddRec expression for the simplest (yet most 5561 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5562 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5563 /// technique for finding the AddRec expression. 5564 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5565 Value *BEValueV, 5566 Value *StartValueV) { 5567 const Loop *L = LI.getLoopFor(PN->getParent()); 5568 assert(L && L->getHeader() == PN->getParent()); 5569 assert(BEValueV && StartValueV); 5570 5571 auto BO = MatchBinaryOp(BEValueV, DT); 5572 if (!BO) 5573 return nullptr; 5574 5575 if (BO->Opcode != Instruction::Add) 5576 return nullptr; 5577 5578 const SCEV *Accum = nullptr; 5579 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5580 Accum = getSCEV(BO->RHS); 5581 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5582 Accum = getSCEV(BO->LHS); 5583 5584 if (!Accum) 5585 return nullptr; 5586 5587 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5588 if (BO->IsNUW) 5589 Flags = setFlags(Flags, SCEV::FlagNUW); 5590 if (BO->IsNSW) 5591 Flags = setFlags(Flags, SCEV::FlagNSW); 5592 5593 const SCEV *StartVal = getSCEV(StartValueV); 5594 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5595 insertValueToMap(PN, PHISCEV); 5596 5597 // We can add Flags to the post-inc expression only if we 5598 // know that it is *undefined behavior* for BEValueV to 5599 // overflow. 5600 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) { 5601 assert(isLoopInvariant(Accum, L) && 5602 "Accum is defined outside L, but is not invariant?"); 5603 if (isAddRecNeverPoison(BEInst, L)) 5604 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5605 } 5606 5607 return PHISCEV; 5608 } 5609 5610 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5611 const Loop *L = LI.getLoopFor(PN->getParent()); 5612 if (!L || L->getHeader() != PN->getParent()) 5613 return nullptr; 5614 5615 // The loop may have multiple entrances or multiple exits; we can analyze 5616 // this phi as an addrec if it has a unique entry value and a unique 5617 // backedge value. 5618 Value *BEValueV = nullptr, *StartValueV = nullptr; 5619 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5620 Value *V = PN->getIncomingValue(i); 5621 if (L->contains(PN->getIncomingBlock(i))) { 5622 if (!BEValueV) { 5623 BEValueV = V; 5624 } else if (BEValueV != V) { 5625 BEValueV = nullptr; 5626 break; 5627 } 5628 } else if (!StartValueV) { 5629 StartValueV = V; 5630 } else if (StartValueV != V) { 5631 StartValueV = nullptr; 5632 break; 5633 } 5634 } 5635 if (!BEValueV || !StartValueV) 5636 return nullptr; 5637 5638 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5639 "PHI node already processed?"); 5640 5641 // First, try to find AddRec expression without creating a fictituos symbolic 5642 // value for PN. 5643 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5644 return S; 5645 5646 // Handle PHI node value symbolically. 5647 const SCEV *SymbolicName = getUnknown(PN); 5648 insertValueToMap(PN, SymbolicName); 5649 5650 // Using this symbolic name for the PHI, analyze the value coming around 5651 // the back-edge. 5652 const SCEV *BEValue = getSCEV(BEValueV); 5653 5654 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5655 // has a special value for the first iteration of the loop. 5656 5657 // If the value coming around the backedge is an add with the symbolic 5658 // value we just inserted, then we found a simple induction variable! 5659 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5660 // If there is a single occurrence of the symbolic value, replace it 5661 // with a recurrence. 5662 unsigned FoundIndex = Add->getNumOperands(); 5663 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5664 if (Add->getOperand(i) == SymbolicName) 5665 if (FoundIndex == e) { 5666 FoundIndex = i; 5667 break; 5668 } 5669 5670 if (FoundIndex != Add->getNumOperands()) { 5671 // Create an add with everything but the specified operand. 5672 SmallVector<const SCEV *, 8> Ops; 5673 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5674 if (i != FoundIndex) 5675 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5676 L, *this)); 5677 const SCEV *Accum = getAddExpr(Ops); 5678 5679 // This is not a valid addrec if the step amount is varying each 5680 // loop iteration, but is not itself an addrec in this loop. 5681 if (isLoopInvariant(Accum, L) || 5682 (isa<SCEVAddRecExpr>(Accum) && 5683 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5684 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5685 5686 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5687 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5688 if (BO->IsNUW) 5689 Flags = setFlags(Flags, SCEV::FlagNUW); 5690 if (BO->IsNSW) 5691 Flags = setFlags(Flags, SCEV::FlagNSW); 5692 } 5693 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5694 // If the increment is an inbounds GEP, then we know the address 5695 // space cannot be wrapped around. We cannot make any guarantee 5696 // about signed or unsigned overflow because pointers are 5697 // unsigned but we may have a negative index from the base 5698 // pointer. We can guarantee that no unsigned wrap occurs if the 5699 // indices form a positive value. 5700 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5701 Flags = setFlags(Flags, SCEV::FlagNW); 5702 5703 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5704 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5705 Flags = setFlags(Flags, SCEV::FlagNUW); 5706 } 5707 5708 // We cannot transfer nuw and nsw flags from subtraction 5709 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5710 // for instance. 5711 } 5712 5713 const SCEV *StartVal = getSCEV(StartValueV); 5714 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5715 5716 // Okay, for the entire analysis of this edge we assumed the PHI 5717 // to be symbolic. We now need to go back and purge all of the 5718 // entries for the scalars that use the symbolic expression. 5719 forgetMemoizedResults(SymbolicName); 5720 insertValueToMap(PN, PHISCEV); 5721 5722 // We can add Flags to the post-inc expression only if we 5723 // know that it is *undefined behavior* for BEValueV to 5724 // overflow. 5725 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5726 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5727 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5728 5729 return PHISCEV; 5730 } 5731 } 5732 } else { 5733 // Otherwise, this could be a loop like this: 5734 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5735 // In this case, j = {1,+,1} and BEValue is j. 5736 // Because the other in-value of i (0) fits the evolution of BEValue 5737 // i really is an addrec evolution. 5738 // 5739 // We can generalize this saying that i is the shifted value of BEValue 5740 // by one iteration: 5741 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5742 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5743 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5744 if (Shifted != getCouldNotCompute() && 5745 Start != getCouldNotCompute()) { 5746 const SCEV *StartVal = getSCEV(StartValueV); 5747 if (Start == StartVal) { 5748 // Okay, for the entire analysis of this edge we assumed the PHI 5749 // to be symbolic. We now need to go back and purge all of the 5750 // entries for the scalars that use the symbolic expression. 5751 forgetMemoizedResults(SymbolicName); 5752 insertValueToMap(PN, Shifted); 5753 return Shifted; 5754 } 5755 } 5756 } 5757 5758 // Remove the temporary PHI node SCEV that has been inserted while intending 5759 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5760 // as it will prevent later (possibly simpler) SCEV expressions to be added 5761 // to the ValueExprMap. 5762 eraseValueFromMap(PN); 5763 5764 return nullptr; 5765 } 5766 5767 // Checks if the SCEV S is available at BB. S is considered available at BB 5768 // if S can be materialized at BB without introducing a fault. 5769 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5770 BasicBlock *BB) { 5771 struct CheckAvailable { 5772 bool TraversalDone = false; 5773 bool Available = true; 5774 5775 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5776 BasicBlock *BB = nullptr; 5777 DominatorTree &DT; 5778 5779 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5780 : L(L), BB(BB), DT(DT) {} 5781 5782 bool setUnavailable() { 5783 TraversalDone = true; 5784 Available = false; 5785 return false; 5786 } 5787 5788 bool follow(const SCEV *S) { 5789 switch (S->getSCEVType()) { 5790 case scConstant: 5791 case scPtrToInt: 5792 case scTruncate: 5793 case scZeroExtend: 5794 case scSignExtend: 5795 case scAddExpr: 5796 case scMulExpr: 5797 case scUMaxExpr: 5798 case scSMaxExpr: 5799 case scUMinExpr: 5800 case scSMinExpr: 5801 case scSequentialUMinExpr: 5802 // These expressions are available if their operand(s) is/are. 5803 return true; 5804 5805 case scAddRecExpr: { 5806 // We allow add recurrences that are on the loop BB is in, or some 5807 // outer loop. This guarantees availability because the value of the 5808 // add recurrence at BB is simply the "current" value of the induction 5809 // variable. We can relax this in the future; for instance an add 5810 // recurrence on a sibling dominating loop is also available at BB. 5811 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5812 if (L && (ARLoop == L || ARLoop->contains(L))) 5813 return true; 5814 5815 return setUnavailable(); 5816 } 5817 5818 case scUnknown: { 5819 // For SCEVUnknown, we check for simple dominance. 5820 const auto *SU = cast<SCEVUnknown>(S); 5821 Value *V = SU->getValue(); 5822 5823 if (isa<Argument>(V)) 5824 return false; 5825 5826 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5827 return false; 5828 5829 return setUnavailable(); 5830 } 5831 5832 case scUDivExpr: 5833 case scCouldNotCompute: 5834 // We do not try to smart about these at all. 5835 return setUnavailable(); 5836 } 5837 llvm_unreachable("Unknown SCEV kind!"); 5838 } 5839 5840 bool isDone() { return TraversalDone; } 5841 }; 5842 5843 CheckAvailable CA(L, BB, DT); 5844 SCEVTraversal<CheckAvailable> ST(CA); 5845 5846 ST.visitAll(S); 5847 return CA.Available; 5848 } 5849 5850 // Try to match a control flow sequence that branches out at BI and merges back 5851 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5852 // match. 5853 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5854 Value *&C, Value *&LHS, Value *&RHS) { 5855 C = BI->getCondition(); 5856 5857 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5858 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5859 5860 if (!LeftEdge.isSingleEdge()) 5861 return false; 5862 5863 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5864 5865 Use &LeftUse = Merge->getOperandUse(0); 5866 Use &RightUse = Merge->getOperandUse(1); 5867 5868 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5869 LHS = LeftUse; 5870 RHS = RightUse; 5871 return true; 5872 } 5873 5874 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5875 LHS = RightUse; 5876 RHS = LeftUse; 5877 return true; 5878 } 5879 5880 return false; 5881 } 5882 5883 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5884 auto IsReachable = 5885 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5886 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5887 const Loop *L = LI.getLoopFor(PN->getParent()); 5888 5889 // We don't want to break LCSSA, even in a SCEV expression tree. 5890 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5891 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5892 return nullptr; 5893 5894 // Try to match 5895 // 5896 // br %cond, label %left, label %right 5897 // left: 5898 // br label %merge 5899 // right: 5900 // br label %merge 5901 // merge: 5902 // V = phi [ %x, %left ], [ %y, %right ] 5903 // 5904 // as "select %cond, %x, %y" 5905 5906 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5907 assert(IDom && "At least the entry block should dominate PN"); 5908 5909 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5910 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5911 5912 if (BI && BI->isConditional() && 5913 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5914 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5915 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5916 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5917 } 5918 5919 return nullptr; 5920 } 5921 5922 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5923 if (const SCEV *S = createAddRecFromPHI(PN)) 5924 return S; 5925 5926 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5927 return S; 5928 5929 // If the PHI has a single incoming value, follow that value, unless the 5930 // PHI's incoming blocks are in a different loop, in which case doing so 5931 // risks breaking LCSSA form. Instcombine would normally zap these, but 5932 // it doesn't have DominatorTree information, so it may miss cases. 5933 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5934 if (LI.replacementPreservesLCSSAForm(PN, V)) 5935 return getSCEV(V); 5936 5937 // If it's not a loop phi, we can't handle it yet. 5938 return getUnknown(PN); 5939 } 5940 5941 bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind, 5942 SCEVTypes RootKind) { 5943 struct FindClosure { 5944 const SCEV *OperandToFind; 5945 const SCEVTypes RootKind; // Must be a sequential min/max expression. 5946 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind. 5947 5948 bool Found = false; 5949 5950 bool canRecurseInto(SCEVTypes Kind) const { 5951 // We can only recurse into the SCEV expression of the same effective type 5952 // as the type of our root SCEV expression, and into zero-extensions. 5953 return RootKind == Kind || NonSequentialRootKind == Kind || 5954 scZeroExtend == Kind; 5955 }; 5956 5957 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind) 5958 : OperandToFind(OperandToFind), RootKind(RootKind), 5959 NonSequentialRootKind( 5960 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType( 5961 RootKind)) {} 5962 5963 bool follow(const SCEV *S) { 5964 Found = S == OperandToFind; 5965 5966 return !isDone() && canRecurseInto(S->getSCEVType()); 5967 } 5968 5969 bool isDone() const { return Found; } 5970 }; 5971 5972 FindClosure FC(OperandToFind, RootKind); 5973 visitAll(Root, FC); 5974 return FC.Found; 5975 } 5976 5977 const SCEV *ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond( 5978 Instruction *I, ICmpInst *Cond, Value *TrueVal, Value *FalseVal) { 5979 // Try to match some simple smax or umax patterns. 5980 auto *ICI = Cond; 5981 5982 Value *LHS = ICI->getOperand(0); 5983 Value *RHS = ICI->getOperand(1); 5984 5985 switch (ICI->getPredicate()) { 5986 case ICmpInst::ICMP_SLT: 5987 case ICmpInst::ICMP_SLE: 5988 case ICmpInst::ICMP_ULT: 5989 case ICmpInst::ICMP_ULE: 5990 std::swap(LHS, RHS); 5991 LLVM_FALLTHROUGH; 5992 case ICmpInst::ICMP_SGT: 5993 case ICmpInst::ICMP_SGE: 5994 case ICmpInst::ICMP_UGT: 5995 case ICmpInst::ICMP_UGE: 5996 // a > b ? a+x : b+x -> max(a, b)+x 5997 // a > b ? b+x : a+x -> min(a, b)+x 5998 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5999 bool Signed = ICI->isSigned(); 6000 const SCEV *LA = getSCEV(TrueVal); 6001 const SCEV *RA = getSCEV(FalseVal); 6002 const SCEV *LS = getSCEV(LHS); 6003 const SCEV *RS = getSCEV(RHS); 6004 if (LA->getType()->isPointerTy()) { 6005 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA. 6006 // Need to make sure we can't produce weird expressions involving 6007 // negated pointers. 6008 if (LA == LS && RA == RS) 6009 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS); 6010 if (LA == RS && RA == LS) 6011 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS); 6012 } 6013 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * { 6014 if (Op->getType()->isPointerTy()) { 6015 Op = getLosslessPtrToIntExpr(Op); 6016 if (isa<SCEVCouldNotCompute>(Op)) 6017 return Op; 6018 } 6019 if (Signed) 6020 Op = getNoopOrSignExtend(Op, I->getType()); 6021 else 6022 Op = getNoopOrZeroExtend(Op, I->getType()); 6023 return Op; 6024 }; 6025 LS = CoerceOperand(LS); 6026 RS = CoerceOperand(RS); 6027 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS)) 6028 break; 6029 const SCEV *LDiff = getMinusSCEV(LA, LS); 6030 const SCEV *RDiff = getMinusSCEV(RA, RS); 6031 if (LDiff == RDiff) 6032 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS), 6033 LDiff); 6034 LDiff = getMinusSCEV(LA, RS); 6035 RDiff = getMinusSCEV(RA, LS); 6036 if (LDiff == RDiff) 6037 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS), 6038 LDiff); 6039 } 6040 break; 6041 case ICmpInst::ICMP_NE: 6042 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y 6043 std::swap(TrueVal, FalseVal); 6044 LLVM_FALLTHROUGH; 6045 case ICmpInst::ICMP_EQ: 6046 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1 6047 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 6048 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 6049 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 6050 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y 6051 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y 6052 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x 6053 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y 6054 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1)) 6055 return getAddExpr(getUMaxExpr(X, C), Y); 6056 } 6057 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...)) 6058 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...)) 6059 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...) 6060 // -> umin_seq(x, umin (..., umin_seq(...), ...)) 6061 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero() && 6062 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) { 6063 const SCEV *X = getSCEV(LHS); 6064 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X)) 6065 X = ZExt->getOperand(); 6066 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(I->getType())) { 6067 const SCEV *FalseValExpr = getSCEV(FalseVal); 6068 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr)) 6069 return getUMinExpr(getNoopOrZeroExtend(X, I->getType()), FalseValExpr, 6070 /*Sequential=*/true); 6071 } 6072 } 6073 break; 6074 default: 6075 break; 6076 } 6077 6078 return getUnknown(I); 6079 } 6080 6081 static Optional<const SCEV *> 6082 createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr, 6083 const SCEV *TrueExpr, const SCEV *FalseExpr) { 6084 assert(CondExpr->getType()->isIntegerTy(1) && 6085 TrueExpr->getType() == FalseExpr->getType() && 6086 TrueExpr->getType()->isIntegerTy(1) && 6087 "Unexpected operands of a select."); 6088 6089 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0) 6090 // --> C + (umin_seq cond, x - C) 6091 // 6092 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C)) 6093 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0) 6094 // --> C + (umin_seq ~cond, x - C) 6095 6096 // FIXME: while we can't legally model the case where both of the hands 6097 // are fully variable, we only require that the *difference* is constant. 6098 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr)) 6099 return None; 6100 6101 const SCEV *X, *C; 6102 if (isa<SCEVConstant>(TrueExpr)) { 6103 CondExpr = SE->getNotSCEV(CondExpr); 6104 X = FalseExpr; 6105 C = TrueExpr; 6106 } else { 6107 X = TrueExpr; 6108 C = FalseExpr; 6109 } 6110 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C), 6111 /*Sequential=*/true)); 6112 } 6113 6114 static Optional<const SCEV *> createNodeForSelectViaUMinSeq(ScalarEvolution *SE, 6115 Value *Cond, 6116 Value *TrueVal, 6117 Value *FalseVal) { 6118 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal)) 6119 return None; 6120 6121 return createNodeForSelectViaUMinSeq( 6122 SE, SE->getSCEV(Cond), SE->getSCEV(TrueVal), SE->getSCEV(FalseVal)); 6123 } 6124 6125 const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq( 6126 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) { 6127 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?"); 6128 assert(TrueVal->getType() == FalseVal->getType() && 6129 V->getType() == TrueVal->getType() && 6130 "Types of select hands and of the result must match."); 6131 6132 // For now, only deal with i1-typed `select`s. 6133 if (!V->getType()->isIntegerTy(1)) 6134 return getUnknown(V); 6135 6136 if (Optional<const SCEV *> S = 6137 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal)) 6138 return *S; 6139 6140 return getUnknown(V); 6141 } 6142 6143 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond, 6144 Value *TrueVal, 6145 Value *FalseVal) { 6146 // Handle "constant" branch or select. This can occur for instance when a 6147 // loop pass transforms an inner loop and moves on to process the outer loop. 6148 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 6149 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 6150 6151 if (auto *I = dyn_cast<Instruction>(V)) { 6152 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) { 6153 const SCEV *S = createNodeForSelectOrPHIInstWithICmpInstCond( 6154 I, ICI, TrueVal, FalseVal); 6155 if (!isa<SCEVUnknown>(S)) 6156 return S; 6157 } 6158 } 6159 6160 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal); 6161 } 6162 6163 /// Expand GEP instructions into add and multiply operations. This allows them 6164 /// to be analyzed by regular SCEV code. 6165 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 6166 // Don't attempt to analyze GEPs over unsized objects. 6167 if (!GEP->getSourceElementType()->isSized()) 6168 return getUnknown(GEP); 6169 6170 SmallVector<const SCEV *, 4> IndexExprs; 6171 for (Value *Index : GEP->indices()) 6172 IndexExprs.push_back(getSCEV(Index)); 6173 return getGEPExpr(GEP, IndexExprs); 6174 } 6175 6176 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 6177 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 6178 return C->getAPInt().countTrailingZeros(); 6179 6180 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 6181 return GetMinTrailingZeros(I->getOperand()); 6182 6183 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 6184 return std::min(GetMinTrailingZeros(T->getOperand()), 6185 (uint32_t)getTypeSizeInBits(T->getType())); 6186 6187 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 6188 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 6189 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 6190 ? getTypeSizeInBits(E->getType()) 6191 : OpRes; 6192 } 6193 6194 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 6195 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 6196 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 6197 ? getTypeSizeInBits(E->getType()) 6198 : OpRes; 6199 } 6200 6201 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 6202 // The result is the min of all operands results. 6203 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 6204 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 6205 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 6206 return MinOpRes; 6207 } 6208 6209 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 6210 // The result is the sum of all operands results. 6211 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 6212 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 6213 for (unsigned i = 1, e = M->getNumOperands(); 6214 SumOpRes != BitWidth && i != e; ++i) 6215 SumOpRes = 6216 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 6217 return SumOpRes; 6218 } 6219 6220 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 6221 // The result is the min of all operands results. 6222 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 6223 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 6224 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 6225 return MinOpRes; 6226 } 6227 6228 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 6229 // The result is the min of all operands results. 6230 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 6231 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 6232 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 6233 return MinOpRes; 6234 } 6235 6236 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 6237 // The result is the min of all operands results. 6238 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 6239 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 6240 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 6241 return MinOpRes; 6242 } 6243 6244 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6245 // For a SCEVUnknown, ask ValueTracking. 6246 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 6247 return Known.countMinTrailingZeros(); 6248 } 6249 6250 // SCEVUDivExpr 6251 return 0; 6252 } 6253 6254 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 6255 auto I = MinTrailingZerosCache.find(S); 6256 if (I != MinTrailingZerosCache.end()) 6257 return I->second; 6258 6259 uint32_t Result = GetMinTrailingZerosImpl(S); 6260 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 6261 assert(InsertPair.second && "Should insert a new key"); 6262 return InsertPair.first->second; 6263 } 6264 6265 /// Helper method to assign a range to V from metadata present in the IR. 6266 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 6267 if (Instruction *I = dyn_cast<Instruction>(V)) 6268 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 6269 return getConstantRangeFromMetadata(*MD); 6270 6271 return None; 6272 } 6273 6274 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 6275 SCEV::NoWrapFlags Flags) { 6276 if (AddRec->getNoWrapFlags(Flags) != Flags) { 6277 AddRec->setNoWrapFlags(Flags); 6278 UnsignedRanges.erase(AddRec); 6279 SignedRanges.erase(AddRec); 6280 } 6281 } 6282 6283 ConstantRange ScalarEvolution:: 6284 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 6285 const DataLayout &DL = getDataLayout(); 6286 6287 unsigned BitWidth = getTypeSizeInBits(U->getType()); 6288 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 6289 6290 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 6291 // use information about the trip count to improve our available range. Note 6292 // that the trip count independent cases are already handled by known bits. 6293 // WARNING: The definition of recurrence used here is subtly different than 6294 // the one used by AddRec (and thus most of this file). Step is allowed to 6295 // be arbitrarily loop varying here, where AddRec allows only loop invariant 6296 // and other addrecs in the same loop (for non-affine addrecs). The code 6297 // below intentionally handles the case where step is not loop invariant. 6298 auto *P = dyn_cast<PHINode>(U->getValue()); 6299 if (!P) 6300 return FullSet; 6301 6302 // Make sure that no Phi input comes from an unreachable block. Otherwise, 6303 // even the values that are not available in these blocks may come from them, 6304 // and this leads to false-positive recurrence test. 6305 for (auto *Pred : predecessors(P->getParent())) 6306 if (!DT.isReachableFromEntry(Pred)) 6307 return FullSet; 6308 6309 BinaryOperator *BO; 6310 Value *Start, *Step; 6311 if (!matchSimpleRecurrence(P, BO, Start, Step)) 6312 return FullSet; 6313 6314 // If we found a recurrence in reachable code, we must be in a loop. Note 6315 // that BO might be in some subloop of L, and that's completely okay. 6316 auto *L = LI.getLoopFor(P->getParent()); 6317 assert(L && L->getHeader() == P->getParent()); 6318 if (!L->contains(BO->getParent())) 6319 // NOTE: This bailout should be an assert instead. However, asserting 6320 // the condition here exposes a case where LoopFusion is querying SCEV 6321 // with malformed loop information during the midst of the transform. 6322 // There doesn't appear to be an obvious fix, so for the moment bailout 6323 // until the caller issue can be fixed. PR49566 tracks the bug. 6324 return FullSet; 6325 6326 // TODO: Extend to other opcodes such as mul, and div 6327 switch (BO->getOpcode()) { 6328 default: 6329 return FullSet; 6330 case Instruction::AShr: 6331 case Instruction::LShr: 6332 case Instruction::Shl: 6333 break; 6334 }; 6335 6336 if (BO->getOperand(0) != P) 6337 // TODO: Handle the power function forms some day. 6338 return FullSet; 6339 6340 unsigned TC = getSmallConstantMaxTripCount(L); 6341 if (!TC || TC >= BitWidth) 6342 return FullSet; 6343 6344 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 6345 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 6346 assert(KnownStart.getBitWidth() == BitWidth && 6347 KnownStep.getBitWidth() == BitWidth); 6348 6349 // Compute total shift amount, being careful of overflow and bitwidths. 6350 auto MaxShiftAmt = KnownStep.getMaxValue(); 6351 APInt TCAP(BitWidth, TC-1); 6352 bool Overflow = false; 6353 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 6354 if (Overflow) 6355 return FullSet; 6356 6357 switch (BO->getOpcode()) { 6358 default: 6359 llvm_unreachable("filtered out above"); 6360 case Instruction::AShr: { 6361 // For each ashr, three cases: 6362 // shift = 0 => unchanged value 6363 // saturation => 0 or -1 6364 // other => a value closer to zero (of the same sign) 6365 // Thus, the end value is closer to zero than the start. 6366 auto KnownEnd = KnownBits::ashr(KnownStart, 6367 KnownBits::makeConstant(TotalShift)); 6368 if (KnownStart.isNonNegative()) 6369 // Analogous to lshr (simply not yet canonicalized) 6370 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 6371 KnownStart.getMaxValue() + 1); 6372 if (KnownStart.isNegative()) 6373 // End >=u Start && End <=s Start 6374 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 6375 KnownEnd.getMaxValue() + 1); 6376 break; 6377 } 6378 case Instruction::LShr: { 6379 // For each lshr, three cases: 6380 // shift = 0 => unchanged value 6381 // saturation => 0 6382 // other => a smaller positive number 6383 // Thus, the low end of the unsigned range is the last value produced. 6384 auto KnownEnd = KnownBits::lshr(KnownStart, 6385 KnownBits::makeConstant(TotalShift)); 6386 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 6387 KnownStart.getMaxValue() + 1); 6388 } 6389 case Instruction::Shl: { 6390 // Iff no bits are shifted out, value increases on every shift. 6391 auto KnownEnd = KnownBits::shl(KnownStart, 6392 KnownBits::makeConstant(TotalShift)); 6393 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 6394 return ConstantRange(KnownStart.getMinValue(), 6395 KnownEnd.getMaxValue() + 1); 6396 break; 6397 } 6398 }; 6399 return FullSet; 6400 } 6401 6402 /// Determine the range for a particular SCEV. If SignHint is 6403 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 6404 /// with a "cleaner" unsigned (resp. signed) representation. 6405 const ConstantRange & 6406 ScalarEvolution::getRangeRef(const SCEV *S, 6407 ScalarEvolution::RangeSignHint SignHint) { 6408 DenseMap<const SCEV *, ConstantRange> &Cache = 6409 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 6410 : SignedRanges; 6411 ConstantRange::PreferredRangeType RangeType = 6412 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 6413 ? ConstantRange::Unsigned : ConstantRange::Signed; 6414 6415 // See if we've computed this range already. 6416 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 6417 if (I != Cache.end()) 6418 return I->second; 6419 6420 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 6421 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 6422 6423 unsigned BitWidth = getTypeSizeInBits(S->getType()); 6424 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 6425 using OBO = OverflowingBinaryOperator; 6426 6427 // If the value has known zeros, the maximum value will have those known zeros 6428 // as well. 6429 uint32_t TZ = GetMinTrailingZeros(S); 6430 if (TZ != 0) { 6431 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 6432 ConservativeResult = 6433 ConstantRange(APInt::getMinValue(BitWidth), 6434 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 6435 else 6436 ConservativeResult = ConstantRange( 6437 APInt::getSignedMinValue(BitWidth), 6438 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 6439 } 6440 6441 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 6442 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 6443 unsigned WrapType = OBO::AnyWrap; 6444 if (Add->hasNoSignedWrap()) 6445 WrapType |= OBO::NoSignedWrap; 6446 if (Add->hasNoUnsignedWrap()) 6447 WrapType |= OBO::NoUnsignedWrap; 6448 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 6449 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 6450 WrapType, RangeType); 6451 return setRange(Add, SignHint, 6452 ConservativeResult.intersectWith(X, RangeType)); 6453 } 6454 6455 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 6456 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 6457 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 6458 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 6459 return setRange(Mul, SignHint, 6460 ConservativeResult.intersectWith(X, RangeType)); 6461 } 6462 6463 if (isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) { 6464 Intrinsic::ID ID; 6465 switch (S->getSCEVType()) { 6466 case scUMaxExpr: 6467 ID = Intrinsic::umax; 6468 break; 6469 case scSMaxExpr: 6470 ID = Intrinsic::smax; 6471 break; 6472 case scUMinExpr: 6473 case scSequentialUMinExpr: 6474 ID = Intrinsic::umin; 6475 break; 6476 case scSMinExpr: 6477 ID = Intrinsic::smin; 6478 break; 6479 default: 6480 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr."); 6481 } 6482 6483 const auto *NAry = cast<SCEVNAryExpr>(S); 6484 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint); 6485 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i) 6486 X = X.intrinsic(ID, {X, getRangeRef(NAry->getOperand(i), SignHint)}); 6487 return setRange(S, SignHint, 6488 ConservativeResult.intersectWith(X, RangeType)); 6489 } 6490 6491 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 6492 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 6493 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 6494 return setRange(UDiv, SignHint, 6495 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 6496 } 6497 6498 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 6499 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 6500 return setRange(ZExt, SignHint, 6501 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 6502 RangeType)); 6503 } 6504 6505 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 6506 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 6507 return setRange(SExt, SignHint, 6508 ConservativeResult.intersectWith(X.signExtend(BitWidth), 6509 RangeType)); 6510 } 6511 6512 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 6513 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 6514 return setRange(PtrToInt, SignHint, X); 6515 } 6516 6517 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 6518 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 6519 return setRange(Trunc, SignHint, 6520 ConservativeResult.intersectWith(X.truncate(BitWidth), 6521 RangeType)); 6522 } 6523 6524 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 6525 // If there's no unsigned wrap, the value will never be less than its 6526 // initial value. 6527 if (AddRec->hasNoUnsignedWrap()) { 6528 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 6529 if (!UnsignedMinValue.isZero()) 6530 ConservativeResult = ConservativeResult.intersectWith( 6531 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 6532 } 6533 6534 // If there's no signed wrap, and all the operands except initial value have 6535 // the same sign or zero, the value won't ever be: 6536 // 1: smaller than initial value if operands are non negative, 6537 // 2: bigger than initial value if operands are non positive. 6538 // For both cases, value can not cross signed min/max boundary. 6539 if (AddRec->hasNoSignedWrap()) { 6540 bool AllNonNeg = true; 6541 bool AllNonPos = true; 6542 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 6543 if (!isKnownNonNegative(AddRec->getOperand(i))) 6544 AllNonNeg = false; 6545 if (!isKnownNonPositive(AddRec->getOperand(i))) 6546 AllNonPos = false; 6547 } 6548 if (AllNonNeg) 6549 ConservativeResult = ConservativeResult.intersectWith( 6550 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 6551 APInt::getSignedMinValue(BitWidth)), 6552 RangeType); 6553 else if (AllNonPos) 6554 ConservativeResult = ConservativeResult.intersectWith( 6555 ConstantRange::getNonEmpty( 6556 APInt::getSignedMinValue(BitWidth), 6557 getSignedRangeMax(AddRec->getStart()) + 1), 6558 RangeType); 6559 } 6560 6561 // TODO: non-affine addrec 6562 if (AddRec->isAffine()) { 6563 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 6564 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 6565 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 6566 auto RangeFromAffine = getRangeForAffineAR( 6567 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6568 BitWidth); 6569 ConservativeResult = 6570 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 6571 6572 auto RangeFromFactoring = getRangeViaFactoring( 6573 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6574 BitWidth); 6575 ConservativeResult = 6576 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 6577 } 6578 6579 // Now try symbolic BE count and more powerful methods. 6580 if (UseExpensiveRangeSharpening) { 6581 const SCEV *SymbolicMaxBECount = 6582 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 6583 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 6584 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6585 AddRec->hasNoSelfWrap()) { 6586 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 6587 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 6588 ConservativeResult = 6589 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 6590 } 6591 } 6592 } 6593 6594 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 6595 } 6596 6597 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6598 6599 // Check if the IR explicitly contains !range metadata. 6600 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 6601 if (MDRange.hasValue()) 6602 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 6603 RangeType); 6604 6605 // Use facts about recurrences in the underlying IR. Note that add 6606 // recurrences are AddRecExprs and thus don't hit this path. This 6607 // primarily handles shift recurrences. 6608 auto CR = getRangeForUnknownRecurrence(U); 6609 ConservativeResult = ConservativeResult.intersectWith(CR); 6610 6611 // See if ValueTracking can give us a useful range. 6612 const DataLayout &DL = getDataLayout(); 6613 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6614 if (Known.getBitWidth() != BitWidth) 6615 Known = Known.zextOrTrunc(BitWidth); 6616 6617 // ValueTracking may be able to compute a tighter result for the number of 6618 // sign bits than for the value of those sign bits. 6619 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6620 if (U->getType()->isPointerTy()) { 6621 // If the pointer size is larger than the index size type, this can cause 6622 // NS to be larger than BitWidth. So compensate for this. 6623 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6624 int ptrIdxDiff = ptrSize - BitWidth; 6625 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6626 NS -= ptrIdxDiff; 6627 } 6628 6629 if (NS > 1) { 6630 // If we know any of the sign bits, we know all of the sign bits. 6631 if (!Known.Zero.getHiBits(NS).isZero()) 6632 Known.Zero.setHighBits(NS); 6633 if (!Known.One.getHiBits(NS).isZero()) 6634 Known.One.setHighBits(NS); 6635 } 6636 6637 if (Known.getMinValue() != Known.getMaxValue() + 1) 6638 ConservativeResult = ConservativeResult.intersectWith( 6639 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6640 RangeType); 6641 if (NS > 1) 6642 ConservativeResult = ConservativeResult.intersectWith( 6643 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6644 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6645 RangeType); 6646 6647 // A range of Phi is a subset of union of all ranges of its input. 6648 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 6649 // Make sure that we do not run over cycled Phis. 6650 if (PendingPhiRanges.insert(Phi).second) { 6651 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 6652 for (auto &Op : Phi->operands()) { 6653 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 6654 RangeFromOps = RangeFromOps.unionWith(OpRange); 6655 // No point to continue if we already have a full set. 6656 if (RangeFromOps.isFullSet()) 6657 break; 6658 } 6659 ConservativeResult = 6660 ConservativeResult.intersectWith(RangeFromOps, RangeType); 6661 bool Erased = PendingPhiRanges.erase(Phi); 6662 assert(Erased && "Failed to erase Phi properly?"); 6663 (void) Erased; 6664 } 6665 } 6666 6667 return setRange(U, SignHint, std::move(ConservativeResult)); 6668 } 6669 6670 return setRange(S, SignHint, std::move(ConservativeResult)); 6671 } 6672 6673 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6674 // values that the expression can take. Initially, the expression has a value 6675 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6676 // argument defines if we treat Step as signed or unsigned. 6677 static ConstantRange getRangeForAffineARHelper(APInt Step, 6678 const ConstantRange &StartRange, 6679 const APInt &MaxBECount, 6680 unsigned BitWidth, bool Signed) { 6681 // If either Step or MaxBECount is 0, then the expression won't change, and we 6682 // just need to return the initial range. 6683 if (Step == 0 || MaxBECount == 0) 6684 return StartRange; 6685 6686 // If we don't know anything about the initial value (i.e. StartRange is 6687 // FullRange), then we don't know anything about the final range either. 6688 // Return FullRange. 6689 if (StartRange.isFullSet()) 6690 return ConstantRange::getFull(BitWidth); 6691 6692 // If Step is signed and negative, then we use its absolute value, but we also 6693 // note that we're moving in the opposite direction. 6694 bool Descending = Signed && Step.isNegative(); 6695 6696 if (Signed) 6697 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6698 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6699 // This equations hold true due to the well-defined wrap-around behavior of 6700 // APInt. 6701 Step = Step.abs(); 6702 6703 // Check if Offset is more than full span of BitWidth. If it is, the 6704 // expression is guaranteed to overflow. 6705 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6706 return ConstantRange::getFull(BitWidth); 6707 6708 // Offset is by how much the expression can change. Checks above guarantee no 6709 // overflow here. 6710 APInt Offset = Step * MaxBECount; 6711 6712 // Minimum value of the final range will match the minimal value of StartRange 6713 // if the expression is increasing and will be decreased by Offset otherwise. 6714 // Maximum value of the final range will match the maximal value of StartRange 6715 // if the expression is decreasing and will be increased by Offset otherwise. 6716 APInt StartLower = StartRange.getLower(); 6717 APInt StartUpper = StartRange.getUpper() - 1; 6718 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6719 : (StartUpper + std::move(Offset)); 6720 6721 // It's possible that the new minimum/maximum value will fall into the initial 6722 // range (due to wrap around). This means that the expression can take any 6723 // value in this bitwidth, and we have to return full range. 6724 if (StartRange.contains(MovedBoundary)) 6725 return ConstantRange::getFull(BitWidth); 6726 6727 APInt NewLower = 6728 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6729 APInt NewUpper = 6730 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6731 NewUpper += 1; 6732 6733 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6734 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6735 } 6736 6737 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6738 const SCEV *Step, 6739 const SCEV *MaxBECount, 6740 unsigned BitWidth) { 6741 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6742 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6743 "Precondition!"); 6744 6745 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6746 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6747 6748 // First, consider step signed. 6749 ConstantRange StartSRange = getSignedRange(Start); 6750 ConstantRange StepSRange = getSignedRange(Step); 6751 6752 // If Step can be both positive and negative, we need to find ranges for the 6753 // maximum absolute step values in both directions and union them. 6754 ConstantRange SR = 6755 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6756 MaxBECountValue, BitWidth, /* Signed = */ true); 6757 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6758 StartSRange, MaxBECountValue, 6759 BitWidth, /* Signed = */ true)); 6760 6761 // Next, consider step unsigned. 6762 ConstantRange UR = getRangeForAffineARHelper( 6763 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6764 MaxBECountValue, BitWidth, /* Signed = */ false); 6765 6766 // Finally, intersect signed and unsigned ranges. 6767 return SR.intersectWith(UR, ConstantRange::Smallest); 6768 } 6769 6770 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6771 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6772 ScalarEvolution::RangeSignHint SignHint) { 6773 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6774 assert(AddRec->hasNoSelfWrap() && 6775 "This only works for non-self-wrapping AddRecs!"); 6776 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6777 const SCEV *Step = AddRec->getStepRecurrence(*this); 6778 // Only deal with constant step to save compile time. 6779 if (!isa<SCEVConstant>(Step)) 6780 return ConstantRange::getFull(BitWidth); 6781 // Let's make sure that we can prove that we do not self-wrap during 6782 // MaxBECount iterations. We need this because MaxBECount is a maximum 6783 // iteration count estimate, and we might infer nw from some exit for which we 6784 // do not know max exit count (or any other side reasoning). 6785 // TODO: Turn into assert at some point. 6786 if (getTypeSizeInBits(MaxBECount->getType()) > 6787 getTypeSizeInBits(AddRec->getType())) 6788 return ConstantRange::getFull(BitWidth); 6789 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6790 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6791 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6792 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6793 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6794 MaxItersWithoutWrap)) 6795 return ConstantRange::getFull(BitWidth); 6796 6797 ICmpInst::Predicate LEPred = 6798 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6799 ICmpInst::Predicate GEPred = 6800 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6801 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6802 6803 // We know that there is no self-wrap. Let's take Start and End values and 6804 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6805 // the iteration. They either lie inside the range [Min(Start, End), 6806 // Max(Start, End)] or outside it: 6807 // 6808 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6809 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6810 // 6811 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6812 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6813 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6814 // Start <= End and step is positive, or Start >= End and step is negative. 6815 const SCEV *Start = AddRec->getStart(); 6816 ConstantRange StartRange = getRangeRef(Start, SignHint); 6817 ConstantRange EndRange = getRangeRef(End, SignHint); 6818 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6819 // If they already cover full iteration space, we will know nothing useful 6820 // even if we prove what we want to prove. 6821 if (RangeBetween.isFullSet()) 6822 return RangeBetween; 6823 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6824 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6825 : RangeBetween.isWrappedSet(); 6826 if (IsWrappedSet) 6827 return ConstantRange::getFull(BitWidth); 6828 6829 if (isKnownPositive(Step) && 6830 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6831 return RangeBetween; 6832 else if (isKnownNegative(Step) && 6833 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6834 return RangeBetween; 6835 return ConstantRange::getFull(BitWidth); 6836 } 6837 6838 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6839 const SCEV *Step, 6840 const SCEV *MaxBECount, 6841 unsigned BitWidth) { 6842 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6843 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6844 6845 struct SelectPattern { 6846 Value *Condition = nullptr; 6847 APInt TrueValue; 6848 APInt FalseValue; 6849 6850 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6851 const SCEV *S) { 6852 Optional<unsigned> CastOp; 6853 APInt Offset(BitWidth, 0); 6854 6855 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6856 "Should be!"); 6857 6858 // Peel off a constant offset: 6859 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6860 // In the future we could consider being smarter here and handle 6861 // {Start+Step,+,Step} too. 6862 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6863 return; 6864 6865 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6866 S = SA->getOperand(1); 6867 } 6868 6869 // Peel off a cast operation 6870 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6871 CastOp = SCast->getSCEVType(); 6872 S = SCast->getOperand(); 6873 } 6874 6875 using namespace llvm::PatternMatch; 6876 6877 auto *SU = dyn_cast<SCEVUnknown>(S); 6878 const APInt *TrueVal, *FalseVal; 6879 if (!SU || 6880 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6881 m_APInt(FalseVal)))) { 6882 Condition = nullptr; 6883 return; 6884 } 6885 6886 TrueValue = *TrueVal; 6887 FalseValue = *FalseVal; 6888 6889 // Re-apply the cast we peeled off earlier 6890 if (CastOp.hasValue()) 6891 switch (*CastOp) { 6892 default: 6893 llvm_unreachable("Unknown SCEV cast type!"); 6894 6895 case scTruncate: 6896 TrueValue = TrueValue.trunc(BitWidth); 6897 FalseValue = FalseValue.trunc(BitWidth); 6898 break; 6899 case scZeroExtend: 6900 TrueValue = TrueValue.zext(BitWidth); 6901 FalseValue = FalseValue.zext(BitWidth); 6902 break; 6903 case scSignExtend: 6904 TrueValue = TrueValue.sext(BitWidth); 6905 FalseValue = FalseValue.sext(BitWidth); 6906 break; 6907 } 6908 6909 // Re-apply the constant offset we peeled off earlier 6910 TrueValue += Offset; 6911 FalseValue += Offset; 6912 } 6913 6914 bool isRecognized() { return Condition != nullptr; } 6915 }; 6916 6917 SelectPattern StartPattern(*this, BitWidth, Start); 6918 if (!StartPattern.isRecognized()) 6919 return ConstantRange::getFull(BitWidth); 6920 6921 SelectPattern StepPattern(*this, BitWidth, Step); 6922 if (!StepPattern.isRecognized()) 6923 return ConstantRange::getFull(BitWidth); 6924 6925 if (StartPattern.Condition != StepPattern.Condition) { 6926 // We don't handle this case today; but we could, by considering four 6927 // possibilities below instead of two. I'm not sure if there are cases where 6928 // that will help over what getRange already does, though. 6929 return ConstantRange::getFull(BitWidth); 6930 } 6931 6932 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6933 // construct arbitrary general SCEV expressions here. This function is called 6934 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6935 // say) can end up caching a suboptimal value. 6936 6937 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6938 // C2352 and C2512 (otherwise it isn't needed). 6939 6940 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6941 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6942 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6943 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6944 6945 ConstantRange TrueRange = 6946 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6947 ConstantRange FalseRange = 6948 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6949 6950 return TrueRange.unionWith(FalseRange); 6951 } 6952 6953 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6954 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6955 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6956 6957 // Return early if there are no flags to propagate to the SCEV. 6958 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6959 if (BinOp->hasNoUnsignedWrap()) 6960 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6961 if (BinOp->hasNoSignedWrap()) 6962 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6963 if (Flags == SCEV::FlagAnyWrap) 6964 return SCEV::FlagAnyWrap; 6965 6966 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6967 } 6968 6969 const Instruction * 6970 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) { 6971 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) 6972 return &*AddRec->getLoop()->getHeader()->begin(); 6973 if (auto *U = dyn_cast<SCEVUnknown>(S)) 6974 if (auto *I = dyn_cast<Instruction>(U->getValue())) 6975 return I; 6976 return nullptr; 6977 } 6978 6979 /// Fills \p Ops with unique operands of \p S, if it has operands. If not, 6980 /// \p Ops remains unmodified. 6981 static void collectUniqueOps(const SCEV *S, 6982 SmallVectorImpl<const SCEV *> &Ops) { 6983 SmallPtrSet<const SCEV *, 4> Unique; 6984 auto InsertUnique = [&](const SCEV *S) { 6985 if (Unique.insert(S).second) 6986 Ops.push_back(S); 6987 }; 6988 if (auto *S2 = dyn_cast<SCEVCastExpr>(S)) 6989 for (auto *Op : S2->operands()) 6990 InsertUnique(Op); 6991 else if (auto *S2 = dyn_cast<SCEVNAryExpr>(S)) 6992 for (auto *Op : S2->operands()) 6993 InsertUnique(Op); 6994 else if (auto *S2 = dyn_cast<SCEVUDivExpr>(S)) 6995 for (auto *Op : S2->operands()) 6996 InsertUnique(Op); 6997 } 6998 6999 const Instruction * 7000 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops, 7001 bool &Precise) { 7002 Precise = true; 7003 // Do a bounded search of the def relation of the requested SCEVs. 7004 SmallSet<const SCEV *, 16> Visited; 7005 SmallVector<const SCEV *> Worklist; 7006 auto pushOp = [&](const SCEV *S) { 7007 if (!Visited.insert(S).second) 7008 return; 7009 // Threshold of 30 here is arbitrary. 7010 if (Visited.size() > 30) { 7011 Precise = false; 7012 return; 7013 } 7014 Worklist.push_back(S); 7015 }; 7016 7017 for (auto *S : Ops) 7018 pushOp(S); 7019 7020 const Instruction *Bound = nullptr; 7021 while (!Worklist.empty()) { 7022 auto *S = Worklist.pop_back_val(); 7023 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) { 7024 if (!Bound || DT.dominates(Bound, DefI)) 7025 Bound = DefI; 7026 } else { 7027 SmallVector<const SCEV *, 4> Ops; 7028 collectUniqueOps(S, Ops); 7029 for (auto *Op : Ops) 7030 pushOp(Op); 7031 } 7032 } 7033 return Bound ? Bound : &*F.getEntryBlock().begin(); 7034 } 7035 7036 const Instruction * 7037 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) { 7038 bool Discard; 7039 return getDefiningScopeBound(Ops, Discard); 7040 } 7041 7042 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A, 7043 const Instruction *B) { 7044 if (A->getParent() == B->getParent() && 7045 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 7046 B->getIterator())) 7047 return true; 7048 7049 auto *BLoop = LI.getLoopFor(B->getParent()); 7050 if (BLoop && BLoop->getHeader() == B->getParent() && 7051 BLoop->getLoopPreheader() == A->getParent() && 7052 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 7053 A->getParent()->end()) && 7054 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(), 7055 B->getIterator())) 7056 return true; 7057 return false; 7058 } 7059 7060 7061 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 7062 // Only proceed if we can prove that I does not yield poison. 7063 if (!programUndefinedIfPoison(I)) 7064 return false; 7065 7066 // At this point we know that if I is executed, then it does not wrap 7067 // according to at least one of NSW or NUW. If I is not executed, then we do 7068 // not know if the calculation that I represents would wrap. Multiple 7069 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 7070 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 7071 // derived from other instructions that map to the same SCEV. We cannot make 7072 // that guarantee for cases where I is not executed. So we need to find a 7073 // upper bound on the defining scope for the SCEV, and prove that I is 7074 // executed every time we enter that scope. When the bounding scope is a 7075 // loop (the common case), this is equivalent to proving I executes on every 7076 // iteration of that loop. 7077 SmallVector<const SCEV *> SCEVOps; 7078 for (const Use &Op : I->operands()) { 7079 // I could be an extractvalue from a call to an overflow intrinsic. 7080 // TODO: We can do better here in some cases. 7081 if (isSCEVable(Op->getType())) 7082 SCEVOps.push_back(getSCEV(Op)); 7083 } 7084 auto *DefI = getDefiningScopeBound(SCEVOps); 7085 return isGuaranteedToTransferExecutionTo(DefI, I); 7086 } 7087 7088 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 7089 // If we know that \c I can never be poison period, then that's enough. 7090 if (isSCEVExprNeverPoison(I)) 7091 return true; 7092 7093 // For an add recurrence specifically, we assume that infinite loops without 7094 // side effects are undefined behavior, and then reason as follows: 7095 // 7096 // If the add recurrence is poison in any iteration, it is poison on all 7097 // future iterations (since incrementing poison yields poison). If the result 7098 // of the add recurrence is fed into the loop latch condition and the loop 7099 // does not contain any throws or exiting blocks other than the latch, we now 7100 // have the ability to "choose" whether the backedge is taken or not (by 7101 // choosing a sufficiently evil value for the poison feeding into the branch) 7102 // for every iteration including and after the one in which \p I first became 7103 // poison. There are two possibilities (let's call the iteration in which \p 7104 // I first became poison as K): 7105 // 7106 // 1. In the set of iterations including and after K, the loop body executes 7107 // no side effects. In this case executing the backege an infinte number 7108 // of times will yield undefined behavior. 7109 // 7110 // 2. In the set of iterations including and after K, the loop body executes 7111 // at least one side effect. In this case, that specific instance of side 7112 // effect is control dependent on poison, which also yields undefined 7113 // behavior. 7114 7115 auto *ExitingBB = L->getExitingBlock(); 7116 auto *LatchBB = L->getLoopLatch(); 7117 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 7118 return false; 7119 7120 SmallPtrSet<const Instruction *, 16> Pushed; 7121 SmallVector<const Instruction *, 8> PoisonStack; 7122 7123 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 7124 // things that are known to be poison under that assumption go on the 7125 // PoisonStack. 7126 Pushed.insert(I); 7127 PoisonStack.push_back(I); 7128 7129 bool LatchControlDependentOnPoison = false; 7130 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 7131 const Instruction *Poison = PoisonStack.pop_back_val(); 7132 7133 for (auto *PoisonUser : Poison->users()) { 7134 if (propagatesPoison(cast<Operator>(PoisonUser))) { 7135 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 7136 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 7137 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 7138 assert(BI->isConditional() && "Only possibility!"); 7139 if (BI->getParent() == LatchBB) { 7140 LatchControlDependentOnPoison = true; 7141 break; 7142 } 7143 } 7144 } 7145 } 7146 7147 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 7148 } 7149 7150 ScalarEvolution::LoopProperties 7151 ScalarEvolution::getLoopProperties(const Loop *L) { 7152 using LoopProperties = ScalarEvolution::LoopProperties; 7153 7154 auto Itr = LoopPropertiesCache.find(L); 7155 if (Itr == LoopPropertiesCache.end()) { 7156 auto HasSideEffects = [](Instruction *I) { 7157 if (auto *SI = dyn_cast<StoreInst>(I)) 7158 return !SI->isSimple(); 7159 7160 return I->mayThrow() || I->mayWriteToMemory(); 7161 }; 7162 7163 LoopProperties LP = {/* HasNoAbnormalExits */ true, 7164 /*HasNoSideEffects*/ true}; 7165 7166 for (auto *BB : L->getBlocks()) 7167 for (auto &I : *BB) { 7168 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 7169 LP.HasNoAbnormalExits = false; 7170 if (HasSideEffects(&I)) 7171 LP.HasNoSideEffects = false; 7172 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 7173 break; // We're already as pessimistic as we can get. 7174 } 7175 7176 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 7177 assert(InsertPair.second && "We just checked!"); 7178 Itr = InsertPair.first; 7179 } 7180 7181 return Itr->second; 7182 } 7183 7184 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) { 7185 // A mustprogress loop without side effects must be finite. 7186 // TODO: The check used here is very conservative. It's only *specific* 7187 // side effects which are well defined in infinite loops. 7188 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L)); 7189 } 7190 7191 const SCEV *ScalarEvolution::createSCEV(Value *V) { 7192 if (!isSCEVable(V->getType())) 7193 return getUnknown(V); 7194 7195 if (Instruction *I = dyn_cast<Instruction>(V)) { 7196 // Don't attempt to analyze instructions in blocks that aren't 7197 // reachable. Such instructions don't matter, and they aren't required 7198 // to obey basic rules for definitions dominating uses which this 7199 // analysis depends on. 7200 if (!DT.isReachableFromEntry(I->getParent())) 7201 return getUnknown(UndefValue::get(V->getType())); 7202 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 7203 return getConstant(CI); 7204 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 7205 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 7206 else if (!isa<ConstantExpr>(V)) 7207 return getUnknown(V); 7208 7209 Operator *U = cast<Operator>(V); 7210 if (auto BO = MatchBinaryOp(U, DT)) { 7211 switch (BO->Opcode) { 7212 case Instruction::Add: { 7213 // The simple thing to do would be to just call getSCEV on both operands 7214 // and call getAddExpr with the result. However if we're looking at a 7215 // bunch of things all added together, this can be quite inefficient, 7216 // because it leads to N-1 getAddExpr calls for N ultimate operands. 7217 // Instead, gather up all the operands and make a single getAddExpr call. 7218 // LLVM IR canonical form means we need only traverse the left operands. 7219 SmallVector<const SCEV *, 4> AddOps; 7220 do { 7221 if (BO->Op) { 7222 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 7223 AddOps.push_back(OpSCEV); 7224 break; 7225 } 7226 7227 // If a NUW or NSW flag can be applied to the SCEV for this 7228 // addition, then compute the SCEV for this addition by itself 7229 // with a separate call to getAddExpr. We need to do that 7230 // instead of pushing the operands of the addition onto AddOps, 7231 // since the flags are only known to apply to this particular 7232 // addition - they may not apply to other additions that can be 7233 // formed with operands from AddOps. 7234 const SCEV *RHS = getSCEV(BO->RHS); 7235 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 7236 if (Flags != SCEV::FlagAnyWrap) { 7237 const SCEV *LHS = getSCEV(BO->LHS); 7238 if (BO->Opcode == Instruction::Sub) 7239 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 7240 else 7241 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 7242 break; 7243 } 7244 } 7245 7246 if (BO->Opcode == Instruction::Sub) 7247 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 7248 else 7249 AddOps.push_back(getSCEV(BO->RHS)); 7250 7251 auto NewBO = MatchBinaryOp(BO->LHS, DT); 7252 if (!NewBO || (NewBO->Opcode != Instruction::Add && 7253 NewBO->Opcode != Instruction::Sub)) { 7254 AddOps.push_back(getSCEV(BO->LHS)); 7255 break; 7256 } 7257 BO = NewBO; 7258 } while (true); 7259 7260 return getAddExpr(AddOps); 7261 } 7262 7263 case Instruction::Mul: { 7264 SmallVector<const SCEV *, 4> MulOps; 7265 do { 7266 if (BO->Op) { 7267 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 7268 MulOps.push_back(OpSCEV); 7269 break; 7270 } 7271 7272 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 7273 if (Flags != SCEV::FlagAnyWrap) { 7274 MulOps.push_back( 7275 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 7276 break; 7277 } 7278 } 7279 7280 MulOps.push_back(getSCEV(BO->RHS)); 7281 auto NewBO = MatchBinaryOp(BO->LHS, DT); 7282 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 7283 MulOps.push_back(getSCEV(BO->LHS)); 7284 break; 7285 } 7286 BO = NewBO; 7287 } while (true); 7288 7289 return getMulExpr(MulOps); 7290 } 7291 case Instruction::UDiv: 7292 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7293 case Instruction::URem: 7294 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7295 case Instruction::Sub: { 7296 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 7297 if (BO->Op) 7298 Flags = getNoWrapFlagsFromUB(BO->Op); 7299 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 7300 } 7301 case Instruction::And: 7302 // For an expression like x&255 that merely masks off the high bits, 7303 // use zext(trunc(x)) as the SCEV expression. 7304 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 7305 if (CI->isZero()) 7306 return getSCEV(BO->RHS); 7307 if (CI->isMinusOne()) 7308 return getSCEV(BO->LHS); 7309 const APInt &A = CI->getValue(); 7310 7311 // Instcombine's ShrinkDemandedConstant may strip bits out of 7312 // constants, obscuring what would otherwise be a low-bits mask. 7313 // Use computeKnownBits to compute what ShrinkDemandedConstant 7314 // knew about to reconstruct a low-bits mask value. 7315 unsigned LZ = A.countLeadingZeros(); 7316 unsigned TZ = A.countTrailingZeros(); 7317 unsigned BitWidth = A.getBitWidth(); 7318 KnownBits Known(BitWidth); 7319 computeKnownBits(BO->LHS, Known, getDataLayout(), 7320 0, &AC, nullptr, &DT); 7321 7322 APInt EffectiveMask = 7323 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 7324 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 7325 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 7326 const SCEV *LHS = getSCEV(BO->LHS); 7327 const SCEV *ShiftedLHS = nullptr; 7328 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 7329 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 7330 // For an expression like (x * 8) & 8, simplify the multiply. 7331 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 7332 unsigned GCD = std::min(MulZeros, TZ); 7333 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 7334 SmallVector<const SCEV*, 4> MulOps; 7335 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 7336 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 7337 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 7338 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 7339 } 7340 } 7341 if (!ShiftedLHS) 7342 ShiftedLHS = getUDivExpr(LHS, MulCount); 7343 return getMulExpr( 7344 getZeroExtendExpr( 7345 getTruncateExpr(ShiftedLHS, 7346 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 7347 BO->LHS->getType()), 7348 MulCount); 7349 } 7350 } 7351 // Binary `and` is a bit-wise `umin`. 7352 if (BO->LHS->getType()->isIntegerTy(1)) 7353 return getUMinExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7354 break; 7355 7356 case Instruction::Or: 7357 // If the RHS of the Or is a constant, we may have something like: 7358 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 7359 // optimizations will transparently handle this case. 7360 // 7361 // In order for this transformation to be safe, the LHS must be of the 7362 // form X*(2^n) and the Or constant must be less than 2^n. 7363 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 7364 const SCEV *LHS = getSCEV(BO->LHS); 7365 const APInt &CIVal = CI->getValue(); 7366 if (GetMinTrailingZeros(LHS) >= 7367 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 7368 // Build a plain add SCEV. 7369 return getAddExpr(LHS, getSCEV(CI), 7370 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 7371 } 7372 } 7373 // Binary `or` is a bit-wise `umax`. 7374 if (BO->LHS->getType()->isIntegerTy(1)) 7375 return getUMaxExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7376 break; 7377 7378 case Instruction::Xor: 7379 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 7380 // If the RHS of xor is -1, then this is a not operation. 7381 if (CI->isMinusOne()) 7382 return getNotSCEV(getSCEV(BO->LHS)); 7383 7384 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 7385 // This is a variant of the check for xor with -1, and it handles 7386 // the case where instcombine has trimmed non-demanded bits out 7387 // of an xor with -1. 7388 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 7389 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 7390 if (LBO->getOpcode() == Instruction::And && 7391 LCI->getValue() == CI->getValue()) 7392 if (const SCEVZeroExtendExpr *Z = 7393 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 7394 Type *UTy = BO->LHS->getType(); 7395 const SCEV *Z0 = Z->getOperand(); 7396 Type *Z0Ty = Z0->getType(); 7397 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 7398 7399 // If C is a low-bits mask, the zero extend is serving to 7400 // mask off the high bits. Complement the operand and 7401 // re-apply the zext. 7402 if (CI->getValue().isMask(Z0TySize)) 7403 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 7404 7405 // If C is a single bit, it may be in the sign-bit position 7406 // before the zero-extend. In this case, represent the xor 7407 // using an add, which is equivalent, and re-apply the zext. 7408 APInt Trunc = CI->getValue().trunc(Z0TySize); 7409 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 7410 Trunc.isSignMask()) 7411 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 7412 UTy); 7413 } 7414 } 7415 break; 7416 7417 case Instruction::Shl: 7418 // Turn shift left of a constant amount into a multiply. 7419 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 7420 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 7421 7422 // If the shift count is not less than the bitwidth, the result of 7423 // the shift is undefined. Don't try to analyze it, because the 7424 // resolution chosen here may differ from the resolution chosen in 7425 // other parts of the compiler. 7426 if (SA->getValue().uge(BitWidth)) 7427 break; 7428 7429 // We can safely preserve the nuw flag in all cases. It's also safe to 7430 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 7431 // requires special handling. It can be preserved as long as we're not 7432 // left shifting by bitwidth - 1. 7433 auto Flags = SCEV::FlagAnyWrap; 7434 if (BO->Op) { 7435 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 7436 if ((MulFlags & SCEV::FlagNSW) && 7437 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 7438 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 7439 if (MulFlags & SCEV::FlagNUW) 7440 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 7441 } 7442 7443 ConstantInt *X = ConstantInt::get( 7444 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 7445 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags); 7446 } 7447 break; 7448 7449 case Instruction::AShr: { 7450 // AShr X, C, where C is a constant. 7451 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 7452 if (!CI) 7453 break; 7454 7455 Type *OuterTy = BO->LHS->getType(); 7456 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 7457 // If the shift count is not less than the bitwidth, the result of 7458 // the shift is undefined. Don't try to analyze it, because the 7459 // resolution chosen here may differ from the resolution chosen in 7460 // other parts of the compiler. 7461 if (CI->getValue().uge(BitWidth)) 7462 break; 7463 7464 if (CI->isZero()) 7465 return getSCEV(BO->LHS); // shift by zero --> noop 7466 7467 uint64_t AShrAmt = CI->getZExtValue(); 7468 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 7469 7470 Operator *L = dyn_cast<Operator>(BO->LHS); 7471 if (L && L->getOpcode() == Instruction::Shl) { 7472 // X = Shl A, n 7473 // Y = AShr X, m 7474 // Both n and m are constant. 7475 7476 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 7477 if (L->getOperand(1) == BO->RHS) 7478 // For a two-shift sext-inreg, i.e. n = m, 7479 // use sext(trunc(x)) as the SCEV expression. 7480 return getSignExtendExpr( 7481 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 7482 7483 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 7484 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 7485 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 7486 if (ShlAmt > AShrAmt) { 7487 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 7488 // expression. We already checked that ShlAmt < BitWidth, so 7489 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 7490 // ShlAmt - AShrAmt < Amt. 7491 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 7492 ShlAmt - AShrAmt); 7493 return getSignExtendExpr( 7494 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 7495 getConstant(Mul)), OuterTy); 7496 } 7497 } 7498 } 7499 break; 7500 } 7501 } 7502 } 7503 7504 switch (U->getOpcode()) { 7505 case Instruction::Trunc: 7506 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 7507 7508 case Instruction::ZExt: 7509 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7510 7511 case Instruction::SExt: 7512 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 7513 // The NSW flag of a subtract does not always survive the conversion to 7514 // A + (-1)*B. By pushing sign extension onto its operands we are much 7515 // more likely to preserve NSW and allow later AddRec optimisations. 7516 // 7517 // NOTE: This is effectively duplicating this logic from getSignExtend: 7518 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 7519 // but by that point the NSW information has potentially been lost. 7520 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 7521 Type *Ty = U->getType(); 7522 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 7523 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 7524 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 7525 } 7526 } 7527 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7528 7529 case Instruction::BitCast: 7530 // BitCasts are no-op casts so we just eliminate the cast. 7531 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 7532 return getSCEV(U->getOperand(0)); 7533 break; 7534 7535 case Instruction::PtrToInt: { 7536 // Pointer to integer cast is straight-forward, so do model it. 7537 const SCEV *Op = getSCEV(U->getOperand(0)); 7538 Type *DstIntTy = U->getType(); 7539 // But only if effective SCEV (integer) type is wide enough to represent 7540 // all possible pointer values. 7541 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 7542 if (isa<SCEVCouldNotCompute>(IntOp)) 7543 return getUnknown(V); 7544 return IntOp; 7545 } 7546 case Instruction::IntToPtr: 7547 // Just don't deal with inttoptr casts. 7548 return getUnknown(V); 7549 7550 case Instruction::SDiv: 7551 // If both operands are non-negative, this is just an udiv. 7552 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7553 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7554 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7555 break; 7556 7557 case Instruction::SRem: 7558 // If both operands are non-negative, this is just an urem. 7559 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7560 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7561 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7562 break; 7563 7564 case Instruction::GetElementPtr: 7565 return createNodeForGEP(cast<GEPOperator>(U)); 7566 7567 case Instruction::PHI: 7568 return createNodeForPHI(cast<PHINode>(U)); 7569 7570 case Instruction::Select: 7571 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1), 7572 U->getOperand(2)); 7573 7574 case Instruction::Call: 7575 case Instruction::Invoke: 7576 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 7577 return getSCEV(RV); 7578 7579 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 7580 switch (II->getIntrinsicID()) { 7581 case Intrinsic::abs: 7582 return getAbsExpr( 7583 getSCEV(II->getArgOperand(0)), 7584 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 7585 case Intrinsic::umax: 7586 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 7587 getSCEV(II->getArgOperand(1))); 7588 case Intrinsic::umin: 7589 return getUMinExpr(getSCEV(II->getArgOperand(0)), 7590 getSCEV(II->getArgOperand(1))); 7591 case Intrinsic::smax: 7592 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 7593 getSCEV(II->getArgOperand(1))); 7594 case Intrinsic::smin: 7595 return getSMinExpr(getSCEV(II->getArgOperand(0)), 7596 getSCEV(II->getArgOperand(1))); 7597 case Intrinsic::usub_sat: { 7598 const SCEV *X = getSCEV(II->getArgOperand(0)); 7599 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7600 const SCEV *ClampedY = getUMinExpr(X, Y); 7601 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 7602 } 7603 case Intrinsic::uadd_sat: { 7604 const SCEV *X = getSCEV(II->getArgOperand(0)); 7605 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7606 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 7607 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 7608 } 7609 case Intrinsic::start_loop_iterations: 7610 // A start_loop_iterations is just equivalent to the first operand for 7611 // SCEV purposes. 7612 return getSCEV(II->getArgOperand(0)); 7613 default: 7614 break; 7615 } 7616 } 7617 break; 7618 } 7619 7620 return getUnknown(V); 7621 } 7622 7623 //===----------------------------------------------------------------------===// 7624 // Iteration Count Computation Code 7625 // 7626 7627 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount, 7628 bool Extend) { 7629 if (isa<SCEVCouldNotCompute>(ExitCount)) 7630 return getCouldNotCompute(); 7631 7632 auto *ExitCountType = ExitCount->getType(); 7633 assert(ExitCountType->isIntegerTy()); 7634 7635 if (!Extend) 7636 return getAddExpr(ExitCount, getOne(ExitCountType)); 7637 7638 auto *WiderType = Type::getIntNTy(ExitCountType->getContext(), 7639 1 + ExitCountType->getScalarSizeInBits()); 7640 return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType), 7641 getOne(WiderType)); 7642 } 7643 7644 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 7645 if (!ExitCount) 7646 return 0; 7647 7648 ConstantInt *ExitConst = ExitCount->getValue(); 7649 7650 // Guard against huge trip counts. 7651 if (ExitConst->getValue().getActiveBits() > 32) 7652 return 0; 7653 7654 // In case of integer overflow, this returns 0, which is correct. 7655 return ((unsigned)ExitConst->getZExtValue()) + 1; 7656 } 7657 7658 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 7659 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 7660 return getConstantTripCount(ExitCount); 7661 } 7662 7663 unsigned 7664 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 7665 const BasicBlock *ExitingBlock) { 7666 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7667 assert(L->isLoopExiting(ExitingBlock) && 7668 "Exiting block must actually branch out of the loop!"); 7669 const SCEVConstant *ExitCount = 7670 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 7671 return getConstantTripCount(ExitCount); 7672 } 7673 7674 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 7675 const auto *MaxExitCount = 7676 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 7677 return getConstantTripCount(MaxExitCount); 7678 } 7679 7680 const SCEV *ScalarEvolution::getConstantMaxTripCountFromArray(const Loop *L) { 7681 // We can't infer from Array in Irregular Loop. 7682 // FIXME: It's hard to infer loop bound from array operated in Nested Loop. 7683 if (!L->isLoopSimplifyForm() || !L->isInnermost()) 7684 return getCouldNotCompute(); 7685 7686 // FIXME: To make the scene more typical, we only analysis loops that have 7687 // one exiting block and that block must be the latch. To make it easier to 7688 // capture loops that have memory access and memory access will be executed 7689 // in each iteration. 7690 const BasicBlock *LoopLatch = L->getLoopLatch(); 7691 assert(LoopLatch && "See defination of simplify form loop."); 7692 if (L->getExitingBlock() != LoopLatch) 7693 return getCouldNotCompute(); 7694 7695 const DataLayout &DL = getDataLayout(); 7696 SmallVector<const SCEV *> InferCountColl; 7697 for (auto *BB : L->getBlocks()) { 7698 // Go here, we can know that Loop is a single exiting and simplified form 7699 // loop. Make sure that infer from Memory Operation in those BBs must be 7700 // executed in loop. First step, we can make sure that max execution time 7701 // of MemAccessBB in loop represents latch max excution time. 7702 // If MemAccessBB does not dom Latch, skip. 7703 // Entry 7704 // │ 7705 // ┌─────▼─────┐ 7706 // │Loop Header◄─────┐ 7707 // └──┬──────┬─┘ │ 7708 // │ │ │ 7709 // ┌────────▼──┐ ┌─▼─────┐ │ 7710 // │MemAccessBB│ │OtherBB│ │ 7711 // └────────┬──┘ └─┬─────┘ │ 7712 // │ │ │ 7713 // ┌─▼──────▼─┐ │ 7714 // │Loop Latch├─────┘ 7715 // └────┬─────┘ 7716 // ▼ 7717 // Exit 7718 if (!DT.dominates(BB, LoopLatch)) 7719 continue; 7720 7721 for (Instruction &Inst : *BB) { 7722 // Find Memory Operation Instruction. 7723 auto *GEP = getLoadStorePointerOperand(&Inst); 7724 if (!GEP) 7725 continue; 7726 7727 auto *ElemSize = dyn_cast<SCEVConstant>(getElementSize(&Inst)); 7728 // Do not infer from scalar type, eg."ElemSize = sizeof()". 7729 if (!ElemSize) 7730 continue; 7731 7732 // Use a existing polynomial recurrence on the trip count. 7733 auto *AddRec = dyn_cast<SCEVAddRecExpr>(getSCEV(GEP)); 7734 if (!AddRec) 7735 continue; 7736 auto *ArrBase = dyn_cast<SCEVUnknown>(getPointerBase(AddRec)); 7737 auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*this)); 7738 if (!ArrBase || !Step) 7739 continue; 7740 assert(isLoopInvariant(ArrBase, L) && "See addrec definition"); 7741 7742 // Only handle { %array + step }, 7743 // FIXME: {(SCEVAddRecExpr) + step } could not be analysed here. 7744 if (AddRec->getStart() != ArrBase) 7745 continue; 7746 7747 // Memory operation pattern which have gaps. 7748 // Or repeat memory opreation. 7749 // And index of GEP wraps arround. 7750 if (Step->getAPInt().getActiveBits() > 32 || 7751 Step->getAPInt().getZExtValue() != 7752 ElemSize->getAPInt().getZExtValue() || 7753 Step->isZero() || Step->getAPInt().isNegative()) 7754 continue; 7755 7756 // Only infer from stack array which has certain size. 7757 // Make sure alloca instruction is not excuted in loop. 7758 AllocaInst *AllocateInst = dyn_cast<AllocaInst>(ArrBase->getValue()); 7759 if (!AllocateInst || L->contains(AllocateInst->getParent())) 7760 continue; 7761 7762 // Make sure only handle normal array. 7763 auto *Ty = dyn_cast<ArrayType>(AllocateInst->getAllocatedType()); 7764 auto *ArrSize = dyn_cast<ConstantInt>(AllocateInst->getArraySize()); 7765 if (!Ty || !ArrSize || !ArrSize->isOne()) 7766 continue; 7767 7768 // FIXME: Since gep indices are silently zext to the indexing type, 7769 // we will have a narrow gep index which wraps around rather than 7770 // increasing strictly, we shoule ensure that step is increasing 7771 // strictly by the loop iteration. 7772 // Now we can infer a max execution time by MemLength/StepLength. 7773 const SCEV *MemSize = 7774 getConstant(Step->getType(), DL.getTypeAllocSize(Ty)); 7775 auto *MaxExeCount = 7776 dyn_cast<SCEVConstant>(getUDivCeilSCEV(MemSize, Step)); 7777 if (!MaxExeCount || MaxExeCount->getAPInt().getActiveBits() > 32) 7778 continue; 7779 7780 // If the loop reaches the maximum number of executions, we can not 7781 // access bytes starting outside the statically allocated size without 7782 // being immediate UB. But it is allowed to enter loop header one more 7783 // time. 7784 auto *InferCount = dyn_cast<SCEVConstant>( 7785 getAddExpr(MaxExeCount, getOne(MaxExeCount->getType()))); 7786 // Discard the maximum number of execution times under 32bits. 7787 if (!InferCount || InferCount->getAPInt().getActiveBits() > 32) 7788 continue; 7789 7790 InferCountColl.push_back(InferCount); 7791 } 7792 } 7793 7794 if (InferCountColl.size() == 0) 7795 return getCouldNotCompute(); 7796 7797 return getUMinFromMismatchedTypes(InferCountColl); 7798 } 7799 7800 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 7801 SmallVector<BasicBlock *, 8> ExitingBlocks; 7802 L->getExitingBlocks(ExitingBlocks); 7803 7804 Optional<unsigned> Res = None; 7805 for (auto *ExitingBB : ExitingBlocks) { 7806 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 7807 if (!Res) 7808 Res = Multiple; 7809 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 7810 } 7811 return Res.getValueOr(1); 7812 } 7813 7814 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7815 const SCEV *ExitCount) { 7816 if (ExitCount == getCouldNotCompute()) 7817 return 1; 7818 7819 // Get the trip count 7820 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7821 7822 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7823 if (!TC) 7824 // Attempt to factor more general cases. Returns the greatest power of 7825 // two divisor. If overflow happens, the trip count expression is still 7826 // divisible by the greatest power of 2 divisor returned. 7827 return 1U << std::min((uint32_t)31, 7828 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7829 7830 ConstantInt *Result = TC->getValue(); 7831 7832 // Guard against huge trip counts (this requires checking 7833 // for zero to handle the case where the trip count == -1 and the 7834 // addition wraps). 7835 if (!Result || Result->getValue().getActiveBits() > 32 || 7836 Result->getValue().getActiveBits() == 0) 7837 return 1; 7838 7839 return (unsigned)Result->getZExtValue(); 7840 } 7841 7842 /// Returns the largest constant divisor of the trip count of this loop as a 7843 /// normal unsigned value, if possible. This means that the actual trip count is 7844 /// always a multiple of the returned value (don't forget the trip count could 7845 /// very well be zero as well!). 7846 /// 7847 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7848 /// multiple of a constant (which is also the case if the trip count is simply 7849 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7850 /// if the trip count is very large (>= 2^32). 7851 /// 7852 /// As explained in the comments for getSmallConstantTripCount, this assumes 7853 /// that control exits the loop via ExitingBlock. 7854 unsigned 7855 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7856 const BasicBlock *ExitingBlock) { 7857 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7858 assert(L->isLoopExiting(ExitingBlock) && 7859 "Exiting block must actually branch out of the loop!"); 7860 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7861 return getSmallConstantTripMultiple(L, ExitCount); 7862 } 7863 7864 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7865 const BasicBlock *ExitingBlock, 7866 ExitCountKind Kind) { 7867 switch (Kind) { 7868 case Exact: 7869 case SymbolicMaximum: 7870 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7871 case ConstantMaximum: 7872 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7873 }; 7874 llvm_unreachable("Invalid ExitCountKind!"); 7875 } 7876 7877 const SCEV * 7878 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7879 SmallVector<const SCEVPredicate *, 4> &Preds) { 7880 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7881 } 7882 7883 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7884 ExitCountKind Kind) { 7885 switch (Kind) { 7886 case Exact: 7887 return getBackedgeTakenInfo(L).getExact(L, this); 7888 case ConstantMaximum: 7889 return getBackedgeTakenInfo(L).getConstantMax(this); 7890 case SymbolicMaximum: 7891 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7892 }; 7893 llvm_unreachable("Invalid ExitCountKind!"); 7894 } 7895 7896 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7897 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7898 } 7899 7900 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7901 static void PushLoopPHIs(const Loop *L, 7902 SmallVectorImpl<Instruction *> &Worklist, 7903 SmallPtrSetImpl<Instruction *> &Visited) { 7904 BasicBlock *Header = L->getHeader(); 7905 7906 // Push all Loop-header PHIs onto the Worklist stack. 7907 for (PHINode &PN : Header->phis()) 7908 if (Visited.insert(&PN).second) 7909 Worklist.push_back(&PN); 7910 } 7911 7912 const ScalarEvolution::BackedgeTakenInfo & 7913 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7914 auto &BTI = getBackedgeTakenInfo(L); 7915 if (BTI.hasFullInfo()) 7916 return BTI; 7917 7918 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7919 7920 if (!Pair.second) 7921 return Pair.first->second; 7922 7923 BackedgeTakenInfo Result = 7924 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7925 7926 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7927 } 7928 7929 ScalarEvolution::BackedgeTakenInfo & 7930 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7931 // Initially insert an invalid entry for this loop. If the insertion 7932 // succeeds, proceed to actually compute a backedge-taken count and 7933 // update the value. The temporary CouldNotCompute value tells SCEV 7934 // code elsewhere that it shouldn't attempt to request a new 7935 // backedge-taken count, which could result in infinite recursion. 7936 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7937 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7938 if (!Pair.second) 7939 return Pair.first->second; 7940 7941 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7942 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7943 // must be cleared in this scope. 7944 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7945 7946 // In product build, there are no usage of statistic. 7947 (void)NumTripCountsComputed; 7948 (void)NumTripCountsNotComputed; 7949 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7950 const SCEV *BEExact = Result.getExact(L, this); 7951 if (BEExact != getCouldNotCompute()) { 7952 assert(isLoopInvariant(BEExact, L) && 7953 isLoopInvariant(Result.getConstantMax(this), L) && 7954 "Computed backedge-taken count isn't loop invariant for loop!"); 7955 ++NumTripCountsComputed; 7956 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7957 isa<PHINode>(L->getHeader()->begin())) { 7958 // Only count loops that have phi nodes as not being computable. 7959 ++NumTripCountsNotComputed; 7960 } 7961 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7962 7963 // Now that we know more about the trip count for this loop, forget any 7964 // existing SCEV values for PHI nodes in this loop since they are only 7965 // conservative estimates made without the benefit of trip count 7966 // information. This invalidation is not necessary for correctness, and is 7967 // only done to produce more precise results. 7968 if (Result.hasAnyInfo()) { 7969 // Invalidate any expression using an addrec in this loop. 7970 SmallVector<const SCEV *, 8> ToForget; 7971 auto LoopUsersIt = LoopUsers.find(L); 7972 if (LoopUsersIt != LoopUsers.end()) 7973 append_range(ToForget, LoopUsersIt->second); 7974 forgetMemoizedResults(ToForget); 7975 7976 // Invalidate constant-evolved loop header phis. 7977 for (PHINode &PN : L->getHeader()->phis()) 7978 ConstantEvolutionLoopExitValue.erase(&PN); 7979 } 7980 7981 // Re-lookup the insert position, since the call to 7982 // computeBackedgeTakenCount above could result in a 7983 // recusive call to getBackedgeTakenInfo (on a different 7984 // loop), which would invalidate the iterator computed 7985 // earlier. 7986 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7987 } 7988 7989 void ScalarEvolution::forgetAllLoops() { 7990 // This method is intended to forget all info about loops. It should 7991 // invalidate caches as if the following happened: 7992 // - The trip counts of all loops have changed arbitrarily 7993 // - Every llvm::Value has been updated in place to produce a different 7994 // result. 7995 BackedgeTakenCounts.clear(); 7996 PredicatedBackedgeTakenCounts.clear(); 7997 BECountUsers.clear(); 7998 LoopPropertiesCache.clear(); 7999 ConstantEvolutionLoopExitValue.clear(); 8000 ValueExprMap.clear(); 8001 ValuesAtScopes.clear(); 8002 ValuesAtScopesUsers.clear(); 8003 LoopDispositions.clear(); 8004 BlockDispositions.clear(); 8005 UnsignedRanges.clear(); 8006 SignedRanges.clear(); 8007 ExprValueMap.clear(); 8008 HasRecMap.clear(); 8009 MinTrailingZerosCache.clear(); 8010 PredicatedSCEVRewrites.clear(); 8011 } 8012 8013 void ScalarEvolution::forgetLoop(const Loop *L) { 8014 SmallVector<const Loop *, 16> LoopWorklist(1, L); 8015 SmallVector<Instruction *, 32> Worklist; 8016 SmallPtrSet<Instruction *, 16> Visited; 8017 SmallVector<const SCEV *, 16> ToForget; 8018 8019 // Iterate over all the loops and sub-loops to drop SCEV information. 8020 while (!LoopWorklist.empty()) { 8021 auto *CurrL = LoopWorklist.pop_back_val(); 8022 8023 // Drop any stored trip count value. 8024 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false); 8025 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true); 8026 8027 // Drop information about predicated SCEV rewrites for this loop. 8028 for (auto I = PredicatedSCEVRewrites.begin(); 8029 I != PredicatedSCEVRewrites.end();) { 8030 std::pair<const SCEV *, const Loop *> Entry = I->first; 8031 if (Entry.second == CurrL) 8032 PredicatedSCEVRewrites.erase(I++); 8033 else 8034 ++I; 8035 } 8036 8037 auto LoopUsersItr = LoopUsers.find(CurrL); 8038 if (LoopUsersItr != LoopUsers.end()) { 8039 ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(), 8040 LoopUsersItr->second.end()); 8041 } 8042 8043 // Drop information about expressions based on loop-header PHIs. 8044 PushLoopPHIs(CurrL, Worklist, Visited); 8045 8046 while (!Worklist.empty()) { 8047 Instruction *I = Worklist.pop_back_val(); 8048 8049 ValueExprMapType::iterator It = 8050 ValueExprMap.find_as(static_cast<Value *>(I)); 8051 if (It != ValueExprMap.end()) { 8052 eraseValueFromMap(It->first); 8053 ToForget.push_back(It->second); 8054 if (PHINode *PN = dyn_cast<PHINode>(I)) 8055 ConstantEvolutionLoopExitValue.erase(PN); 8056 } 8057 8058 PushDefUseChildren(I, Worklist, Visited); 8059 } 8060 8061 LoopPropertiesCache.erase(CurrL); 8062 // Forget all contained loops too, to avoid dangling entries in the 8063 // ValuesAtScopes map. 8064 LoopWorklist.append(CurrL->begin(), CurrL->end()); 8065 } 8066 forgetMemoizedResults(ToForget); 8067 } 8068 8069 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 8070 while (Loop *Parent = L->getParentLoop()) 8071 L = Parent; 8072 forgetLoop(L); 8073 } 8074 8075 void ScalarEvolution::forgetValue(Value *V) { 8076 Instruction *I = dyn_cast<Instruction>(V); 8077 if (!I) return; 8078 8079 // Drop information about expressions based on loop-header PHIs. 8080 SmallVector<Instruction *, 16> Worklist; 8081 SmallPtrSet<Instruction *, 8> Visited; 8082 SmallVector<const SCEV *, 8> ToForget; 8083 Worklist.push_back(I); 8084 Visited.insert(I); 8085 8086 while (!Worklist.empty()) { 8087 I = Worklist.pop_back_val(); 8088 ValueExprMapType::iterator It = 8089 ValueExprMap.find_as(static_cast<Value *>(I)); 8090 if (It != ValueExprMap.end()) { 8091 eraseValueFromMap(It->first); 8092 ToForget.push_back(It->second); 8093 if (PHINode *PN = dyn_cast<PHINode>(I)) 8094 ConstantEvolutionLoopExitValue.erase(PN); 8095 } 8096 8097 PushDefUseChildren(I, Worklist, Visited); 8098 } 8099 forgetMemoizedResults(ToForget); 8100 } 8101 8102 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 8103 LoopDispositions.clear(); 8104 } 8105 8106 /// Get the exact loop backedge taken count considering all loop exits. A 8107 /// computable result can only be returned for loops with all exiting blocks 8108 /// dominating the latch. howFarToZero assumes that the limit of each loop test 8109 /// is never skipped. This is a valid assumption as long as the loop exits via 8110 /// that test. For precise results, it is the caller's responsibility to specify 8111 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 8112 const SCEV * 8113 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 8114 SmallVector<const SCEVPredicate *, 4> *Preds) const { 8115 // If any exits were not computable, the loop is not computable. 8116 if (!isComplete() || ExitNotTaken.empty()) 8117 return SE->getCouldNotCompute(); 8118 8119 const BasicBlock *Latch = L->getLoopLatch(); 8120 // All exiting blocks we have collected must dominate the only backedge. 8121 if (!Latch) 8122 return SE->getCouldNotCompute(); 8123 8124 // All exiting blocks we have gathered dominate loop's latch, so exact trip 8125 // count is simply a minimum out of all these calculated exit counts. 8126 SmallVector<const SCEV *, 2> Ops; 8127 for (auto &ENT : ExitNotTaken) { 8128 const SCEV *BECount = ENT.ExactNotTaken; 8129 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 8130 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 8131 "We should only have known counts for exiting blocks that dominate " 8132 "latch!"); 8133 8134 Ops.push_back(BECount); 8135 8136 if (Preds) 8137 for (auto *P : ENT.Predicates) 8138 Preds->push_back(P); 8139 8140 assert((Preds || ENT.hasAlwaysTruePredicate()) && 8141 "Predicate should be always true!"); 8142 } 8143 8144 return SE->getUMinFromMismatchedTypes(Ops); 8145 } 8146 8147 /// Get the exact not taken count for this loop exit. 8148 const SCEV * 8149 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 8150 ScalarEvolution *SE) const { 8151 for (auto &ENT : ExitNotTaken) 8152 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 8153 return ENT.ExactNotTaken; 8154 8155 return SE->getCouldNotCompute(); 8156 } 8157 8158 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 8159 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 8160 for (auto &ENT : ExitNotTaken) 8161 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 8162 return ENT.MaxNotTaken; 8163 8164 return SE->getCouldNotCompute(); 8165 } 8166 8167 /// getConstantMax - Get the constant max backedge taken count for the loop. 8168 const SCEV * 8169 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 8170 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 8171 return !ENT.hasAlwaysTruePredicate(); 8172 }; 8173 8174 if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue)) 8175 return SE->getCouldNotCompute(); 8176 8177 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 8178 isa<SCEVConstant>(getConstantMax())) && 8179 "No point in having a non-constant max backedge taken count!"); 8180 return getConstantMax(); 8181 } 8182 8183 const SCEV * 8184 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 8185 ScalarEvolution *SE) { 8186 if (!SymbolicMax) 8187 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 8188 return SymbolicMax; 8189 } 8190 8191 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 8192 ScalarEvolution *SE) const { 8193 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 8194 return !ENT.hasAlwaysTruePredicate(); 8195 }; 8196 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 8197 } 8198 8199 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 8200 : ExitLimit(E, E, false, None) { 8201 } 8202 8203 ScalarEvolution::ExitLimit::ExitLimit( 8204 const SCEV *E, const SCEV *M, bool MaxOrZero, 8205 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 8206 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 8207 // If we prove the max count is zero, so is the symbolic bound. This happens 8208 // in practice due to differences in a) how context sensitive we've chosen 8209 // to be and b) how we reason about bounds impied by UB. 8210 if (MaxNotTaken->isZero()) 8211 ExactNotTaken = MaxNotTaken; 8212 8213 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 8214 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 8215 "Exact is not allowed to be less precise than Max"); 8216 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 8217 isa<SCEVConstant>(MaxNotTaken)) && 8218 "No point in having a non-constant max backedge taken count!"); 8219 for (auto *PredSet : PredSetList) 8220 for (auto *P : *PredSet) 8221 addPredicate(P); 8222 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) && 8223 "Backedge count should be int"); 8224 assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) && 8225 "Max backedge count should be int"); 8226 } 8227 8228 ScalarEvolution::ExitLimit::ExitLimit( 8229 const SCEV *E, const SCEV *M, bool MaxOrZero, 8230 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 8231 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 8232 } 8233 8234 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 8235 bool MaxOrZero) 8236 : ExitLimit(E, M, MaxOrZero, None) { 8237 } 8238 8239 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 8240 /// computable exit into a persistent ExitNotTakenInfo array. 8241 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 8242 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 8243 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 8244 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 8245 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 8246 8247 ExitNotTaken.reserve(ExitCounts.size()); 8248 std::transform( 8249 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 8250 [&](const EdgeExitInfo &EEI) { 8251 BasicBlock *ExitBB = EEI.first; 8252 const ExitLimit &EL = EEI.second; 8253 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 8254 EL.Predicates); 8255 }); 8256 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 8257 isa<SCEVConstant>(ConstantMax)) && 8258 "No point in having a non-constant max backedge taken count!"); 8259 } 8260 8261 /// Compute the number of times the backedge of the specified loop will execute. 8262 ScalarEvolution::BackedgeTakenInfo 8263 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 8264 bool AllowPredicates) { 8265 SmallVector<BasicBlock *, 8> ExitingBlocks; 8266 L->getExitingBlocks(ExitingBlocks); 8267 8268 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 8269 8270 SmallVector<EdgeExitInfo, 4> ExitCounts; 8271 bool CouldComputeBECount = true; 8272 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 8273 const SCEV *MustExitMaxBECount = nullptr; 8274 const SCEV *MayExitMaxBECount = nullptr; 8275 bool MustExitMaxOrZero = false; 8276 8277 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 8278 // and compute maxBECount. 8279 // Do a union of all the predicates here. 8280 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 8281 BasicBlock *ExitBB = ExitingBlocks[i]; 8282 8283 // We canonicalize untaken exits to br (constant), ignore them so that 8284 // proving an exit untaken doesn't negatively impact our ability to reason 8285 // about the loop as whole. 8286 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 8287 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 8288 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 8289 if (ExitIfTrue == CI->isZero()) 8290 continue; 8291 } 8292 8293 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 8294 8295 assert((AllowPredicates || EL.Predicates.empty()) && 8296 "Predicated exit limit when predicates are not allowed!"); 8297 8298 // 1. For each exit that can be computed, add an entry to ExitCounts. 8299 // CouldComputeBECount is true only if all exits can be computed. 8300 if (EL.ExactNotTaken == getCouldNotCompute()) 8301 // We couldn't compute an exact value for this exit, so 8302 // we won't be able to compute an exact value for the loop. 8303 CouldComputeBECount = false; 8304 else 8305 ExitCounts.emplace_back(ExitBB, EL); 8306 8307 // 2. Derive the loop's MaxBECount from each exit's max number of 8308 // non-exiting iterations. Partition the loop exits into two kinds: 8309 // LoopMustExits and LoopMayExits. 8310 // 8311 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 8312 // is a LoopMayExit. If any computable LoopMustExit is found, then 8313 // MaxBECount is the minimum EL.MaxNotTaken of computable 8314 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 8315 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 8316 // computable EL.MaxNotTaken. 8317 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 8318 DT.dominates(ExitBB, Latch)) { 8319 if (!MustExitMaxBECount) { 8320 MustExitMaxBECount = EL.MaxNotTaken; 8321 MustExitMaxOrZero = EL.MaxOrZero; 8322 } else { 8323 MustExitMaxBECount = 8324 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 8325 } 8326 } else if (MayExitMaxBECount != getCouldNotCompute()) { 8327 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 8328 MayExitMaxBECount = EL.MaxNotTaken; 8329 else { 8330 MayExitMaxBECount = 8331 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 8332 } 8333 } 8334 } 8335 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 8336 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 8337 // The loop backedge will be taken the maximum or zero times if there's 8338 // a single exit that must be taken the maximum or zero times. 8339 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 8340 8341 // Remember which SCEVs are used in exit limits for invalidation purposes. 8342 // We only care about non-constant SCEVs here, so we can ignore EL.MaxNotTaken 8343 // and MaxBECount, which must be SCEVConstant. 8344 for (const auto &Pair : ExitCounts) 8345 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken)) 8346 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates}); 8347 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 8348 MaxBECount, MaxOrZero); 8349 } 8350 8351 ScalarEvolution::ExitLimit 8352 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 8353 bool AllowPredicates) { 8354 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 8355 // If our exiting block does not dominate the latch, then its connection with 8356 // loop's exit limit may be far from trivial. 8357 const BasicBlock *Latch = L->getLoopLatch(); 8358 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 8359 return getCouldNotCompute(); 8360 8361 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 8362 Instruction *Term = ExitingBlock->getTerminator(); 8363 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 8364 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 8365 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 8366 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 8367 "It should have one successor in loop and one exit block!"); 8368 // Proceed to the next level to examine the exit condition expression. 8369 return computeExitLimitFromCond( 8370 L, BI->getCondition(), ExitIfTrue, 8371 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 8372 } 8373 8374 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 8375 // For switch, make sure that there is a single exit from the loop. 8376 BasicBlock *Exit = nullptr; 8377 for (auto *SBB : successors(ExitingBlock)) 8378 if (!L->contains(SBB)) { 8379 if (Exit) // Multiple exit successors. 8380 return getCouldNotCompute(); 8381 Exit = SBB; 8382 } 8383 assert(Exit && "Exiting block must have at least one exit"); 8384 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 8385 /*ControlsExit=*/IsOnlyExit); 8386 } 8387 8388 return getCouldNotCompute(); 8389 } 8390 8391 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 8392 const Loop *L, Value *ExitCond, bool ExitIfTrue, 8393 bool ControlsExit, bool AllowPredicates) { 8394 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 8395 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 8396 ControlsExit, AllowPredicates); 8397 } 8398 8399 Optional<ScalarEvolution::ExitLimit> 8400 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 8401 bool ExitIfTrue, bool ControlsExit, 8402 bool AllowPredicates) { 8403 (void)this->L; 8404 (void)this->ExitIfTrue; 8405 (void)this->AllowPredicates; 8406 8407 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 8408 this->AllowPredicates == AllowPredicates && 8409 "Variance in assumed invariant key components!"); 8410 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 8411 if (Itr == TripCountMap.end()) 8412 return None; 8413 return Itr->second; 8414 } 8415 8416 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 8417 bool ExitIfTrue, 8418 bool ControlsExit, 8419 bool AllowPredicates, 8420 const ExitLimit &EL) { 8421 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 8422 this->AllowPredicates == AllowPredicates && 8423 "Variance in assumed invariant key components!"); 8424 8425 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 8426 assert(InsertResult.second && "Expected successful insertion!"); 8427 (void)InsertResult; 8428 (void)ExitIfTrue; 8429 } 8430 8431 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 8432 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8433 bool ControlsExit, bool AllowPredicates) { 8434 8435 if (auto MaybeEL = 8436 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 8437 return *MaybeEL; 8438 8439 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 8440 ControlsExit, AllowPredicates); 8441 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 8442 return EL; 8443 } 8444 8445 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 8446 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8447 bool ControlsExit, bool AllowPredicates) { 8448 // Handle BinOp conditions (And, Or). 8449 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 8450 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 8451 return *LimitFromBinOp; 8452 8453 // With an icmp, it may be feasible to compute an exact backedge-taken count. 8454 // Proceed to the next level to examine the icmp. 8455 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 8456 ExitLimit EL = 8457 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 8458 if (EL.hasFullInfo() || !AllowPredicates) 8459 return EL; 8460 8461 // Try again, but use SCEV predicates this time. 8462 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 8463 /*AllowPredicates=*/true); 8464 } 8465 8466 // Check for a constant condition. These are normally stripped out by 8467 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 8468 // preserve the CFG and is temporarily leaving constant conditions 8469 // in place. 8470 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 8471 if (ExitIfTrue == !CI->getZExtValue()) 8472 // The backedge is always taken. 8473 return getCouldNotCompute(); 8474 else 8475 // The backedge is never taken. 8476 return getZero(CI->getType()); 8477 } 8478 8479 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic 8480 // with a constant step, we can form an equivalent icmp predicate and figure 8481 // out how many iterations will be taken before we exit. 8482 const WithOverflowInst *WO; 8483 const APInt *C; 8484 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) && 8485 match(WO->getRHS(), m_APInt(C))) { 8486 ConstantRange NWR = 8487 ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C, 8488 WO->getNoWrapKind()); 8489 CmpInst::Predicate Pred; 8490 APInt NewRHSC, Offset; 8491 NWR.getEquivalentICmp(Pred, NewRHSC, Offset); 8492 if (!ExitIfTrue) 8493 Pred = ICmpInst::getInversePredicate(Pred); 8494 auto *LHS = getSCEV(WO->getLHS()); 8495 if (Offset != 0) 8496 LHS = getAddExpr(LHS, getConstant(Offset)); 8497 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC), 8498 ControlsExit, AllowPredicates); 8499 if (EL.hasAnyInfo()) return EL; 8500 } 8501 8502 // If it's not an integer or pointer comparison then compute it the hard way. 8503 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8504 } 8505 8506 Optional<ScalarEvolution::ExitLimit> 8507 ScalarEvolution::computeExitLimitFromCondFromBinOp( 8508 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8509 bool ControlsExit, bool AllowPredicates) { 8510 // Check if the controlling expression for this loop is an And or Or. 8511 Value *Op0, *Op1; 8512 bool IsAnd = false; 8513 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 8514 IsAnd = true; 8515 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 8516 IsAnd = false; 8517 else 8518 return None; 8519 8520 // EitherMayExit is true in these two cases: 8521 // br (and Op0 Op1), loop, exit 8522 // br (or Op0 Op1), exit, loop 8523 bool EitherMayExit = IsAnd ^ ExitIfTrue; 8524 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 8525 ControlsExit && !EitherMayExit, 8526 AllowPredicates); 8527 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 8528 ControlsExit && !EitherMayExit, 8529 AllowPredicates); 8530 8531 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 8532 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 8533 if (isa<ConstantInt>(Op1)) 8534 return Op1 == NeutralElement ? EL0 : EL1; 8535 if (isa<ConstantInt>(Op0)) 8536 return Op0 == NeutralElement ? EL1 : EL0; 8537 8538 const SCEV *BECount = getCouldNotCompute(); 8539 const SCEV *MaxBECount = getCouldNotCompute(); 8540 if (EitherMayExit) { 8541 // Both conditions must be same for the loop to continue executing. 8542 // Choose the less conservative count. 8543 if (EL0.ExactNotTaken != getCouldNotCompute() && 8544 EL1.ExactNotTaken != getCouldNotCompute()) { 8545 BECount = getUMinFromMismatchedTypes( 8546 EL0.ExactNotTaken, EL1.ExactNotTaken, 8547 /*Sequential=*/!isa<BinaryOperator>(ExitCond)); 8548 } 8549 if (EL0.MaxNotTaken == getCouldNotCompute()) 8550 MaxBECount = EL1.MaxNotTaken; 8551 else if (EL1.MaxNotTaken == getCouldNotCompute()) 8552 MaxBECount = EL0.MaxNotTaken; 8553 else 8554 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 8555 } else { 8556 // Both conditions must be same at the same time for the loop to exit. 8557 // For now, be conservative. 8558 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 8559 BECount = EL0.ExactNotTaken; 8560 } 8561 8562 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 8563 // to be more aggressive when computing BECount than when computing 8564 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 8565 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 8566 // to not. 8567 if (isa<SCEVCouldNotCompute>(MaxBECount) && 8568 !isa<SCEVCouldNotCompute>(BECount)) 8569 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 8570 8571 return ExitLimit(BECount, MaxBECount, false, 8572 { &EL0.Predicates, &EL1.Predicates }); 8573 } 8574 8575 ScalarEvolution::ExitLimit 8576 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8577 ICmpInst *ExitCond, 8578 bool ExitIfTrue, 8579 bool ControlsExit, 8580 bool AllowPredicates) { 8581 // If the condition was exit on true, convert the condition to exit on false 8582 ICmpInst::Predicate Pred; 8583 if (!ExitIfTrue) 8584 Pred = ExitCond->getPredicate(); 8585 else 8586 Pred = ExitCond->getInversePredicate(); 8587 const ICmpInst::Predicate OriginalPred = Pred; 8588 8589 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 8590 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 8591 8592 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsExit, 8593 AllowPredicates); 8594 if (EL.hasAnyInfo()) return EL; 8595 8596 auto *ExhaustiveCount = 8597 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8598 8599 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 8600 return ExhaustiveCount; 8601 8602 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 8603 ExitCond->getOperand(1), L, OriginalPred); 8604 } 8605 ScalarEvolution::ExitLimit 8606 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8607 ICmpInst::Predicate Pred, 8608 const SCEV *LHS, const SCEV *RHS, 8609 bool ControlsExit, 8610 bool AllowPredicates) { 8611 8612 // Try to evaluate any dependencies out of the loop. 8613 LHS = getSCEVAtScope(LHS, L); 8614 RHS = getSCEVAtScope(RHS, L); 8615 8616 // At this point, we would like to compute how many iterations of the 8617 // loop the predicate will return true for these inputs. 8618 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 8619 // If there is a loop-invariant, force it into the RHS. 8620 std::swap(LHS, RHS); 8621 Pred = ICmpInst::getSwappedPredicate(Pred); 8622 } 8623 8624 bool ControllingFiniteLoop = 8625 ControlsExit && loopHasNoAbnormalExits(L) && loopIsFiniteByAssumption(L); 8626 // Simplify the operands before analyzing them. 8627 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0, 8628 (EnableFiniteLoopControl ? ControllingFiniteLoop 8629 : false)); 8630 8631 // If we have a comparison of a chrec against a constant, try to use value 8632 // ranges to answer this query. 8633 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 8634 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 8635 if (AddRec->getLoop() == L) { 8636 // Form the constant range. 8637 ConstantRange CompRange = 8638 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 8639 8640 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 8641 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 8642 } 8643 8644 // If this loop must exit based on this condition (or execute undefined 8645 // behaviour), and we can prove the test sequence produced must repeat 8646 // the same values on self-wrap of the IV, then we can infer that IV 8647 // doesn't self wrap because if it did, we'd have an infinite (undefined) 8648 // loop. 8649 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) { 8650 // TODO: We can peel off any functions which are invertible *in L*. Loop 8651 // invariant terms are effectively constants for our purposes here. 8652 auto *InnerLHS = LHS; 8653 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) 8654 InnerLHS = ZExt->getOperand(); 8655 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) { 8656 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 8657 if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() && 8658 StrideC && StrideC->getAPInt().isPowerOf2()) { 8659 auto Flags = AR->getNoWrapFlags(); 8660 Flags = setFlags(Flags, SCEV::FlagNW); 8661 SmallVector<const SCEV*> Operands{AR->operands()}; 8662 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 8663 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 8664 } 8665 } 8666 } 8667 8668 switch (Pred) { 8669 case ICmpInst::ICMP_NE: { // while (X != Y) 8670 // Convert to: while (X-Y != 0) 8671 if (LHS->getType()->isPointerTy()) { 8672 LHS = getLosslessPtrToIntExpr(LHS); 8673 if (isa<SCEVCouldNotCompute>(LHS)) 8674 return LHS; 8675 } 8676 if (RHS->getType()->isPointerTy()) { 8677 RHS = getLosslessPtrToIntExpr(RHS); 8678 if (isa<SCEVCouldNotCompute>(RHS)) 8679 return RHS; 8680 } 8681 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 8682 AllowPredicates); 8683 if (EL.hasAnyInfo()) return EL; 8684 break; 8685 } 8686 case ICmpInst::ICMP_EQ: { // while (X == Y) 8687 // Convert to: while (X-Y == 0) 8688 if (LHS->getType()->isPointerTy()) { 8689 LHS = getLosslessPtrToIntExpr(LHS); 8690 if (isa<SCEVCouldNotCompute>(LHS)) 8691 return LHS; 8692 } 8693 if (RHS->getType()->isPointerTy()) { 8694 RHS = getLosslessPtrToIntExpr(RHS); 8695 if (isa<SCEVCouldNotCompute>(RHS)) 8696 return RHS; 8697 } 8698 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 8699 if (EL.hasAnyInfo()) return EL; 8700 break; 8701 } 8702 case ICmpInst::ICMP_SLT: 8703 case ICmpInst::ICMP_ULT: { // while (X < Y) 8704 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 8705 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 8706 AllowPredicates); 8707 if (EL.hasAnyInfo()) return EL; 8708 break; 8709 } 8710 case ICmpInst::ICMP_SGT: 8711 case ICmpInst::ICMP_UGT: { // while (X > Y) 8712 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 8713 ExitLimit EL = 8714 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 8715 AllowPredicates); 8716 if (EL.hasAnyInfo()) return EL; 8717 break; 8718 } 8719 default: 8720 break; 8721 } 8722 8723 return getCouldNotCompute(); 8724 } 8725 8726 ScalarEvolution::ExitLimit 8727 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 8728 SwitchInst *Switch, 8729 BasicBlock *ExitingBlock, 8730 bool ControlsExit) { 8731 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 8732 8733 // Give up if the exit is the default dest of a switch. 8734 if (Switch->getDefaultDest() == ExitingBlock) 8735 return getCouldNotCompute(); 8736 8737 assert(L->contains(Switch->getDefaultDest()) && 8738 "Default case must not exit the loop!"); 8739 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 8740 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 8741 8742 // while (X != Y) --> while (X-Y != 0) 8743 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 8744 if (EL.hasAnyInfo()) 8745 return EL; 8746 8747 return getCouldNotCompute(); 8748 } 8749 8750 static ConstantInt * 8751 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 8752 ScalarEvolution &SE) { 8753 const SCEV *InVal = SE.getConstant(C); 8754 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 8755 assert(isa<SCEVConstant>(Val) && 8756 "Evaluation of SCEV at constant didn't fold correctly?"); 8757 return cast<SCEVConstant>(Val)->getValue(); 8758 } 8759 8760 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8761 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8762 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8763 if (!RHS) 8764 return getCouldNotCompute(); 8765 8766 const BasicBlock *Latch = L->getLoopLatch(); 8767 if (!Latch) 8768 return getCouldNotCompute(); 8769 8770 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8771 if (!Predecessor) 8772 return getCouldNotCompute(); 8773 8774 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8775 // Return LHS in OutLHS and shift_opt in OutOpCode. 8776 auto MatchPositiveShift = 8777 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8778 8779 using namespace PatternMatch; 8780 8781 ConstantInt *ShiftAmt; 8782 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8783 OutOpCode = Instruction::LShr; 8784 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8785 OutOpCode = Instruction::AShr; 8786 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8787 OutOpCode = Instruction::Shl; 8788 else 8789 return false; 8790 8791 return ShiftAmt->getValue().isStrictlyPositive(); 8792 }; 8793 8794 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8795 // 8796 // loop: 8797 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8798 // %iv.shifted = lshr i32 %iv, <positive constant> 8799 // 8800 // Return true on a successful match. Return the corresponding PHI node (%iv 8801 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8802 auto MatchShiftRecurrence = 8803 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8804 Optional<Instruction::BinaryOps> PostShiftOpCode; 8805 8806 { 8807 Instruction::BinaryOps OpC; 8808 Value *V; 8809 8810 // If we encounter a shift instruction, "peel off" the shift operation, 8811 // and remember that we did so. Later when we inspect %iv's backedge 8812 // value, we will make sure that the backedge value uses the same 8813 // operation. 8814 // 8815 // Note: the peeled shift operation does not have to be the same 8816 // instruction as the one feeding into the PHI's backedge value. We only 8817 // really care about it being the same *kind* of shift instruction -- 8818 // that's all that is required for our later inferences to hold. 8819 if (MatchPositiveShift(LHS, V, OpC)) { 8820 PostShiftOpCode = OpC; 8821 LHS = V; 8822 } 8823 } 8824 8825 PNOut = dyn_cast<PHINode>(LHS); 8826 if (!PNOut || PNOut->getParent() != L->getHeader()) 8827 return false; 8828 8829 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8830 Value *OpLHS; 8831 8832 return 8833 // The backedge value for the PHI node must be a shift by a positive 8834 // amount 8835 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8836 8837 // of the PHI node itself 8838 OpLHS == PNOut && 8839 8840 // and the kind of shift should be match the kind of shift we peeled 8841 // off, if any. 8842 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8843 }; 8844 8845 PHINode *PN; 8846 Instruction::BinaryOps OpCode; 8847 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8848 return getCouldNotCompute(); 8849 8850 const DataLayout &DL = getDataLayout(); 8851 8852 // The key rationale for this optimization is that for some kinds of shift 8853 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8854 // within a finite number of iterations. If the condition guarding the 8855 // backedge (in the sense that the backedge is taken if the condition is true) 8856 // is false for the value the shift recurrence stabilizes to, then we know 8857 // that the backedge is taken only a finite number of times. 8858 8859 ConstantInt *StableValue = nullptr; 8860 switch (OpCode) { 8861 default: 8862 llvm_unreachable("Impossible case!"); 8863 8864 case Instruction::AShr: { 8865 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8866 // bitwidth(K) iterations. 8867 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8868 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8869 Predecessor->getTerminator(), &DT); 8870 auto *Ty = cast<IntegerType>(RHS->getType()); 8871 if (Known.isNonNegative()) 8872 StableValue = ConstantInt::get(Ty, 0); 8873 else if (Known.isNegative()) 8874 StableValue = ConstantInt::get(Ty, -1, true); 8875 else 8876 return getCouldNotCompute(); 8877 8878 break; 8879 } 8880 case Instruction::LShr: 8881 case Instruction::Shl: 8882 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8883 // stabilize to 0 in at most bitwidth(K) iterations. 8884 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8885 break; 8886 } 8887 8888 auto *Result = 8889 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8890 assert(Result->getType()->isIntegerTy(1) && 8891 "Otherwise cannot be an operand to a branch instruction"); 8892 8893 if (Result->isZeroValue()) { 8894 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8895 const SCEV *UpperBound = 8896 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8897 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8898 } 8899 8900 return getCouldNotCompute(); 8901 } 8902 8903 /// Return true if we can constant fold an instruction of the specified type, 8904 /// assuming that all operands were constants. 8905 static bool CanConstantFold(const Instruction *I) { 8906 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8907 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8908 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8909 return true; 8910 8911 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8912 if (const Function *F = CI->getCalledFunction()) 8913 return canConstantFoldCallTo(CI, F); 8914 return false; 8915 } 8916 8917 /// Determine whether this instruction can constant evolve within this loop 8918 /// assuming its operands can all constant evolve. 8919 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8920 // An instruction outside of the loop can't be derived from a loop PHI. 8921 if (!L->contains(I)) return false; 8922 8923 if (isa<PHINode>(I)) { 8924 // We don't currently keep track of the control flow needed to evaluate 8925 // PHIs, so we cannot handle PHIs inside of loops. 8926 return L->getHeader() == I->getParent(); 8927 } 8928 8929 // If we won't be able to constant fold this expression even if the operands 8930 // are constants, bail early. 8931 return CanConstantFold(I); 8932 } 8933 8934 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8935 /// recursing through each instruction operand until reaching a loop header phi. 8936 static PHINode * 8937 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8938 DenseMap<Instruction *, PHINode *> &PHIMap, 8939 unsigned Depth) { 8940 if (Depth > MaxConstantEvolvingDepth) 8941 return nullptr; 8942 8943 // Otherwise, we can evaluate this instruction if all of its operands are 8944 // constant or derived from a PHI node themselves. 8945 PHINode *PHI = nullptr; 8946 for (Value *Op : UseInst->operands()) { 8947 if (isa<Constant>(Op)) continue; 8948 8949 Instruction *OpInst = dyn_cast<Instruction>(Op); 8950 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8951 8952 PHINode *P = dyn_cast<PHINode>(OpInst); 8953 if (!P) 8954 // If this operand is already visited, reuse the prior result. 8955 // We may have P != PHI if this is the deepest point at which the 8956 // inconsistent paths meet. 8957 P = PHIMap.lookup(OpInst); 8958 if (!P) { 8959 // Recurse and memoize the results, whether a phi is found or not. 8960 // This recursive call invalidates pointers into PHIMap. 8961 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8962 PHIMap[OpInst] = P; 8963 } 8964 if (!P) 8965 return nullptr; // Not evolving from PHI 8966 if (PHI && PHI != P) 8967 return nullptr; // Evolving from multiple different PHIs. 8968 PHI = P; 8969 } 8970 // This is a expression evolving from a constant PHI! 8971 return PHI; 8972 } 8973 8974 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8975 /// in the loop that V is derived from. We allow arbitrary operations along the 8976 /// way, but the operands of an operation must either be constants or a value 8977 /// derived from a constant PHI. If this expression does not fit with these 8978 /// constraints, return null. 8979 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8980 Instruction *I = dyn_cast<Instruction>(V); 8981 if (!I || !canConstantEvolve(I, L)) return nullptr; 8982 8983 if (PHINode *PN = dyn_cast<PHINode>(I)) 8984 return PN; 8985 8986 // Record non-constant instructions contained by the loop. 8987 DenseMap<Instruction *, PHINode *> PHIMap; 8988 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8989 } 8990 8991 /// EvaluateExpression - Given an expression that passes the 8992 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8993 /// in the loop has the value PHIVal. If we can't fold this expression for some 8994 /// reason, return null. 8995 static Constant *EvaluateExpression(Value *V, const Loop *L, 8996 DenseMap<Instruction *, Constant *> &Vals, 8997 const DataLayout &DL, 8998 const TargetLibraryInfo *TLI) { 8999 // Convenient constant check, but redundant for recursive calls. 9000 if (Constant *C = dyn_cast<Constant>(V)) return C; 9001 Instruction *I = dyn_cast<Instruction>(V); 9002 if (!I) return nullptr; 9003 9004 if (Constant *C = Vals.lookup(I)) return C; 9005 9006 // An instruction inside the loop depends on a value outside the loop that we 9007 // weren't given a mapping for, or a value such as a call inside the loop. 9008 if (!canConstantEvolve(I, L)) return nullptr; 9009 9010 // An unmapped PHI can be due to a branch or another loop inside this loop, 9011 // or due to this not being the initial iteration through a loop where we 9012 // couldn't compute the evolution of this particular PHI last time. 9013 if (isa<PHINode>(I)) return nullptr; 9014 9015 std::vector<Constant*> Operands(I->getNumOperands()); 9016 9017 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 9018 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 9019 if (!Operand) { 9020 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 9021 if (!Operands[i]) return nullptr; 9022 continue; 9023 } 9024 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 9025 Vals[Operand] = C; 9026 if (!C) return nullptr; 9027 Operands[i] = C; 9028 } 9029 9030 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 9031 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 9032 Operands[1], DL, TLI); 9033 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 9034 if (!LI->isVolatile()) 9035 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 9036 } 9037 return ConstantFoldInstOperands(I, Operands, DL, TLI); 9038 } 9039 9040 9041 // If every incoming value to PN except the one for BB is a specific Constant, 9042 // return that, else return nullptr. 9043 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 9044 Constant *IncomingVal = nullptr; 9045 9046 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 9047 if (PN->getIncomingBlock(i) == BB) 9048 continue; 9049 9050 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 9051 if (!CurrentVal) 9052 return nullptr; 9053 9054 if (IncomingVal != CurrentVal) { 9055 if (IncomingVal) 9056 return nullptr; 9057 IncomingVal = CurrentVal; 9058 } 9059 } 9060 9061 return IncomingVal; 9062 } 9063 9064 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 9065 /// in the header of its containing loop, we know the loop executes a 9066 /// constant number of times, and the PHI node is just a recurrence 9067 /// involving constants, fold it. 9068 Constant * 9069 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 9070 const APInt &BEs, 9071 const Loop *L) { 9072 auto I = ConstantEvolutionLoopExitValue.find(PN); 9073 if (I != ConstantEvolutionLoopExitValue.end()) 9074 return I->second; 9075 9076 if (BEs.ugt(MaxBruteForceIterations)) 9077 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 9078 9079 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 9080 9081 DenseMap<Instruction *, Constant *> CurrentIterVals; 9082 BasicBlock *Header = L->getHeader(); 9083 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 9084 9085 BasicBlock *Latch = L->getLoopLatch(); 9086 if (!Latch) 9087 return nullptr; 9088 9089 for (PHINode &PHI : Header->phis()) { 9090 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 9091 CurrentIterVals[&PHI] = StartCST; 9092 } 9093 if (!CurrentIterVals.count(PN)) 9094 return RetVal = nullptr; 9095 9096 Value *BEValue = PN->getIncomingValueForBlock(Latch); 9097 9098 // Execute the loop symbolically to determine the exit value. 9099 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 9100 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 9101 9102 unsigned NumIterations = BEs.getZExtValue(); // must be in range 9103 unsigned IterationNum = 0; 9104 const DataLayout &DL = getDataLayout(); 9105 for (; ; ++IterationNum) { 9106 if (IterationNum == NumIterations) 9107 return RetVal = CurrentIterVals[PN]; // Got exit value! 9108 9109 // Compute the value of the PHIs for the next iteration. 9110 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 9111 DenseMap<Instruction *, Constant *> NextIterVals; 9112 Constant *NextPHI = 9113 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 9114 if (!NextPHI) 9115 return nullptr; // Couldn't evaluate! 9116 NextIterVals[PN] = NextPHI; 9117 9118 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 9119 9120 // Also evaluate the other PHI nodes. However, we don't get to stop if we 9121 // cease to be able to evaluate one of them or if they stop evolving, 9122 // because that doesn't necessarily prevent us from computing PN. 9123 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 9124 for (const auto &I : CurrentIterVals) { 9125 PHINode *PHI = dyn_cast<PHINode>(I.first); 9126 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 9127 PHIsToCompute.emplace_back(PHI, I.second); 9128 } 9129 // We use two distinct loops because EvaluateExpression may invalidate any 9130 // iterators into CurrentIterVals. 9131 for (const auto &I : PHIsToCompute) { 9132 PHINode *PHI = I.first; 9133 Constant *&NextPHI = NextIterVals[PHI]; 9134 if (!NextPHI) { // Not already computed. 9135 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 9136 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 9137 } 9138 if (NextPHI != I.second) 9139 StoppedEvolving = false; 9140 } 9141 9142 // If all entries in CurrentIterVals == NextIterVals then we can stop 9143 // iterating, the loop can't continue to change. 9144 if (StoppedEvolving) 9145 return RetVal = CurrentIterVals[PN]; 9146 9147 CurrentIterVals.swap(NextIterVals); 9148 } 9149 } 9150 9151 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 9152 Value *Cond, 9153 bool ExitWhen) { 9154 PHINode *PN = getConstantEvolvingPHI(Cond, L); 9155 if (!PN) return getCouldNotCompute(); 9156 9157 // If the loop is canonicalized, the PHI will have exactly two entries. 9158 // That's the only form we support here. 9159 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 9160 9161 DenseMap<Instruction *, Constant *> CurrentIterVals; 9162 BasicBlock *Header = L->getHeader(); 9163 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 9164 9165 BasicBlock *Latch = L->getLoopLatch(); 9166 assert(Latch && "Should follow from NumIncomingValues == 2!"); 9167 9168 for (PHINode &PHI : Header->phis()) { 9169 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 9170 CurrentIterVals[&PHI] = StartCST; 9171 } 9172 if (!CurrentIterVals.count(PN)) 9173 return getCouldNotCompute(); 9174 9175 // Okay, we find a PHI node that defines the trip count of this loop. Execute 9176 // the loop symbolically to determine when the condition gets a value of 9177 // "ExitWhen". 9178 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 9179 const DataLayout &DL = getDataLayout(); 9180 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 9181 auto *CondVal = dyn_cast_or_null<ConstantInt>( 9182 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 9183 9184 // Couldn't symbolically evaluate. 9185 if (!CondVal) return getCouldNotCompute(); 9186 9187 if (CondVal->getValue() == uint64_t(ExitWhen)) { 9188 ++NumBruteForceTripCountsComputed; 9189 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 9190 } 9191 9192 // Update all the PHI nodes for the next iteration. 9193 DenseMap<Instruction *, Constant *> NextIterVals; 9194 9195 // Create a list of which PHIs we need to compute. We want to do this before 9196 // calling EvaluateExpression on them because that may invalidate iterators 9197 // into CurrentIterVals. 9198 SmallVector<PHINode *, 8> PHIsToCompute; 9199 for (const auto &I : CurrentIterVals) { 9200 PHINode *PHI = dyn_cast<PHINode>(I.first); 9201 if (!PHI || PHI->getParent() != Header) continue; 9202 PHIsToCompute.push_back(PHI); 9203 } 9204 for (PHINode *PHI : PHIsToCompute) { 9205 Constant *&NextPHI = NextIterVals[PHI]; 9206 if (NextPHI) continue; // Already computed! 9207 9208 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 9209 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 9210 } 9211 CurrentIterVals.swap(NextIterVals); 9212 } 9213 9214 // Too many iterations were needed to evaluate. 9215 return getCouldNotCompute(); 9216 } 9217 9218 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 9219 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 9220 ValuesAtScopes[V]; 9221 // Check to see if we've folded this expression at this loop before. 9222 for (auto &LS : Values) 9223 if (LS.first == L) 9224 return LS.second ? LS.second : V; 9225 9226 Values.emplace_back(L, nullptr); 9227 9228 // Otherwise compute it. 9229 const SCEV *C = computeSCEVAtScope(V, L); 9230 for (auto &LS : reverse(ValuesAtScopes[V])) 9231 if (LS.first == L) { 9232 LS.second = C; 9233 if (!isa<SCEVConstant>(C)) 9234 ValuesAtScopesUsers[C].push_back({L, V}); 9235 break; 9236 } 9237 return C; 9238 } 9239 9240 /// This builds up a Constant using the ConstantExpr interface. That way, we 9241 /// will return Constants for objects which aren't represented by a 9242 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 9243 /// Returns NULL if the SCEV isn't representable as a Constant. 9244 static Constant *BuildConstantFromSCEV(const SCEV *V) { 9245 switch (V->getSCEVType()) { 9246 case scCouldNotCompute: 9247 case scAddRecExpr: 9248 return nullptr; 9249 case scConstant: 9250 return cast<SCEVConstant>(V)->getValue(); 9251 case scUnknown: 9252 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 9253 case scSignExtend: { 9254 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 9255 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 9256 return ConstantExpr::getSExt(CastOp, SS->getType()); 9257 return nullptr; 9258 } 9259 case scZeroExtend: { 9260 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 9261 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 9262 return ConstantExpr::getZExt(CastOp, SZ->getType()); 9263 return nullptr; 9264 } 9265 case scPtrToInt: { 9266 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 9267 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 9268 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 9269 9270 return nullptr; 9271 } 9272 case scTruncate: { 9273 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 9274 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 9275 return ConstantExpr::getTrunc(CastOp, ST->getType()); 9276 return nullptr; 9277 } 9278 case scAddExpr: { 9279 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 9280 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 9281 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 9282 unsigned AS = PTy->getAddressSpace(); 9283 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 9284 C = ConstantExpr::getBitCast(C, DestPtrTy); 9285 } 9286 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 9287 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 9288 if (!C2) 9289 return nullptr; 9290 9291 // First pointer! 9292 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 9293 unsigned AS = C2->getType()->getPointerAddressSpace(); 9294 std::swap(C, C2); 9295 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 9296 // The offsets have been converted to bytes. We can add bytes to an 9297 // i8* by GEP with the byte count in the first index. 9298 C = ConstantExpr::getBitCast(C, DestPtrTy); 9299 } 9300 9301 // Don't bother trying to sum two pointers. We probably can't 9302 // statically compute a load that results from it anyway. 9303 if (C2->getType()->isPointerTy()) 9304 return nullptr; 9305 9306 if (C->getType()->isPointerTy()) { 9307 C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()), 9308 C, C2); 9309 } else { 9310 C = ConstantExpr::getAdd(C, C2); 9311 } 9312 } 9313 return C; 9314 } 9315 return nullptr; 9316 } 9317 case scMulExpr: { 9318 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 9319 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 9320 // Don't bother with pointers at all. 9321 if (C->getType()->isPointerTy()) 9322 return nullptr; 9323 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 9324 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 9325 if (!C2 || C2->getType()->isPointerTy()) 9326 return nullptr; 9327 C = ConstantExpr::getMul(C, C2); 9328 } 9329 return C; 9330 } 9331 return nullptr; 9332 } 9333 case scUDivExpr: { 9334 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 9335 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 9336 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 9337 if (LHS->getType() == RHS->getType()) 9338 return ConstantExpr::getUDiv(LHS, RHS); 9339 return nullptr; 9340 } 9341 case scSMaxExpr: 9342 case scUMaxExpr: 9343 case scSMinExpr: 9344 case scUMinExpr: 9345 case scSequentialUMinExpr: 9346 return nullptr; // TODO: smax, umax, smin, umax, umin_seq. 9347 } 9348 llvm_unreachable("Unknown SCEV kind!"); 9349 } 9350 9351 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 9352 if (isa<SCEVConstant>(V)) return V; 9353 9354 // If this instruction is evolved from a constant-evolving PHI, compute the 9355 // exit value from the loop without using SCEVs. 9356 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 9357 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 9358 if (PHINode *PN = dyn_cast<PHINode>(I)) { 9359 const Loop *CurrLoop = this->LI[I->getParent()]; 9360 // Looking for loop exit value. 9361 if (CurrLoop && CurrLoop->getParentLoop() == L && 9362 PN->getParent() == CurrLoop->getHeader()) { 9363 // Okay, there is no closed form solution for the PHI node. Check 9364 // to see if the loop that contains it has a known backedge-taken 9365 // count. If so, we may be able to force computation of the exit 9366 // value. 9367 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 9368 // This trivial case can show up in some degenerate cases where 9369 // the incoming IR has not yet been fully simplified. 9370 if (BackedgeTakenCount->isZero()) { 9371 Value *InitValue = nullptr; 9372 bool MultipleInitValues = false; 9373 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 9374 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 9375 if (!InitValue) 9376 InitValue = PN->getIncomingValue(i); 9377 else if (InitValue != PN->getIncomingValue(i)) { 9378 MultipleInitValues = true; 9379 break; 9380 } 9381 } 9382 } 9383 if (!MultipleInitValues && InitValue) 9384 return getSCEV(InitValue); 9385 } 9386 // Do we have a loop invariant value flowing around the backedge 9387 // for a loop which must execute the backedge? 9388 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 9389 isKnownPositive(BackedgeTakenCount) && 9390 PN->getNumIncomingValues() == 2) { 9391 9392 unsigned InLoopPred = 9393 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 9394 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 9395 if (CurrLoop->isLoopInvariant(BackedgeVal)) 9396 return getSCEV(BackedgeVal); 9397 } 9398 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 9399 // Okay, we know how many times the containing loop executes. If 9400 // this is a constant evolving PHI node, get the final value at 9401 // the specified iteration number. 9402 Constant *RV = getConstantEvolutionLoopExitValue( 9403 PN, BTCC->getAPInt(), CurrLoop); 9404 if (RV) return getSCEV(RV); 9405 } 9406 } 9407 9408 // If there is a single-input Phi, evaluate it at our scope. If we can 9409 // prove that this replacement does not break LCSSA form, use new value. 9410 if (PN->getNumOperands() == 1) { 9411 const SCEV *Input = getSCEV(PN->getOperand(0)); 9412 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 9413 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 9414 // for the simplest case just support constants. 9415 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 9416 } 9417 } 9418 9419 // Okay, this is an expression that we cannot symbolically evaluate 9420 // into a SCEV. Check to see if it's possible to symbolically evaluate 9421 // the arguments into constants, and if so, try to constant propagate the 9422 // result. This is particularly useful for computing loop exit values. 9423 if (CanConstantFold(I)) { 9424 SmallVector<Constant *, 4> Operands; 9425 bool MadeImprovement = false; 9426 for (Value *Op : I->operands()) { 9427 if (Constant *C = dyn_cast<Constant>(Op)) { 9428 Operands.push_back(C); 9429 continue; 9430 } 9431 9432 // If any of the operands is non-constant and if they are 9433 // non-integer and non-pointer, don't even try to analyze them 9434 // with scev techniques. 9435 if (!isSCEVable(Op->getType())) 9436 return V; 9437 9438 const SCEV *OrigV = getSCEV(Op); 9439 const SCEV *OpV = getSCEVAtScope(OrigV, L); 9440 MadeImprovement |= OrigV != OpV; 9441 9442 Constant *C = BuildConstantFromSCEV(OpV); 9443 if (!C) return V; 9444 if (C->getType() != Op->getType()) 9445 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 9446 Op->getType(), 9447 false), 9448 C, Op->getType()); 9449 Operands.push_back(C); 9450 } 9451 9452 // Check to see if getSCEVAtScope actually made an improvement. 9453 if (MadeImprovement) { 9454 Constant *C = nullptr; 9455 const DataLayout &DL = getDataLayout(); 9456 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 9457 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 9458 Operands[1], DL, &TLI); 9459 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 9460 if (!Load->isVolatile()) 9461 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 9462 DL); 9463 } else 9464 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 9465 if (!C) return V; 9466 return getSCEV(C); 9467 } 9468 } 9469 } 9470 9471 // This is some other type of SCEVUnknown, just return it. 9472 return V; 9473 } 9474 9475 if (isa<SCEVCommutativeExpr>(V) || isa<SCEVSequentialMinMaxExpr>(V)) { 9476 const auto *Comm = cast<SCEVNAryExpr>(V); 9477 // Avoid performing the look-up in the common case where the specified 9478 // expression has no loop-variant portions. 9479 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 9480 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 9481 if (OpAtScope != Comm->getOperand(i)) { 9482 // Okay, at least one of these operands is loop variant but might be 9483 // foldable. Build a new instance of the folded commutative expression. 9484 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 9485 Comm->op_begin()+i); 9486 NewOps.push_back(OpAtScope); 9487 9488 for (++i; i != e; ++i) { 9489 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 9490 NewOps.push_back(OpAtScope); 9491 } 9492 if (isa<SCEVAddExpr>(Comm)) 9493 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 9494 if (isa<SCEVMulExpr>(Comm)) 9495 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 9496 if (isa<SCEVMinMaxExpr>(Comm)) 9497 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 9498 if (isa<SCEVSequentialMinMaxExpr>(Comm)) 9499 return getSequentialMinMaxExpr(Comm->getSCEVType(), NewOps); 9500 llvm_unreachable("Unknown commutative / sequential min/max SCEV type!"); 9501 } 9502 } 9503 // If we got here, all operands are loop invariant. 9504 return Comm; 9505 } 9506 9507 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 9508 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 9509 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 9510 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 9511 return Div; // must be loop invariant 9512 return getUDivExpr(LHS, RHS); 9513 } 9514 9515 // If this is a loop recurrence for a loop that does not contain L, then we 9516 // are dealing with the final value computed by the loop. 9517 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 9518 // First, attempt to evaluate each operand. 9519 // Avoid performing the look-up in the common case where the specified 9520 // expression has no loop-variant portions. 9521 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 9522 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 9523 if (OpAtScope == AddRec->getOperand(i)) 9524 continue; 9525 9526 // Okay, at least one of these operands is loop variant but might be 9527 // foldable. Build a new instance of the folded commutative expression. 9528 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 9529 AddRec->op_begin()+i); 9530 NewOps.push_back(OpAtScope); 9531 for (++i; i != e; ++i) 9532 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 9533 9534 const SCEV *FoldedRec = 9535 getAddRecExpr(NewOps, AddRec->getLoop(), 9536 AddRec->getNoWrapFlags(SCEV::FlagNW)); 9537 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 9538 // The addrec may be folded to a nonrecurrence, for example, if the 9539 // induction variable is multiplied by zero after constant folding. Go 9540 // ahead and return the folded value. 9541 if (!AddRec) 9542 return FoldedRec; 9543 break; 9544 } 9545 9546 // If the scope is outside the addrec's loop, evaluate it by using the 9547 // loop exit value of the addrec. 9548 if (!AddRec->getLoop()->contains(L)) { 9549 // To evaluate this recurrence, we need to know how many times the AddRec 9550 // loop iterates. Compute this now. 9551 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 9552 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 9553 9554 // Then, evaluate the AddRec. 9555 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 9556 } 9557 9558 return AddRec; 9559 } 9560 9561 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 9562 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9563 if (Op == Cast->getOperand()) 9564 return Cast; // must be loop invariant 9565 return getCastExpr(Cast->getSCEVType(), Op, Cast->getType()); 9566 } 9567 9568 llvm_unreachable("Unknown SCEV type!"); 9569 } 9570 9571 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 9572 return getSCEVAtScope(getSCEV(V), L); 9573 } 9574 9575 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 9576 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 9577 return stripInjectiveFunctions(ZExt->getOperand()); 9578 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 9579 return stripInjectiveFunctions(SExt->getOperand()); 9580 return S; 9581 } 9582 9583 /// Finds the minimum unsigned root of the following equation: 9584 /// 9585 /// A * X = B (mod N) 9586 /// 9587 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 9588 /// A and B isn't important. 9589 /// 9590 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 9591 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 9592 ScalarEvolution &SE) { 9593 uint32_t BW = A.getBitWidth(); 9594 assert(BW == SE.getTypeSizeInBits(B->getType())); 9595 assert(A != 0 && "A must be non-zero."); 9596 9597 // 1. D = gcd(A, N) 9598 // 9599 // The gcd of A and N may have only one prime factor: 2. The number of 9600 // trailing zeros in A is its multiplicity 9601 uint32_t Mult2 = A.countTrailingZeros(); 9602 // D = 2^Mult2 9603 9604 // 2. Check if B is divisible by D. 9605 // 9606 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 9607 // is not less than multiplicity of this prime factor for D. 9608 if (SE.GetMinTrailingZeros(B) < Mult2) 9609 return SE.getCouldNotCompute(); 9610 9611 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 9612 // modulo (N / D). 9613 // 9614 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 9615 // (N / D) in general. The inverse itself always fits into BW bits, though, 9616 // so we immediately truncate it. 9617 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 9618 APInt Mod(BW + 1, 0); 9619 Mod.setBit(BW - Mult2); // Mod = N / D 9620 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 9621 9622 // 4. Compute the minimum unsigned root of the equation: 9623 // I * (B / D) mod (N / D) 9624 // To simplify the computation, we factor out the divide by D: 9625 // (I * B mod N) / D 9626 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 9627 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 9628 } 9629 9630 /// For a given quadratic addrec, generate coefficients of the corresponding 9631 /// quadratic equation, multiplied by a common value to ensure that they are 9632 /// integers. 9633 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 9634 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 9635 /// were multiplied by, and BitWidth is the bit width of the original addrec 9636 /// coefficients. 9637 /// This function returns None if the addrec coefficients are not compile- 9638 /// time constants. 9639 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 9640 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 9641 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 9642 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 9643 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 9644 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 9645 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 9646 << *AddRec << '\n'); 9647 9648 // We currently can only solve this if the coefficients are constants. 9649 if (!LC || !MC || !NC) { 9650 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 9651 return None; 9652 } 9653 9654 APInt L = LC->getAPInt(); 9655 APInt M = MC->getAPInt(); 9656 APInt N = NC->getAPInt(); 9657 assert(!N.isZero() && "This is not a quadratic addrec"); 9658 9659 unsigned BitWidth = LC->getAPInt().getBitWidth(); 9660 unsigned NewWidth = BitWidth + 1; 9661 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 9662 << BitWidth << '\n'); 9663 // The sign-extension (as opposed to a zero-extension) here matches the 9664 // extension used in SolveQuadraticEquationWrap (with the same motivation). 9665 N = N.sext(NewWidth); 9666 M = M.sext(NewWidth); 9667 L = L.sext(NewWidth); 9668 9669 // The increments are M, M+N, M+2N, ..., so the accumulated values are 9670 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 9671 // L+M, L+2M+N, L+3M+3N, ... 9672 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 9673 // 9674 // The equation Acc = 0 is then 9675 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 9676 // In a quadratic form it becomes: 9677 // N n^2 + (2M-N) n + 2L = 0. 9678 9679 APInt A = N; 9680 APInt B = 2 * M - A; 9681 APInt C = 2 * L; 9682 APInt T = APInt(NewWidth, 2); 9683 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 9684 << "x + " << C << ", coeff bw: " << NewWidth 9685 << ", multiplied by " << T << '\n'); 9686 return std::make_tuple(A, B, C, T, BitWidth); 9687 } 9688 9689 /// Helper function to compare optional APInts: 9690 /// (a) if X and Y both exist, return min(X, Y), 9691 /// (b) if neither X nor Y exist, return None, 9692 /// (c) if exactly one of X and Y exists, return that value. 9693 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 9694 if (X.hasValue() && Y.hasValue()) { 9695 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 9696 APInt XW = X->sextOrSelf(W); 9697 APInt YW = Y->sextOrSelf(W); 9698 return XW.slt(YW) ? *X : *Y; 9699 } 9700 if (!X.hasValue() && !Y.hasValue()) 9701 return None; 9702 return X.hasValue() ? *X : *Y; 9703 } 9704 9705 /// Helper function to truncate an optional APInt to a given BitWidth. 9706 /// When solving addrec-related equations, it is preferable to return a value 9707 /// that has the same bit width as the original addrec's coefficients. If the 9708 /// solution fits in the original bit width, truncate it (except for i1). 9709 /// Returning a value of a different bit width may inhibit some optimizations. 9710 /// 9711 /// In general, a solution to a quadratic equation generated from an addrec 9712 /// may require BW+1 bits, where BW is the bit width of the addrec's 9713 /// coefficients. The reason is that the coefficients of the quadratic 9714 /// equation are BW+1 bits wide (to avoid truncation when converting from 9715 /// the addrec to the equation). 9716 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 9717 if (!X.hasValue()) 9718 return None; 9719 unsigned W = X->getBitWidth(); 9720 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9721 return X->trunc(BitWidth); 9722 return X; 9723 } 9724 9725 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9726 /// iterations. The values L, M, N are assumed to be signed, and they 9727 /// should all have the same bit widths. 9728 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9729 /// where BW is the bit width of the addrec's coefficients. 9730 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9731 /// returned as such, otherwise the bit width of the returned value may 9732 /// be greater than BW. 9733 /// 9734 /// This function returns None if 9735 /// (a) the addrec coefficients are not constant, or 9736 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9737 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9738 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9739 static Optional<APInt> 9740 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9741 APInt A, B, C, M; 9742 unsigned BitWidth; 9743 auto T = GetQuadraticEquation(AddRec); 9744 if (!T.hasValue()) 9745 return None; 9746 9747 std::tie(A, B, C, M, BitWidth) = *T; 9748 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9749 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9750 if (!X.hasValue()) 9751 return None; 9752 9753 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9754 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9755 if (!V->isZero()) 9756 return None; 9757 9758 return TruncIfPossible(X, BitWidth); 9759 } 9760 9761 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9762 /// iterations. The values M, N are assumed to be signed, and they 9763 /// should all have the same bit widths. 9764 /// Find the least n such that c(n) does not belong to the given range, 9765 /// while c(n-1) does. 9766 /// 9767 /// This function returns None if 9768 /// (a) the addrec coefficients are not constant, or 9769 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9770 /// bounds of the range. 9771 static Optional<APInt> 9772 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9773 const ConstantRange &Range, ScalarEvolution &SE) { 9774 assert(AddRec->getOperand(0)->isZero() && 9775 "Starting value of addrec should be 0"); 9776 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9777 << Range << ", addrec " << *AddRec << '\n'); 9778 // This case is handled in getNumIterationsInRange. Here we can assume that 9779 // we start in the range. 9780 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9781 "Addrec's initial value should be in range"); 9782 9783 APInt A, B, C, M; 9784 unsigned BitWidth; 9785 auto T = GetQuadraticEquation(AddRec); 9786 if (!T.hasValue()) 9787 return None; 9788 9789 // Be careful about the return value: there can be two reasons for not 9790 // returning an actual number. First, if no solutions to the equations 9791 // were found, and second, if the solutions don't leave the given range. 9792 // The first case means that the actual solution is "unknown", the second 9793 // means that it's known, but not valid. If the solution is unknown, we 9794 // cannot make any conclusions. 9795 // Return a pair: the optional solution and a flag indicating if the 9796 // solution was found. 9797 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9798 // Solve for signed overflow and unsigned overflow, pick the lower 9799 // solution. 9800 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9801 << Bound << " (before multiplying by " << M << ")\n"); 9802 Bound *= M; // The quadratic equation multiplier. 9803 9804 Optional<APInt> SO = None; 9805 if (BitWidth > 1) { 9806 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9807 "signed overflow\n"); 9808 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9809 } 9810 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9811 "unsigned overflow\n"); 9812 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9813 BitWidth+1); 9814 9815 auto LeavesRange = [&] (const APInt &X) { 9816 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9817 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9818 if (Range.contains(V0->getValue())) 9819 return false; 9820 // X should be at least 1, so X-1 is non-negative. 9821 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9822 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9823 if (Range.contains(V1->getValue())) 9824 return true; 9825 return false; 9826 }; 9827 9828 // If SolveQuadraticEquationWrap returns None, it means that there can 9829 // be a solution, but the function failed to find it. We cannot treat it 9830 // as "no solution". 9831 if (!SO.hasValue() || !UO.hasValue()) 9832 return { None, false }; 9833 9834 // Check the smaller value first to see if it leaves the range. 9835 // At this point, both SO and UO must have values. 9836 Optional<APInt> Min = MinOptional(SO, UO); 9837 if (LeavesRange(*Min)) 9838 return { Min, true }; 9839 Optional<APInt> Max = Min == SO ? UO : SO; 9840 if (LeavesRange(*Max)) 9841 return { Max, true }; 9842 9843 // Solutions were found, but were eliminated, hence the "true". 9844 return { None, true }; 9845 }; 9846 9847 std::tie(A, B, C, M, BitWidth) = *T; 9848 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9849 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9850 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9851 auto SL = SolveForBoundary(Lower); 9852 auto SU = SolveForBoundary(Upper); 9853 // If any of the solutions was unknown, no meaninigful conclusions can 9854 // be made. 9855 if (!SL.second || !SU.second) 9856 return None; 9857 9858 // Claim: The correct solution is not some value between Min and Max. 9859 // 9860 // Justification: Assuming that Min and Max are different values, one of 9861 // them is when the first signed overflow happens, the other is when the 9862 // first unsigned overflow happens. Crossing the range boundary is only 9863 // possible via an overflow (treating 0 as a special case of it, modeling 9864 // an overflow as crossing k*2^W for some k). 9865 // 9866 // The interesting case here is when Min was eliminated as an invalid 9867 // solution, but Max was not. The argument is that if there was another 9868 // overflow between Min and Max, it would also have been eliminated if 9869 // it was considered. 9870 // 9871 // For a given boundary, it is possible to have two overflows of the same 9872 // type (signed/unsigned) without having the other type in between: this 9873 // can happen when the vertex of the parabola is between the iterations 9874 // corresponding to the overflows. This is only possible when the two 9875 // overflows cross k*2^W for the same k. In such case, if the second one 9876 // left the range (and was the first one to do so), the first overflow 9877 // would have to enter the range, which would mean that either we had left 9878 // the range before or that we started outside of it. Both of these cases 9879 // are contradictions. 9880 // 9881 // Claim: In the case where SolveForBoundary returns None, the correct 9882 // solution is not some value between the Max for this boundary and the 9883 // Min of the other boundary. 9884 // 9885 // Justification: Assume that we had such Max_A and Min_B corresponding 9886 // to range boundaries A and B and such that Max_A < Min_B. If there was 9887 // a solution between Max_A and Min_B, it would have to be caused by an 9888 // overflow corresponding to either A or B. It cannot correspond to B, 9889 // since Min_B is the first occurrence of such an overflow. If it 9890 // corresponded to A, it would have to be either a signed or an unsigned 9891 // overflow that is larger than both eliminated overflows for A. But 9892 // between the eliminated overflows and this overflow, the values would 9893 // cover the entire value space, thus crossing the other boundary, which 9894 // is a contradiction. 9895 9896 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9897 } 9898 9899 ScalarEvolution::ExitLimit 9900 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9901 bool AllowPredicates) { 9902 9903 // This is only used for loops with a "x != y" exit test. The exit condition 9904 // is now expressed as a single expression, V = x-y. So the exit test is 9905 // effectively V != 0. We know and take advantage of the fact that this 9906 // expression only being used in a comparison by zero context. 9907 9908 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9909 // If the value is a constant 9910 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9911 // If the value is already zero, the branch will execute zero times. 9912 if (C->getValue()->isZero()) return C; 9913 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9914 } 9915 9916 const SCEVAddRecExpr *AddRec = 9917 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9918 9919 if (!AddRec && AllowPredicates) 9920 // Try to make this an AddRec using runtime tests, in the first X 9921 // iterations of this loop, where X is the SCEV expression found by the 9922 // algorithm below. 9923 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9924 9925 if (!AddRec || AddRec->getLoop() != L) 9926 return getCouldNotCompute(); 9927 9928 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9929 // the quadratic equation to solve it. 9930 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9931 // We can only use this value if the chrec ends up with an exact zero 9932 // value at this index. When solving for "X*X != 5", for example, we 9933 // should not accept a root of 2. 9934 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9935 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9936 return ExitLimit(R, R, false, Predicates); 9937 } 9938 return getCouldNotCompute(); 9939 } 9940 9941 // Otherwise we can only handle this if it is affine. 9942 if (!AddRec->isAffine()) 9943 return getCouldNotCompute(); 9944 9945 // If this is an affine expression, the execution count of this branch is 9946 // the minimum unsigned root of the following equation: 9947 // 9948 // Start + Step*N = 0 (mod 2^BW) 9949 // 9950 // equivalent to: 9951 // 9952 // Step*N = -Start (mod 2^BW) 9953 // 9954 // where BW is the common bit width of Start and Step. 9955 9956 // Get the initial value for the loop. 9957 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9958 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9959 9960 // For now we handle only constant steps. 9961 // 9962 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9963 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9964 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9965 // We have not yet seen any such cases. 9966 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9967 if (!StepC || StepC->getValue()->isZero()) 9968 return getCouldNotCompute(); 9969 9970 // For positive steps (counting up until unsigned overflow): 9971 // N = -Start/Step (as unsigned) 9972 // For negative steps (counting down to zero): 9973 // N = Start/-Step 9974 // First compute the unsigned distance from zero in the direction of Step. 9975 bool CountDown = StepC->getAPInt().isNegative(); 9976 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9977 9978 // Handle unitary steps, which cannot wraparound. 9979 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9980 // N = Distance (as unsigned) 9981 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9982 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9983 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance)); 9984 9985 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9986 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9987 // case, and see if we can improve the bound. 9988 // 9989 // Explicitly handling this here is necessary because getUnsignedRange 9990 // isn't context-sensitive; it doesn't know that we only care about the 9991 // range inside the loop. 9992 const SCEV *Zero = getZero(Distance->getType()); 9993 const SCEV *One = getOne(Distance->getType()); 9994 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9995 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9996 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9997 // as "unsigned_max(Distance + 1) - 1". 9998 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9999 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 10000 } 10001 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 10002 } 10003 10004 // If the condition controls loop exit (the loop exits only if the expression 10005 // is true) and the addition is no-wrap we can use unsigned divide to 10006 // compute the backedge count. In this case, the step may not divide the 10007 // distance, but we don't care because if the condition is "missed" the loop 10008 // will have undefined behavior due to wrapping. 10009 if (ControlsExit && AddRec->hasNoSelfWrap() && 10010 loopHasNoAbnormalExits(AddRec->getLoop())) { 10011 const SCEV *Exact = 10012 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 10013 const SCEV *Max = getCouldNotCompute(); 10014 if (Exact != getCouldNotCompute()) { 10015 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 10016 Max = getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact))); 10017 } 10018 return ExitLimit(Exact, Max, false, Predicates); 10019 } 10020 10021 // Solve the general equation. 10022 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 10023 getNegativeSCEV(Start), *this); 10024 10025 const SCEV *M = E; 10026 if (E != getCouldNotCompute()) { 10027 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L)); 10028 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E))); 10029 } 10030 return ExitLimit(E, M, false, Predicates); 10031 } 10032 10033 ScalarEvolution::ExitLimit 10034 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 10035 // Loops that look like: while (X == 0) are very strange indeed. We don't 10036 // handle them yet except for the trivial case. This could be expanded in the 10037 // future as needed. 10038 10039 // If the value is a constant, check to see if it is known to be non-zero 10040 // already. If so, the backedge will execute zero times. 10041 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 10042 if (!C->getValue()->isZero()) 10043 return getZero(C->getType()); 10044 return getCouldNotCompute(); // Otherwise it will loop infinitely. 10045 } 10046 10047 // We could implement others, but I really doubt anyone writes loops like 10048 // this, and if they did, they would already be constant folded. 10049 return getCouldNotCompute(); 10050 } 10051 10052 std::pair<const BasicBlock *, const BasicBlock *> 10053 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 10054 const { 10055 // If the block has a unique predecessor, then there is no path from the 10056 // predecessor to the block that does not go through the direct edge 10057 // from the predecessor to the block. 10058 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 10059 return {Pred, BB}; 10060 10061 // A loop's header is defined to be a block that dominates the loop. 10062 // If the header has a unique predecessor outside the loop, it must be 10063 // a block that has exactly one successor that can reach the loop. 10064 if (const Loop *L = LI.getLoopFor(BB)) 10065 return {L->getLoopPredecessor(), L->getHeader()}; 10066 10067 return {nullptr, nullptr}; 10068 } 10069 10070 /// SCEV structural equivalence is usually sufficient for testing whether two 10071 /// expressions are equal, however for the purposes of looking for a condition 10072 /// guarding a loop, it can be useful to be a little more general, since a 10073 /// front-end may have replicated the controlling expression. 10074 static bool HasSameValue(const SCEV *A, const SCEV *B) { 10075 // Quick check to see if they are the same SCEV. 10076 if (A == B) return true; 10077 10078 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 10079 // Not all instructions that are "identical" compute the same value. For 10080 // instance, two distinct alloca instructions allocating the same type are 10081 // identical and do not read memory; but compute distinct values. 10082 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 10083 }; 10084 10085 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 10086 // two different instructions with the same value. Check for this case. 10087 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 10088 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 10089 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 10090 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 10091 if (ComputesEqualValues(AI, BI)) 10092 return true; 10093 10094 // Otherwise assume they may have a different value. 10095 return false; 10096 } 10097 10098 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 10099 const SCEV *&LHS, const SCEV *&RHS, 10100 unsigned Depth, 10101 bool ControllingFiniteLoop) { 10102 bool Changed = false; 10103 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 10104 // '0 != 0'. 10105 auto TrivialCase = [&](bool TriviallyTrue) { 10106 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 10107 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 10108 return true; 10109 }; 10110 // If we hit the max recursion limit bail out. 10111 if (Depth >= 3) 10112 return false; 10113 10114 // Canonicalize a constant to the right side. 10115 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 10116 // Check for both operands constant. 10117 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 10118 if (ConstantExpr::getICmp(Pred, 10119 LHSC->getValue(), 10120 RHSC->getValue())->isNullValue()) 10121 return TrivialCase(false); 10122 else 10123 return TrivialCase(true); 10124 } 10125 // Otherwise swap the operands to put the constant on the right. 10126 std::swap(LHS, RHS); 10127 Pred = ICmpInst::getSwappedPredicate(Pred); 10128 Changed = true; 10129 } 10130 10131 // If we're comparing an addrec with a value which is loop-invariant in the 10132 // addrec's loop, put the addrec on the left. Also make a dominance check, 10133 // as both operands could be addrecs loop-invariant in each other's loop. 10134 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 10135 const Loop *L = AR->getLoop(); 10136 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 10137 std::swap(LHS, RHS); 10138 Pred = ICmpInst::getSwappedPredicate(Pred); 10139 Changed = true; 10140 } 10141 } 10142 10143 // If there's a constant operand, canonicalize comparisons with boundary 10144 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 10145 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 10146 const APInt &RA = RC->getAPInt(); 10147 10148 bool SimplifiedByConstantRange = false; 10149 10150 if (!ICmpInst::isEquality(Pred)) { 10151 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 10152 if (ExactCR.isFullSet()) 10153 return TrivialCase(true); 10154 else if (ExactCR.isEmptySet()) 10155 return TrivialCase(false); 10156 10157 APInt NewRHS; 10158 CmpInst::Predicate NewPred; 10159 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 10160 ICmpInst::isEquality(NewPred)) { 10161 // We were able to convert an inequality to an equality. 10162 Pred = NewPred; 10163 RHS = getConstant(NewRHS); 10164 Changed = SimplifiedByConstantRange = true; 10165 } 10166 } 10167 10168 if (!SimplifiedByConstantRange) { 10169 switch (Pred) { 10170 default: 10171 break; 10172 case ICmpInst::ICMP_EQ: 10173 case ICmpInst::ICMP_NE: 10174 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 10175 if (!RA) 10176 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 10177 if (const SCEVMulExpr *ME = 10178 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 10179 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 10180 ME->getOperand(0)->isAllOnesValue()) { 10181 RHS = AE->getOperand(1); 10182 LHS = ME->getOperand(1); 10183 Changed = true; 10184 } 10185 break; 10186 10187 10188 // The "Should have been caught earlier!" messages refer to the fact 10189 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 10190 // should have fired on the corresponding cases, and canonicalized the 10191 // check to trivial case. 10192 10193 case ICmpInst::ICMP_UGE: 10194 assert(!RA.isMinValue() && "Should have been caught earlier!"); 10195 Pred = ICmpInst::ICMP_UGT; 10196 RHS = getConstant(RA - 1); 10197 Changed = true; 10198 break; 10199 case ICmpInst::ICMP_ULE: 10200 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 10201 Pred = ICmpInst::ICMP_ULT; 10202 RHS = getConstant(RA + 1); 10203 Changed = true; 10204 break; 10205 case ICmpInst::ICMP_SGE: 10206 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 10207 Pred = ICmpInst::ICMP_SGT; 10208 RHS = getConstant(RA - 1); 10209 Changed = true; 10210 break; 10211 case ICmpInst::ICMP_SLE: 10212 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 10213 Pred = ICmpInst::ICMP_SLT; 10214 RHS = getConstant(RA + 1); 10215 Changed = true; 10216 break; 10217 } 10218 } 10219 } 10220 10221 // Check for obvious equality. 10222 if (HasSameValue(LHS, RHS)) { 10223 if (ICmpInst::isTrueWhenEqual(Pred)) 10224 return TrivialCase(true); 10225 if (ICmpInst::isFalseWhenEqual(Pred)) 10226 return TrivialCase(false); 10227 } 10228 10229 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 10230 // adding or subtracting 1 from one of the operands. This can be done for 10231 // one of two reasons: 10232 // 1) The range of the RHS does not include the (signed/unsigned) boundaries 10233 // 2) The loop is finite, with this comparison controlling the exit. Since the 10234 // loop is finite, the bound cannot include the corresponding boundary 10235 // (otherwise it would loop forever). 10236 switch (Pred) { 10237 case ICmpInst::ICMP_SLE: 10238 if (ControllingFiniteLoop || !getSignedRangeMax(RHS).isMaxSignedValue()) { 10239 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 10240 SCEV::FlagNSW); 10241 Pred = ICmpInst::ICMP_SLT; 10242 Changed = true; 10243 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 10244 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 10245 SCEV::FlagNSW); 10246 Pred = ICmpInst::ICMP_SLT; 10247 Changed = true; 10248 } 10249 break; 10250 case ICmpInst::ICMP_SGE: 10251 if (ControllingFiniteLoop || !getSignedRangeMin(RHS).isMinSignedValue()) { 10252 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 10253 SCEV::FlagNSW); 10254 Pred = ICmpInst::ICMP_SGT; 10255 Changed = true; 10256 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 10257 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 10258 SCEV::FlagNSW); 10259 Pred = ICmpInst::ICMP_SGT; 10260 Changed = true; 10261 } 10262 break; 10263 case ICmpInst::ICMP_ULE: 10264 if (ControllingFiniteLoop || !getUnsignedRangeMax(RHS).isMaxValue()) { 10265 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 10266 SCEV::FlagNUW); 10267 Pred = ICmpInst::ICMP_ULT; 10268 Changed = true; 10269 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 10270 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 10271 Pred = ICmpInst::ICMP_ULT; 10272 Changed = true; 10273 } 10274 break; 10275 case ICmpInst::ICMP_UGE: 10276 if (ControllingFiniteLoop || !getUnsignedRangeMin(RHS).isMinValue()) { 10277 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 10278 Pred = ICmpInst::ICMP_UGT; 10279 Changed = true; 10280 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 10281 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 10282 SCEV::FlagNUW); 10283 Pred = ICmpInst::ICMP_UGT; 10284 Changed = true; 10285 } 10286 break; 10287 default: 10288 break; 10289 } 10290 10291 // TODO: More simplifications are possible here. 10292 10293 // Recursively simplify until we either hit a recursion limit or nothing 10294 // changes. 10295 if (Changed) 10296 return SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1, 10297 ControllingFiniteLoop); 10298 10299 return Changed; 10300 } 10301 10302 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 10303 return getSignedRangeMax(S).isNegative(); 10304 } 10305 10306 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 10307 return getSignedRangeMin(S).isStrictlyPositive(); 10308 } 10309 10310 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 10311 return !getSignedRangeMin(S).isNegative(); 10312 } 10313 10314 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 10315 return !getSignedRangeMax(S).isStrictlyPositive(); 10316 } 10317 10318 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 10319 return getUnsignedRangeMin(S) != 0; 10320 } 10321 10322 std::pair<const SCEV *, const SCEV *> 10323 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 10324 // Compute SCEV on entry of loop L. 10325 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 10326 if (Start == getCouldNotCompute()) 10327 return { Start, Start }; 10328 // Compute post increment SCEV for loop L. 10329 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 10330 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 10331 return { Start, PostInc }; 10332 } 10333 10334 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 10335 const SCEV *LHS, const SCEV *RHS) { 10336 // First collect all loops. 10337 SmallPtrSet<const Loop *, 8> LoopsUsed; 10338 getUsedLoops(LHS, LoopsUsed); 10339 getUsedLoops(RHS, LoopsUsed); 10340 10341 if (LoopsUsed.empty()) 10342 return false; 10343 10344 // Domination relationship must be a linear order on collected loops. 10345 #ifndef NDEBUG 10346 for (auto *L1 : LoopsUsed) 10347 for (auto *L2 : LoopsUsed) 10348 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 10349 DT.dominates(L2->getHeader(), L1->getHeader())) && 10350 "Domination relationship is not a linear order"); 10351 #endif 10352 10353 const Loop *MDL = 10354 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 10355 [&](const Loop *L1, const Loop *L2) { 10356 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 10357 }); 10358 10359 // Get init and post increment value for LHS. 10360 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 10361 // if LHS contains unknown non-invariant SCEV then bail out. 10362 if (SplitLHS.first == getCouldNotCompute()) 10363 return false; 10364 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 10365 // Get init and post increment value for RHS. 10366 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 10367 // if RHS contains unknown non-invariant SCEV then bail out. 10368 if (SplitRHS.first == getCouldNotCompute()) 10369 return false; 10370 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 10371 // It is possible that init SCEV contains an invariant load but it does 10372 // not dominate MDL and is not available at MDL loop entry, so we should 10373 // check it here. 10374 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 10375 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 10376 return false; 10377 10378 // It seems backedge guard check is faster than entry one so in some cases 10379 // it can speed up whole estimation by short circuit 10380 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 10381 SplitRHS.second) && 10382 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 10383 } 10384 10385 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 10386 const SCEV *LHS, const SCEV *RHS) { 10387 // Canonicalize the inputs first. 10388 (void)SimplifyICmpOperands(Pred, LHS, RHS); 10389 10390 if (isKnownViaInduction(Pred, LHS, RHS)) 10391 return true; 10392 10393 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 10394 return true; 10395 10396 // Otherwise see what can be done with some simple reasoning. 10397 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 10398 } 10399 10400 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 10401 const SCEV *LHS, 10402 const SCEV *RHS) { 10403 if (isKnownPredicate(Pred, LHS, RHS)) 10404 return true; 10405 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 10406 return false; 10407 return None; 10408 } 10409 10410 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 10411 const SCEV *LHS, const SCEV *RHS, 10412 const Instruction *CtxI) { 10413 // TODO: Analyze guards and assumes from Context's block. 10414 return isKnownPredicate(Pred, LHS, RHS) || 10415 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS); 10416 } 10417 10418 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, 10419 const SCEV *LHS, 10420 const SCEV *RHS, 10421 const Instruction *CtxI) { 10422 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 10423 if (KnownWithoutContext) 10424 return KnownWithoutContext; 10425 10426 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS)) 10427 return true; 10428 else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), 10429 ICmpInst::getInversePredicate(Pred), 10430 LHS, RHS)) 10431 return false; 10432 return None; 10433 } 10434 10435 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 10436 const SCEVAddRecExpr *LHS, 10437 const SCEV *RHS) { 10438 const Loop *L = LHS->getLoop(); 10439 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 10440 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 10441 } 10442 10443 Optional<ScalarEvolution::MonotonicPredicateType> 10444 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 10445 ICmpInst::Predicate Pred) { 10446 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 10447 10448 #ifndef NDEBUG 10449 // Verify an invariant: inverting the predicate should turn a monotonically 10450 // increasing change to a monotonically decreasing one, and vice versa. 10451 if (Result) { 10452 auto ResultSwapped = 10453 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 10454 10455 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 10456 assert(ResultSwapped.getValue() != Result.getValue() && 10457 "monotonicity should flip as we flip the predicate"); 10458 } 10459 #endif 10460 10461 return Result; 10462 } 10463 10464 Optional<ScalarEvolution::MonotonicPredicateType> 10465 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 10466 ICmpInst::Predicate Pred) { 10467 // A zero step value for LHS means the induction variable is essentially a 10468 // loop invariant value. We don't really depend on the predicate actually 10469 // flipping from false to true (for increasing predicates, and the other way 10470 // around for decreasing predicates), all we care about is that *if* the 10471 // predicate changes then it only changes from false to true. 10472 // 10473 // A zero step value in itself is not very useful, but there may be places 10474 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 10475 // as general as possible. 10476 10477 // Only handle LE/LT/GE/GT predicates. 10478 if (!ICmpInst::isRelational(Pred)) 10479 return None; 10480 10481 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 10482 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 10483 "Should be greater or less!"); 10484 10485 // Check that AR does not wrap. 10486 if (ICmpInst::isUnsigned(Pred)) { 10487 if (!LHS->hasNoUnsignedWrap()) 10488 return None; 10489 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10490 } else { 10491 assert(ICmpInst::isSigned(Pred) && 10492 "Relational predicate is either signed or unsigned!"); 10493 if (!LHS->hasNoSignedWrap()) 10494 return None; 10495 10496 const SCEV *Step = LHS->getStepRecurrence(*this); 10497 10498 if (isKnownNonNegative(Step)) 10499 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10500 10501 if (isKnownNonPositive(Step)) 10502 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10503 10504 return None; 10505 } 10506 } 10507 10508 Optional<ScalarEvolution::LoopInvariantPredicate> 10509 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 10510 const SCEV *LHS, const SCEV *RHS, 10511 const Loop *L) { 10512 10513 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10514 if (!isLoopInvariant(RHS, L)) { 10515 if (!isLoopInvariant(LHS, L)) 10516 return None; 10517 10518 std::swap(LHS, RHS); 10519 Pred = ICmpInst::getSwappedPredicate(Pred); 10520 } 10521 10522 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10523 if (!ArLHS || ArLHS->getLoop() != L) 10524 return None; 10525 10526 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 10527 if (!MonotonicType) 10528 return None; 10529 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 10530 // true as the loop iterates, and the backedge is control dependent on 10531 // "ArLHS `Pred` RHS" == true then we can reason as follows: 10532 // 10533 // * if the predicate was false in the first iteration then the predicate 10534 // is never evaluated again, since the loop exits without taking the 10535 // backedge. 10536 // * if the predicate was true in the first iteration then it will 10537 // continue to be true for all future iterations since it is 10538 // monotonically increasing. 10539 // 10540 // For both the above possibilities, we can replace the loop varying 10541 // predicate with its value on the first iteration of the loop (which is 10542 // loop invariant). 10543 // 10544 // A similar reasoning applies for a monotonically decreasing predicate, by 10545 // replacing true with false and false with true in the above two bullets. 10546 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 10547 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 10548 10549 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 10550 return None; 10551 10552 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 10553 } 10554 10555 Optional<ScalarEvolution::LoopInvariantPredicate> 10556 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 10557 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 10558 const Instruction *CtxI, const SCEV *MaxIter) { 10559 // Try to prove the following set of facts: 10560 // - The predicate is monotonic in the iteration space. 10561 // - If the check does not fail on the 1st iteration: 10562 // - No overflow will happen during first MaxIter iterations; 10563 // - It will not fail on the MaxIter'th iteration. 10564 // If the check does fail on the 1st iteration, we leave the loop and no 10565 // other checks matter. 10566 10567 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10568 if (!isLoopInvariant(RHS, L)) { 10569 if (!isLoopInvariant(LHS, L)) 10570 return None; 10571 10572 std::swap(LHS, RHS); 10573 Pred = ICmpInst::getSwappedPredicate(Pred); 10574 } 10575 10576 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 10577 if (!AR || AR->getLoop() != L) 10578 return None; 10579 10580 // The predicate must be relational (i.e. <, <=, >=, >). 10581 if (!ICmpInst::isRelational(Pred)) 10582 return None; 10583 10584 // TODO: Support steps other than +/- 1. 10585 const SCEV *Step = AR->getStepRecurrence(*this); 10586 auto *One = getOne(Step->getType()); 10587 auto *MinusOne = getNegativeSCEV(One); 10588 if (Step != One && Step != MinusOne) 10589 return None; 10590 10591 // Type mismatch here means that MaxIter is potentially larger than max 10592 // unsigned value in start type, which mean we cannot prove no wrap for the 10593 // indvar. 10594 if (AR->getType() != MaxIter->getType()) 10595 return None; 10596 10597 // Value of IV on suggested last iteration. 10598 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 10599 // Does it still meet the requirement? 10600 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 10601 return None; 10602 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 10603 // not exceed max unsigned value of this type), this effectively proves 10604 // that there is no wrap during the iteration. To prove that there is no 10605 // signed/unsigned wrap, we need to check that 10606 // Start <= Last for step = 1 or Start >= Last for step = -1. 10607 ICmpInst::Predicate NoOverflowPred = 10608 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 10609 if (Step == MinusOne) 10610 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 10611 const SCEV *Start = AR->getStart(); 10612 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI)) 10613 return None; 10614 10615 // Everything is fine. 10616 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 10617 } 10618 10619 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 10620 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 10621 if (HasSameValue(LHS, RHS)) 10622 return ICmpInst::isTrueWhenEqual(Pred); 10623 10624 // This code is split out from isKnownPredicate because it is called from 10625 // within isLoopEntryGuardedByCond. 10626 10627 auto CheckRanges = [&](const ConstantRange &RangeLHS, 10628 const ConstantRange &RangeRHS) { 10629 return RangeLHS.icmp(Pred, RangeRHS); 10630 }; 10631 10632 // The check at the top of the function catches the case where the values are 10633 // known to be equal. 10634 if (Pred == CmpInst::ICMP_EQ) 10635 return false; 10636 10637 if (Pred == CmpInst::ICMP_NE) { 10638 if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 10639 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS))) 10640 return true; 10641 auto *Diff = getMinusSCEV(LHS, RHS); 10642 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff); 10643 } 10644 10645 if (CmpInst::isSigned(Pred)) 10646 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 10647 10648 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 10649 } 10650 10651 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 10652 const SCEV *LHS, 10653 const SCEV *RHS) { 10654 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where 10655 // C1 and C2 are constant integers. If either X or Y are not add expressions, 10656 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via 10657 // OutC1 and OutC2. 10658 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y, 10659 APInt &OutC1, APInt &OutC2, 10660 SCEV::NoWrapFlags ExpectedFlags) { 10661 const SCEV *XNonConstOp, *XConstOp; 10662 const SCEV *YNonConstOp, *YConstOp; 10663 SCEV::NoWrapFlags XFlagsPresent; 10664 SCEV::NoWrapFlags YFlagsPresent; 10665 10666 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) { 10667 XConstOp = getZero(X->getType()); 10668 XNonConstOp = X; 10669 XFlagsPresent = ExpectedFlags; 10670 } 10671 if (!isa<SCEVConstant>(XConstOp) || 10672 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) 10673 return false; 10674 10675 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) { 10676 YConstOp = getZero(Y->getType()); 10677 YNonConstOp = Y; 10678 YFlagsPresent = ExpectedFlags; 10679 } 10680 10681 if (!isa<SCEVConstant>(YConstOp) || 10682 (YFlagsPresent & ExpectedFlags) != ExpectedFlags) 10683 return false; 10684 10685 if (YNonConstOp != XNonConstOp) 10686 return false; 10687 10688 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt(); 10689 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt(); 10690 10691 return true; 10692 }; 10693 10694 APInt C1; 10695 APInt C2; 10696 10697 switch (Pred) { 10698 default: 10699 break; 10700 10701 case ICmpInst::ICMP_SGE: 10702 std::swap(LHS, RHS); 10703 LLVM_FALLTHROUGH; 10704 case ICmpInst::ICMP_SLE: 10705 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2. 10706 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2)) 10707 return true; 10708 10709 break; 10710 10711 case ICmpInst::ICMP_SGT: 10712 std::swap(LHS, RHS); 10713 LLVM_FALLTHROUGH; 10714 case ICmpInst::ICMP_SLT: 10715 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2. 10716 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2)) 10717 return true; 10718 10719 break; 10720 10721 case ICmpInst::ICMP_UGE: 10722 std::swap(LHS, RHS); 10723 LLVM_FALLTHROUGH; 10724 case ICmpInst::ICMP_ULE: 10725 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2. 10726 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2)) 10727 return true; 10728 10729 break; 10730 10731 case ICmpInst::ICMP_UGT: 10732 std::swap(LHS, RHS); 10733 LLVM_FALLTHROUGH; 10734 case ICmpInst::ICMP_ULT: 10735 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2. 10736 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2)) 10737 return true; 10738 break; 10739 } 10740 10741 return false; 10742 } 10743 10744 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10745 const SCEV *LHS, 10746 const SCEV *RHS) { 10747 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10748 return false; 10749 10750 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10751 // the stack can result in exponential time complexity. 10752 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10753 10754 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10755 // 10756 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10757 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10758 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10759 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10760 // use isKnownPredicate later if needed. 10761 return isKnownNonNegative(RHS) && 10762 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10763 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10764 } 10765 10766 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10767 ICmpInst::Predicate Pred, 10768 const SCEV *LHS, const SCEV *RHS) { 10769 // No need to even try if we know the module has no guards. 10770 if (!HasGuards) 10771 return false; 10772 10773 return any_of(*BB, [&](const Instruction &I) { 10774 using namespace llvm::PatternMatch; 10775 10776 Value *Condition; 10777 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10778 m_Value(Condition))) && 10779 isImpliedCond(Pred, LHS, RHS, Condition, false); 10780 }); 10781 } 10782 10783 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10784 /// protected by a conditional between LHS and RHS. This is used to 10785 /// to eliminate casts. 10786 bool 10787 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10788 ICmpInst::Predicate Pred, 10789 const SCEV *LHS, const SCEV *RHS) { 10790 // Interpret a null as meaning no loop, where there is obviously no guard 10791 // (interprocedural conditions notwithstanding). 10792 if (!L) return true; 10793 10794 if (VerifyIR) 10795 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10796 "This cannot be done on broken IR!"); 10797 10798 10799 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10800 return true; 10801 10802 BasicBlock *Latch = L->getLoopLatch(); 10803 if (!Latch) 10804 return false; 10805 10806 BranchInst *LoopContinuePredicate = 10807 dyn_cast<BranchInst>(Latch->getTerminator()); 10808 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10809 isImpliedCond(Pred, LHS, RHS, 10810 LoopContinuePredicate->getCondition(), 10811 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10812 return true; 10813 10814 // We don't want more than one activation of the following loops on the stack 10815 // -- that can lead to O(n!) time complexity. 10816 if (WalkingBEDominatingConds) 10817 return false; 10818 10819 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10820 10821 // See if we can exploit a trip count to prove the predicate. 10822 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10823 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10824 if (LatchBECount != getCouldNotCompute()) { 10825 // We know that Latch branches back to the loop header exactly 10826 // LatchBECount times. This means the backdege condition at Latch is 10827 // equivalent to "{0,+,1} u< LatchBECount". 10828 Type *Ty = LatchBECount->getType(); 10829 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10830 const SCEV *LoopCounter = 10831 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10832 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10833 LatchBECount)) 10834 return true; 10835 } 10836 10837 // Check conditions due to any @llvm.assume intrinsics. 10838 for (auto &AssumeVH : AC.assumptions()) { 10839 if (!AssumeVH) 10840 continue; 10841 auto *CI = cast<CallInst>(AssumeVH); 10842 if (!DT.dominates(CI, Latch->getTerminator())) 10843 continue; 10844 10845 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10846 return true; 10847 } 10848 10849 // If the loop is not reachable from the entry block, we risk running into an 10850 // infinite loop as we walk up into the dom tree. These loops do not matter 10851 // anyway, so we just return a conservative answer when we see them. 10852 if (!DT.isReachableFromEntry(L->getHeader())) 10853 return false; 10854 10855 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10856 return true; 10857 10858 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10859 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10860 assert(DTN && "should reach the loop header before reaching the root!"); 10861 10862 BasicBlock *BB = DTN->getBlock(); 10863 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10864 return true; 10865 10866 BasicBlock *PBB = BB->getSinglePredecessor(); 10867 if (!PBB) 10868 continue; 10869 10870 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10871 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10872 continue; 10873 10874 Value *Condition = ContinuePredicate->getCondition(); 10875 10876 // If we have an edge `E` within the loop body that dominates the only 10877 // latch, the condition guarding `E` also guards the backedge. This 10878 // reasoning works only for loops with a single latch. 10879 10880 BasicBlockEdge DominatingEdge(PBB, BB); 10881 if (DominatingEdge.isSingleEdge()) { 10882 // We're constructively (and conservatively) enumerating edges within the 10883 // loop body that dominate the latch. The dominator tree better agree 10884 // with us on this: 10885 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10886 10887 if (isImpliedCond(Pred, LHS, RHS, Condition, 10888 BB != ContinuePredicate->getSuccessor(0))) 10889 return true; 10890 } 10891 } 10892 10893 return false; 10894 } 10895 10896 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10897 ICmpInst::Predicate Pred, 10898 const SCEV *LHS, 10899 const SCEV *RHS) { 10900 if (VerifyIR) 10901 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10902 "This cannot be done on broken IR!"); 10903 10904 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10905 // the facts (a >= b && a != b) separately. A typical situation is when the 10906 // non-strict comparison is known from ranges and non-equality is known from 10907 // dominating predicates. If we are proving strict comparison, we always try 10908 // to prove non-equality and non-strict comparison separately. 10909 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10910 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10911 bool ProvedNonStrictComparison = false; 10912 bool ProvedNonEquality = false; 10913 10914 auto SplitAndProve = 10915 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10916 if (!ProvedNonStrictComparison) 10917 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10918 if (!ProvedNonEquality) 10919 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10920 if (ProvedNonStrictComparison && ProvedNonEquality) 10921 return true; 10922 return false; 10923 }; 10924 10925 if (ProvingStrictComparison) { 10926 auto ProofFn = [&](ICmpInst::Predicate P) { 10927 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10928 }; 10929 if (SplitAndProve(ProofFn)) 10930 return true; 10931 } 10932 10933 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10934 auto ProveViaGuard = [&](const BasicBlock *Block) { 10935 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10936 return true; 10937 if (ProvingStrictComparison) { 10938 auto ProofFn = [&](ICmpInst::Predicate P) { 10939 return isImpliedViaGuard(Block, P, LHS, RHS); 10940 }; 10941 if (SplitAndProve(ProofFn)) 10942 return true; 10943 } 10944 return false; 10945 }; 10946 10947 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10948 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10949 const Instruction *CtxI = &BB->front(); 10950 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI)) 10951 return true; 10952 if (ProvingStrictComparison) { 10953 auto ProofFn = [&](ICmpInst::Predicate P) { 10954 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI); 10955 }; 10956 if (SplitAndProve(ProofFn)) 10957 return true; 10958 } 10959 return false; 10960 }; 10961 10962 // Starting at the block's predecessor, climb up the predecessor chain, as long 10963 // as there are predecessors that can be found that have unique successors 10964 // leading to the original block. 10965 const Loop *ContainingLoop = LI.getLoopFor(BB); 10966 const BasicBlock *PredBB; 10967 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10968 PredBB = ContainingLoop->getLoopPredecessor(); 10969 else 10970 PredBB = BB->getSinglePredecessor(); 10971 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10972 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10973 if (ProveViaGuard(Pair.first)) 10974 return true; 10975 10976 const BranchInst *LoopEntryPredicate = 10977 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10978 if (!LoopEntryPredicate || 10979 LoopEntryPredicate->isUnconditional()) 10980 continue; 10981 10982 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10983 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10984 return true; 10985 } 10986 10987 // Check conditions due to any @llvm.assume intrinsics. 10988 for (auto &AssumeVH : AC.assumptions()) { 10989 if (!AssumeVH) 10990 continue; 10991 auto *CI = cast<CallInst>(AssumeVH); 10992 if (!DT.dominates(CI, BB)) 10993 continue; 10994 10995 if (ProveViaCond(CI->getArgOperand(0), false)) 10996 return true; 10997 } 10998 10999 return false; 11000 } 11001 11002 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 11003 ICmpInst::Predicate Pred, 11004 const SCEV *LHS, 11005 const SCEV *RHS) { 11006 // Interpret a null as meaning no loop, where there is obviously no guard 11007 // (interprocedural conditions notwithstanding). 11008 if (!L) 11009 return false; 11010 11011 // Both LHS and RHS must be available at loop entry. 11012 assert(isAvailableAtLoopEntry(LHS, L) && 11013 "LHS is not available at Loop Entry"); 11014 assert(isAvailableAtLoopEntry(RHS, L) && 11015 "RHS is not available at Loop Entry"); 11016 11017 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 11018 return true; 11019 11020 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 11021 } 11022 11023 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 11024 const SCEV *RHS, 11025 const Value *FoundCondValue, bool Inverse, 11026 const Instruction *CtxI) { 11027 // False conditions implies anything. Do not bother analyzing it further. 11028 if (FoundCondValue == 11029 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 11030 return true; 11031 11032 if (!PendingLoopPredicates.insert(FoundCondValue).second) 11033 return false; 11034 11035 auto ClearOnExit = 11036 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 11037 11038 // Recursively handle And and Or conditions. 11039 const Value *Op0, *Op1; 11040 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 11041 if (!Inverse) 11042 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 11043 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 11044 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 11045 if (Inverse) 11046 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 11047 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 11048 } 11049 11050 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 11051 if (!ICI) return false; 11052 11053 // Now that we found a conditional branch that dominates the loop or controls 11054 // the loop latch. Check to see if it is the comparison we are looking for. 11055 ICmpInst::Predicate FoundPred; 11056 if (Inverse) 11057 FoundPred = ICI->getInversePredicate(); 11058 else 11059 FoundPred = ICI->getPredicate(); 11060 11061 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 11062 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 11063 11064 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI); 11065 } 11066 11067 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 11068 const SCEV *RHS, 11069 ICmpInst::Predicate FoundPred, 11070 const SCEV *FoundLHS, const SCEV *FoundRHS, 11071 const Instruction *CtxI) { 11072 // Balance the types. 11073 if (getTypeSizeInBits(LHS->getType()) < 11074 getTypeSizeInBits(FoundLHS->getType())) { 11075 // For unsigned and equality predicates, try to prove that both found 11076 // operands fit into narrow unsigned range. If so, try to prove facts in 11077 // narrow types. 11078 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() && 11079 !FoundRHS->getType()->isPointerTy()) { 11080 auto *NarrowType = LHS->getType(); 11081 auto *WideType = FoundLHS->getType(); 11082 auto BitWidth = getTypeSizeInBits(NarrowType); 11083 const SCEV *MaxValue = getZeroExtendExpr( 11084 getConstant(APInt::getMaxValue(BitWidth)), WideType); 11085 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS, 11086 MaxValue) && 11087 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS, 11088 MaxValue)) { 11089 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 11090 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 11091 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 11092 TruncFoundRHS, CtxI)) 11093 return true; 11094 } 11095 } 11096 11097 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy()) 11098 return false; 11099 if (CmpInst::isSigned(Pred)) { 11100 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 11101 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 11102 } else { 11103 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 11104 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 11105 } 11106 } else if (getTypeSizeInBits(LHS->getType()) > 11107 getTypeSizeInBits(FoundLHS->getType())) { 11108 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy()) 11109 return false; 11110 if (CmpInst::isSigned(FoundPred)) { 11111 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 11112 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 11113 } else { 11114 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 11115 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 11116 } 11117 } 11118 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 11119 FoundRHS, CtxI); 11120 } 11121 11122 bool ScalarEvolution::isImpliedCondBalancedTypes( 11123 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 11124 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 11125 const Instruction *CtxI) { 11126 assert(getTypeSizeInBits(LHS->getType()) == 11127 getTypeSizeInBits(FoundLHS->getType()) && 11128 "Types should be balanced!"); 11129 // Canonicalize the query to match the way instcombine will have 11130 // canonicalized the comparison. 11131 if (SimplifyICmpOperands(Pred, LHS, RHS)) 11132 if (LHS == RHS) 11133 return CmpInst::isTrueWhenEqual(Pred); 11134 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 11135 if (FoundLHS == FoundRHS) 11136 return CmpInst::isFalseWhenEqual(FoundPred); 11137 11138 // Check to see if we can make the LHS or RHS match. 11139 if (LHS == FoundRHS || RHS == FoundLHS) { 11140 if (isa<SCEVConstant>(RHS)) { 11141 std::swap(FoundLHS, FoundRHS); 11142 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 11143 } else { 11144 std::swap(LHS, RHS); 11145 Pred = ICmpInst::getSwappedPredicate(Pred); 11146 } 11147 } 11148 11149 // Check whether the found predicate is the same as the desired predicate. 11150 if (FoundPred == Pred) 11151 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 11152 11153 // Check whether swapping the found predicate makes it the same as the 11154 // desired predicate. 11155 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 11156 // We can write the implication 11157 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 11158 // using one of the following ways: 11159 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 11160 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 11161 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 11162 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 11163 // Forms 1. and 2. require swapping the operands of one condition. Don't 11164 // do this if it would break canonical constant/addrec ordering. 11165 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 11166 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 11167 CtxI); 11168 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 11169 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI); 11170 11171 // There's no clear preference between forms 3. and 4., try both. Avoid 11172 // forming getNotSCEV of pointer values as the resulting subtract is 11173 // not legal. 11174 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() && 11175 isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 11176 FoundLHS, FoundRHS, CtxI)) 11177 return true; 11178 11179 if (!FoundLHS->getType()->isPointerTy() && 11180 !FoundRHS->getType()->isPointerTy() && 11181 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 11182 getNotSCEV(FoundRHS), CtxI)) 11183 return true; 11184 11185 return false; 11186 } 11187 11188 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1, 11189 CmpInst::Predicate P2) { 11190 assert(P1 != P2 && "Handled earlier!"); 11191 return CmpInst::isRelational(P2) && 11192 P1 == CmpInst::getFlippedSignednessPredicate(P2); 11193 }; 11194 if (IsSignFlippedPredicate(Pred, FoundPred)) { 11195 // Unsigned comparison is the same as signed comparison when both the 11196 // operands are non-negative or negative. 11197 if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) || 11198 (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS))) 11199 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 11200 // Create local copies that we can freely swap and canonicalize our 11201 // conditions to "le/lt". 11202 ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred; 11203 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS, 11204 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS; 11205 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) { 11206 CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred); 11207 CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred); 11208 std::swap(CanonicalLHS, CanonicalRHS); 11209 std::swap(CanonicalFoundLHS, CanonicalFoundRHS); 11210 } 11211 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) && 11212 "Must be!"); 11213 assert((ICmpInst::isLT(CanonicalFoundPred) || 11214 ICmpInst::isLE(CanonicalFoundPred)) && 11215 "Must be!"); 11216 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS)) 11217 // Use implication: 11218 // x <u y && y >=s 0 --> x <s y. 11219 // If we can prove the left part, the right part is also proven. 11220 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 11221 CanonicalRHS, CanonicalFoundLHS, 11222 CanonicalFoundRHS); 11223 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS)) 11224 // Use implication: 11225 // x <s y && y <s 0 --> x <u y. 11226 // If we can prove the left part, the right part is also proven. 11227 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 11228 CanonicalRHS, CanonicalFoundLHS, 11229 CanonicalFoundRHS); 11230 } 11231 11232 // Check if we can make progress by sharpening ranges. 11233 if (FoundPred == ICmpInst::ICMP_NE && 11234 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 11235 11236 const SCEVConstant *C = nullptr; 11237 const SCEV *V = nullptr; 11238 11239 if (isa<SCEVConstant>(FoundLHS)) { 11240 C = cast<SCEVConstant>(FoundLHS); 11241 V = FoundRHS; 11242 } else { 11243 C = cast<SCEVConstant>(FoundRHS); 11244 V = FoundLHS; 11245 } 11246 11247 // The guarding predicate tells us that C != V. If the known range 11248 // of V is [C, t), we can sharpen the range to [C + 1, t). The 11249 // range we consider has to correspond to same signedness as the 11250 // predicate we're interested in folding. 11251 11252 APInt Min = ICmpInst::isSigned(Pred) ? 11253 getSignedRangeMin(V) : getUnsignedRangeMin(V); 11254 11255 if (Min == C->getAPInt()) { 11256 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 11257 // This is true even if (Min + 1) wraps around -- in case of 11258 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 11259 11260 APInt SharperMin = Min + 1; 11261 11262 switch (Pred) { 11263 case ICmpInst::ICMP_SGE: 11264 case ICmpInst::ICMP_UGE: 11265 // We know V `Pred` SharperMin. If this implies LHS `Pred` 11266 // RHS, we're done. 11267 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 11268 CtxI)) 11269 return true; 11270 LLVM_FALLTHROUGH; 11271 11272 case ICmpInst::ICMP_SGT: 11273 case ICmpInst::ICMP_UGT: 11274 // We know from the range information that (V `Pred` Min || 11275 // V == Min). We know from the guarding condition that !(V 11276 // == Min). This gives us 11277 // 11278 // V `Pred` Min || V == Min && !(V == Min) 11279 // => V `Pred` Min 11280 // 11281 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 11282 11283 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI)) 11284 return true; 11285 break; 11286 11287 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 11288 case ICmpInst::ICMP_SLE: 11289 case ICmpInst::ICMP_ULE: 11290 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 11291 LHS, V, getConstant(SharperMin), CtxI)) 11292 return true; 11293 LLVM_FALLTHROUGH; 11294 11295 case ICmpInst::ICMP_SLT: 11296 case ICmpInst::ICMP_ULT: 11297 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 11298 LHS, V, getConstant(Min), CtxI)) 11299 return true; 11300 break; 11301 11302 default: 11303 // No change 11304 break; 11305 } 11306 } 11307 } 11308 11309 // Check whether the actual condition is beyond sufficient. 11310 if (FoundPred == ICmpInst::ICMP_EQ) 11311 if (ICmpInst::isTrueWhenEqual(Pred)) 11312 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 11313 return true; 11314 if (Pred == ICmpInst::ICMP_NE) 11315 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 11316 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 11317 return true; 11318 11319 // Otherwise assume the worst. 11320 return false; 11321 } 11322 11323 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 11324 const SCEV *&L, const SCEV *&R, 11325 SCEV::NoWrapFlags &Flags) { 11326 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 11327 if (!AE || AE->getNumOperands() != 2) 11328 return false; 11329 11330 L = AE->getOperand(0); 11331 R = AE->getOperand(1); 11332 Flags = AE->getNoWrapFlags(); 11333 return true; 11334 } 11335 11336 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 11337 const SCEV *Less) { 11338 // We avoid subtracting expressions here because this function is usually 11339 // fairly deep in the call stack (i.e. is called many times). 11340 11341 // X - X = 0. 11342 if (More == Less) 11343 return APInt(getTypeSizeInBits(More->getType()), 0); 11344 11345 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 11346 const auto *LAR = cast<SCEVAddRecExpr>(Less); 11347 const auto *MAR = cast<SCEVAddRecExpr>(More); 11348 11349 if (LAR->getLoop() != MAR->getLoop()) 11350 return None; 11351 11352 // We look at affine expressions only; not for correctness but to keep 11353 // getStepRecurrence cheap. 11354 if (!LAR->isAffine() || !MAR->isAffine()) 11355 return None; 11356 11357 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 11358 return None; 11359 11360 Less = LAR->getStart(); 11361 More = MAR->getStart(); 11362 11363 // fall through 11364 } 11365 11366 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 11367 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 11368 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 11369 return M - L; 11370 } 11371 11372 SCEV::NoWrapFlags Flags; 11373 const SCEV *LLess = nullptr, *RLess = nullptr; 11374 const SCEV *LMore = nullptr, *RMore = nullptr; 11375 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 11376 // Compare (X + C1) vs X. 11377 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 11378 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 11379 if (RLess == More) 11380 return -(C1->getAPInt()); 11381 11382 // Compare X vs (X + C2). 11383 if (splitBinaryAdd(More, LMore, RMore, Flags)) 11384 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 11385 if (RMore == Less) 11386 return C2->getAPInt(); 11387 11388 // Compare (X + C1) vs (X + C2). 11389 if (C1 && C2 && RLess == RMore) 11390 return C2->getAPInt() - C1->getAPInt(); 11391 11392 return None; 11393 } 11394 11395 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 11396 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 11397 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) { 11398 // Try to recognize the following pattern: 11399 // 11400 // FoundRHS = ... 11401 // ... 11402 // loop: 11403 // FoundLHS = {Start,+,W} 11404 // context_bb: // Basic block from the same loop 11405 // known(Pred, FoundLHS, FoundRHS) 11406 // 11407 // If some predicate is known in the context of a loop, it is also known on 11408 // each iteration of this loop, including the first iteration. Therefore, in 11409 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 11410 // prove the original pred using this fact. 11411 if (!CtxI) 11412 return false; 11413 const BasicBlock *ContextBB = CtxI->getParent(); 11414 // Make sure AR varies in the context block. 11415 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 11416 const Loop *L = AR->getLoop(); 11417 // Make sure that context belongs to the loop and executes on 1st iteration 11418 // (if it ever executes at all). 11419 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 11420 return false; 11421 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 11422 return false; 11423 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 11424 } 11425 11426 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 11427 const Loop *L = AR->getLoop(); 11428 // Make sure that context belongs to the loop and executes on 1st iteration 11429 // (if it ever executes at all). 11430 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 11431 return false; 11432 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 11433 return false; 11434 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 11435 } 11436 11437 return false; 11438 } 11439 11440 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 11441 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 11442 const SCEV *FoundLHS, const SCEV *FoundRHS) { 11443 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 11444 return false; 11445 11446 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 11447 if (!AddRecLHS) 11448 return false; 11449 11450 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 11451 if (!AddRecFoundLHS) 11452 return false; 11453 11454 // We'd like to let SCEV reason about control dependencies, so we constrain 11455 // both the inequalities to be about add recurrences on the same loop. This 11456 // way we can use isLoopEntryGuardedByCond later. 11457 11458 const Loop *L = AddRecFoundLHS->getLoop(); 11459 if (L != AddRecLHS->getLoop()) 11460 return false; 11461 11462 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 11463 // 11464 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 11465 // ... (2) 11466 // 11467 // Informal proof for (2), assuming (1) [*]: 11468 // 11469 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 11470 // 11471 // Then 11472 // 11473 // FoundLHS s< FoundRHS s< INT_MIN - C 11474 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 11475 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 11476 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 11477 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 11478 // <=> FoundLHS + C s< FoundRHS + C 11479 // 11480 // [*]: (1) can be proved by ruling out overflow. 11481 // 11482 // [**]: This can be proved by analyzing all the four possibilities: 11483 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 11484 // (A s>= 0, B s>= 0). 11485 // 11486 // Note: 11487 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 11488 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 11489 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 11490 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 11491 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 11492 // C)". 11493 11494 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 11495 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 11496 if (!LDiff || !RDiff || *LDiff != *RDiff) 11497 return false; 11498 11499 if (LDiff->isMinValue()) 11500 return true; 11501 11502 APInt FoundRHSLimit; 11503 11504 if (Pred == CmpInst::ICMP_ULT) { 11505 FoundRHSLimit = -(*RDiff); 11506 } else { 11507 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 11508 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 11509 } 11510 11511 // Try to prove (1) or (2), as needed. 11512 return isAvailableAtLoopEntry(FoundRHS, L) && 11513 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 11514 getConstant(FoundRHSLimit)); 11515 } 11516 11517 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 11518 const SCEV *LHS, const SCEV *RHS, 11519 const SCEV *FoundLHS, 11520 const SCEV *FoundRHS, unsigned Depth) { 11521 const PHINode *LPhi = nullptr, *RPhi = nullptr; 11522 11523 auto ClearOnExit = make_scope_exit([&]() { 11524 if (LPhi) { 11525 bool Erased = PendingMerges.erase(LPhi); 11526 assert(Erased && "Failed to erase LPhi!"); 11527 (void)Erased; 11528 } 11529 if (RPhi) { 11530 bool Erased = PendingMerges.erase(RPhi); 11531 assert(Erased && "Failed to erase RPhi!"); 11532 (void)Erased; 11533 } 11534 }); 11535 11536 // Find respective Phis and check that they are not being pending. 11537 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 11538 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 11539 if (!PendingMerges.insert(Phi).second) 11540 return false; 11541 LPhi = Phi; 11542 } 11543 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 11544 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 11545 // If we detect a loop of Phi nodes being processed by this method, for 11546 // example: 11547 // 11548 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 11549 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 11550 // 11551 // we don't want to deal with a case that complex, so return conservative 11552 // answer false. 11553 if (!PendingMerges.insert(Phi).second) 11554 return false; 11555 RPhi = Phi; 11556 } 11557 11558 // If none of LHS, RHS is a Phi, nothing to do here. 11559 if (!LPhi && !RPhi) 11560 return false; 11561 11562 // If there is a SCEVUnknown Phi we are interested in, make it left. 11563 if (!LPhi) { 11564 std::swap(LHS, RHS); 11565 std::swap(FoundLHS, FoundRHS); 11566 std::swap(LPhi, RPhi); 11567 Pred = ICmpInst::getSwappedPredicate(Pred); 11568 } 11569 11570 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 11571 const BasicBlock *LBB = LPhi->getParent(); 11572 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11573 11574 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 11575 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 11576 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 11577 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 11578 }; 11579 11580 if (RPhi && RPhi->getParent() == LBB) { 11581 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 11582 // If we compare two Phis from the same block, and for each entry block 11583 // the predicate is true for incoming values from this block, then the 11584 // predicate is also true for the Phis. 11585 for (const BasicBlock *IncBB : predecessors(LBB)) { 11586 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11587 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 11588 if (!ProvedEasily(L, R)) 11589 return false; 11590 } 11591 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 11592 // Case two: RHS is also a Phi from the same basic block, and it is an 11593 // AddRec. It means that there is a loop which has both AddRec and Unknown 11594 // PHIs, for it we can compare incoming values of AddRec from above the loop 11595 // and latch with their respective incoming values of LPhi. 11596 // TODO: Generalize to handle loops with many inputs in a header. 11597 if (LPhi->getNumIncomingValues() != 2) return false; 11598 11599 auto *RLoop = RAR->getLoop(); 11600 auto *Predecessor = RLoop->getLoopPredecessor(); 11601 assert(Predecessor && "Loop with AddRec with no predecessor?"); 11602 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 11603 if (!ProvedEasily(L1, RAR->getStart())) 11604 return false; 11605 auto *Latch = RLoop->getLoopLatch(); 11606 assert(Latch && "Loop with AddRec with no latch?"); 11607 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 11608 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 11609 return false; 11610 } else { 11611 // In all other cases go over inputs of LHS and compare each of them to RHS, 11612 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 11613 // At this point RHS is either a non-Phi, or it is a Phi from some block 11614 // different from LBB. 11615 for (const BasicBlock *IncBB : predecessors(LBB)) { 11616 // Check that RHS is available in this block. 11617 if (!dominates(RHS, IncBB)) 11618 return false; 11619 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11620 // Make sure L does not refer to a value from a potentially previous 11621 // iteration of a loop. 11622 if (!properlyDominates(L, IncBB)) 11623 return false; 11624 if (!ProvedEasily(L, RHS)) 11625 return false; 11626 } 11627 } 11628 return true; 11629 } 11630 11631 bool ScalarEvolution::isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred, 11632 const SCEV *LHS, 11633 const SCEV *RHS, 11634 const SCEV *FoundLHS, 11635 const SCEV *FoundRHS) { 11636 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make 11637 // sure that we are dealing with same LHS. 11638 if (RHS == FoundRHS) { 11639 std::swap(LHS, RHS); 11640 std::swap(FoundLHS, FoundRHS); 11641 Pred = ICmpInst::getSwappedPredicate(Pred); 11642 } 11643 if (LHS != FoundLHS) 11644 return false; 11645 11646 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS); 11647 if (!SUFoundRHS) 11648 return false; 11649 11650 Value *Shiftee, *ShiftValue; 11651 11652 using namespace PatternMatch; 11653 if (match(SUFoundRHS->getValue(), 11654 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) { 11655 auto *ShifteeS = getSCEV(Shiftee); 11656 // Prove one of the following: 11657 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS 11658 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS 11659 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0 11660 // ---> LHS <s RHS 11661 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0 11662 // ---> LHS <=s RHS 11663 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) 11664 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS); 11665 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) 11666 if (isKnownNonNegative(ShifteeS)) 11667 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS); 11668 } 11669 11670 return false; 11671 } 11672 11673 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 11674 const SCEV *LHS, const SCEV *RHS, 11675 const SCEV *FoundLHS, 11676 const SCEV *FoundRHS, 11677 const Instruction *CtxI) { 11678 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11679 return true; 11680 11681 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11682 return true; 11683 11684 if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11685 return true; 11686 11687 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 11688 CtxI)) 11689 return true; 11690 11691 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 11692 FoundLHS, FoundRHS); 11693 } 11694 11695 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 11696 template <typename MinMaxExprType> 11697 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 11698 const SCEV *Candidate) { 11699 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 11700 if (!MinMaxExpr) 11701 return false; 11702 11703 return is_contained(MinMaxExpr->operands(), Candidate); 11704 } 11705 11706 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 11707 ICmpInst::Predicate Pred, 11708 const SCEV *LHS, const SCEV *RHS) { 11709 // If both sides are affine addrecs for the same loop, with equal 11710 // steps, and we know the recurrences don't wrap, then we only 11711 // need to check the predicate on the starting values. 11712 11713 if (!ICmpInst::isRelational(Pred)) 11714 return false; 11715 11716 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 11717 if (!LAR) 11718 return false; 11719 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11720 if (!RAR) 11721 return false; 11722 if (LAR->getLoop() != RAR->getLoop()) 11723 return false; 11724 if (!LAR->isAffine() || !RAR->isAffine()) 11725 return false; 11726 11727 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 11728 return false; 11729 11730 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 11731 SCEV::FlagNSW : SCEV::FlagNUW; 11732 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 11733 return false; 11734 11735 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 11736 } 11737 11738 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 11739 /// expression? 11740 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 11741 ICmpInst::Predicate Pred, 11742 const SCEV *LHS, const SCEV *RHS) { 11743 switch (Pred) { 11744 default: 11745 return false; 11746 11747 case ICmpInst::ICMP_SGE: 11748 std::swap(LHS, RHS); 11749 LLVM_FALLTHROUGH; 11750 case ICmpInst::ICMP_SLE: 11751 return 11752 // min(A, ...) <= A 11753 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 11754 // A <= max(A, ...) 11755 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 11756 11757 case ICmpInst::ICMP_UGE: 11758 std::swap(LHS, RHS); 11759 LLVM_FALLTHROUGH; 11760 case ICmpInst::ICMP_ULE: 11761 return 11762 // min(A, ...) <= A 11763 // FIXME: what about umin_seq? 11764 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 11765 // A <= max(A, ...) 11766 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 11767 } 11768 11769 llvm_unreachable("covered switch fell through?!"); 11770 } 11771 11772 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 11773 const SCEV *LHS, const SCEV *RHS, 11774 const SCEV *FoundLHS, 11775 const SCEV *FoundRHS, 11776 unsigned Depth) { 11777 assert(getTypeSizeInBits(LHS->getType()) == 11778 getTypeSizeInBits(RHS->getType()) && 11779 "LHS and RHS have different sizes?"); 11780 assert(getTypeSizeInBits(FoundLHS->getType()) == 11781 getTypeSizeInBits(FoundRHS->getType()) && 11782 "FoundLHS and FoundRHS have different sizes?"); 11783 // We want to avoid hurting the compile time with analysis of too big trees. 11784 if (Depth > MaxSCEVOperationsImplicationDepth) 11785 return false; 11786 11787 // We only want to work with GT comparison so far. 11788 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 11789 Pred = CmpInst::getSwappedPredicate(Pred); 11790 std::swap(LHS, RHS); 11791 std::swap(FoundLHS, FoundRHS); 11792 } 11793 11794 // For unsigned, try to reduce it to corresponding signed comparison. 11795 if (Pred == ICmpInst::ICMP_UGT) 11796 // We can replace unsigned predicate with its signed counterpart if all 11797 // involved values are non-negative. 11798 // TODO: We could have better support for unsigned. 11799 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 11800 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 11801 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 11802 // use this fact to prove that LHS and RHS are non-negative. 11803 const SCEV *MinusOne = getMinusOne(LHS->getType()); 11804 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 11805 FoundRHS) && 11806 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 11807 FoundRHS)) 11808 Pred = ICmpInst::ICMP_SGT; 11809 } 11810 11811 if (Pred != ICmpInst::ICMP_SGT) 11812 return false; 11813 11814 auto GetOpFromSExt = [&](const SCEV *S) { 11815 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 11816 return Ext->getOperand(); 11817 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 11818 // the constant in some cases. 11819 return S; 11820 }; 11821 11822 // Acquire values from extensions. 11823 auto *OrigLHS = LHS; 11824 auto *OrigFoundLHS = FoundLHS; 11825 LHS = GetOpFromSExt(LHS); 11826 FoundLHS = GetOpFromSExt(FoundLHS); 11827 11828 // Is the SGT predicate can be proved trivially or using the found context. 11829 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 11830 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 11831 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 11832 FoundRHS, Depth + 1); 11833 }; 11834 11835 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 11836 // We want to avoid creation of any new non-constant SCEV. Since we are 11837 // going to compare the operands to RHS, we should be certain that we don't 11838 // need any size extensions for this. So let's decline all cases when the 11839 // sizes of types of LHS and RHS do not match. 11840 // TODO: Maybe try to get RHS from sext to catch more cases? 11841 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11842 return false; 11843 11844 // Should not overflow. 11845 if (!LHSAddExpr->hasNoSignedWrap()) 11846 return false; 11847 11848 auto *LL = LHSAddExpr->getOperand(0); 11849 auto *LR = LHSAddExpr->getOperand(1); 11850 auto *MinusOne = getMinusOne(RHS->getType()); 11851 11852 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11853 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11854 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11855 }; 11856 // Try to prove the following rule: 11857 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11858 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11859 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11860 return true; 11861 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11862 Value *LL, *LR; 11863 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11864 11865 using namespace llvm::PatternMatch; 11866 11867 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11868 // Rules for division. 11869 // We are going to perform some comparisons with Denominator and its 11870 // derivative expressions. In general case, creating a SCEV for it may 11871 // lead to a complex analysis of the entire graph, and in particular it 11872 // can request trip count recalculation for the same loop. This would 11873 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11874 // this, we only want to create SCEVs that are constants in this section. 11875 // So we bail if Denominator is not a constant. 11876 if (!isa<ConstantInt>(LR)) 11877 return false; 11878 11879 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11880 11881 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11882 // then a SCEV for the numerator already exists and matches with FoundLHS. 11883 auto *Numerator = getExistingSCEV(LL); 11884 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11885 return false; 11886 11887 // Make sure that the numerator matches with FoundLHS and the denominator 11888 // is positive. 11889 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11890 return false; 11891 11892 auto *DTy = Denominator->getType(); 11893 auto *FRHSTy = FoundRHS->getType(); 11894 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11895 // One of types is a pointer and another one is not. We cannot extend 11896 // them properly to a wider type, so let us just reject this case. 11897 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11898 // to avoid this check. 11899 return false; 11900 11901 // Given that: 11902 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11903 auto *WTy = getWiderType(DTy, FRHSTy); 11904 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11905 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11906 11907 // Try to prove the following rule: 11908 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11909 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11910 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11911 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11912 if (isKnownNonPositive(RHS) && 11913 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11914 return true; 11915 11916 // Try to prove the following rule: 11917 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11918 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11919 // If we divide it by Denominator > 2, then: 11920 // 1. If FoundLHS is negative, then the result is 0. 11921 // 2. If FoundLHS is non-negative, then the result is non-negative. 11922 // Anyways, the result is non-negative. 11923 auto *MinusOne = getMinusOne(WTy); 11924 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11925 if (isKnownNegative(RHS) && 11926 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11927 return true; 11928 } 11929 } 11930 11931 // If our expression contained SCEVUnknown Phis, and we split it down and now 11932 // need to prove something for them, try to prove the predicate for every 11933 // possible incoming values of those Phis. 11934 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11935 return true; 11936 11937 return false; 11938 } 11939 11940 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11941 const SCEV *LHS, const SCEV *RHS) { 11942 // zext x u<= sext x, sext x s<= zext x 11943 switch (Pred) { 11944 case ICmpInst::ICMP_SGE: 11945 std::swap(LHS, RHS); 11946 LLVM_FALLTHROUGH; 11947 case ICmpInst::ICMP_SLE: { 11948 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11949 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11950 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11951 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11952 return true; 11953 break; 11954 } 11955 case ICmpInst::ICMP_UGE: 11956 std::swap(LHS, RHS); 11957 LLVM_FALLTHROUGH; 11958 case ICmpInst::ICMP_ULE: { 11959 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11960 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11961 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11962 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11963 return true; 11964 break; 11965 } 11966 default: 11967 break; 11968 }; 11969 return false; 11970 } 11971 11972 bool 11973 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 11974 const SCEV *LHS, const SCEV *RHS) { 11975 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 11976 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 11977 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 11978 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 11979 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 11980 } 11981 11982 bool 11983 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 11984 const SCEV *LHS, const SCEV *RHS, 11985 const SCEV *FoundLHS, 11986 const SCEV *FoundRHS) { 11987 switch (Pred) { 11988 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 11989 case ICmpInst::ICMP_EQ: 11990 case ICmpInst::ICMP_NE: 11991 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 11992 return true; 11993 break; 11994 case ICmpInst::ICMP_SLT: 11995 case ICmpInst::ICMP_SLE: 11996 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 11997 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 11998 return true; 11999 break; 12000 case ICmpInst::ICMP_SGT: 12001 case ICmpInst::ICMP_SGE: 12002 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 12003 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 12004 return true; 12005 break; 12006 case ICmpInst::ICMP_ULT: 12007 case ICmpInst::ICMP_ULE: 12008 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 12009 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 12010 return true; 12011 break; 12012 case ICmpInst::ICMP_UGT: 12013 case ICmpInst::ICMP_UGE: 12014 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 12015 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 12016 return true; 12017 break; 12018 } 12019 12020 // Maybe it can be proved via operations? 12021 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 12022 return true; 12023 12024 return false; 12025 } 12026 12027 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 12028 const SCEV *LHS, 12029 const SCEV *RHS, 12030 const SCEV *FoundLHS, 12031 const SCEV *FoundRHS) { 12032 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 12033 // The restriction on `FoundRHS` be lifted easily -- it exists only to 12034 // reduce the compile time impact of this optimization. 12035 return false; 12036 12037 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 12038 if (!Addend) 12039 return false; 12040 12041 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 12042 12043 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 12044 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 12045 ConstantRange FoundLHSRange = 12046 ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS); 12047 12048 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 12049 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 12050 12051 // We can also compute the range of values for `LHS` that satisfy the 12052 // consequent, "`LHS` `Pred` `RHS`": 12053 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 12054 // The antecedent implies the consequent if every value of `LHS` that 12055 // satisfies the antecedent also satisfies the consequent. 12056 return LHSRange.icmp(Pred, ConstRHS); 12057 } 12058 12059 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 12060 bool IsSigned) { 12061 assert(isKnownPositive(Stride) && "Positive stride expected!"); 12062 12063 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 12064 const SCEV *One = getOne(Stride->getType()); 12065 12066 if (IsSigned) { 12067 APInt MaxRHS = getSignedRangeMax(RHS); 12068 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 12069 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 12070 12071 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 12072 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 12073 } 12074 12075 APInt MaxRHS = getUnsignedRangeMax(RHS); 12076 APInt MaxValue = APInt::getMaxValue(BitWidth); 12077 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 12078 12079 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 12080 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 12081 } 12082 12083 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 12084 bool IsSigned) { 12085 12086 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 12087 const SCEV *One = getOne(Stride->getType()); 12088 12089 if (IsSigned) { 12090 APInt MinRHS = getSignedRangeMin(RHS); 12091 APInt MinValue = APInt::getSignedMinValue(BitWidth); 12092 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 12093 12094 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 12095 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 12096 } 12097 12098 APInt MinRHS = getUnsignedRangeMin(RHS); 12099 APInt MinValue = APInt::getMinValue(BitWidth); 12100 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 12101 12102 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 12103 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 12104 } 12105 12106 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) { 12107 // umin(N, 1) + floor((N - umin(N, 1)) / D) 12108 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin 12109 // expression fixes the case of N=0. 12110 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType())); 12111 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne); 12112 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D)); 12113 } 12114 12115 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 12116 const SCEV *Stride, 12117 const SCEV *End, 12118 unsigned BitWidth, 12119 bool IsSigned) { 12120 // The logic in this function assumes we can represent a positive stride. 12121 // If we can't, the backedge-taken count must be zero. 12122 if (IsSigned && BitWidth == 1) 12123 return getZero(Stride->getType()); 12124 12125 // This code has only been closely audited for negative strides in the 12126 // unsigned comparison case, it may be correct for signed comparison, but 12127 // that needs to be established. 12128 assert((!IsSigned || !isKnownNonPositive(Stride)) && 12129 "Stride is expected strictly positive for signed case!"); 12130 12131 // Calculate the maximum backedge count based on the range of values 12132 // permitted by Start, End, and Stride. 12133 APInt MinStart = 12134 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 12135 12136 APInt MinStride = 12137 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 12138 12139 // We assume either the stride is positive, or the backedge-taken count 12140 // is zero. So force StrideForMaxBECount to be at least one. 12141 APInt One(BitWidth, 1); 12142 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride) 12143 : APIntOps::umax(One, MinStride); 12144 12145 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 12146 : APInt::getMaxValue(BitWidth); 12147 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 12148 12149 // Although End can be a MAX expression we estimate MaxEnd considering only 12150 // the case End = RHS of the loop termination condition. This is safe because 12151 // in the other case (End - Start) is zero, leading to a zero maximum backedge 12152 // taken count. 12153 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 12154 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 12155 12156 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride) 12157 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart) 12158 : APIntOps::umax(MaxEnd, MinStart); 12159 12160 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */, 12161 getConstant(StrideForMaxBECount) /* Step */); 12162 } 12163 12164 ScalarEvolution::ExitLimit 12165 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 12166 const Loop *L, bool IsSigned, 12167 bool ControlsExit, bool AllowPredicates) { 12168 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 12169 12170 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 12171 bool PredicatedIV = false; 12172 12173 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) { 12174 // Can we prove this loop *must* be UB if overflow of IV occurs? 12175 // Reasoning goes as follows: 12176 // * Suppose the IV did self wrap. 12177 // * If Stride evenly divides the iteration space, then once wrap 12178 // occurs, the loop must revisit the same values. 12179 // * We know that RHS is invariant, and that none of those values 12180 // caused this exit to be taken previously. Thus, this exit is 12181 // dynamically dead. 12182 // * If this is the sole exit, then a dead exit implies the loop 12183 // must be infinite if there are no abnormal exits. 12184 // * If the loop were infinite, then it must either not be mustprogress 12185 // or have side effects. Otherwise, it must be UB. 12186 // * It can't (by assumption), be UB so we have contradicted our 12187 // premise and can conclude the IV did not in fact self-wrap. 12188 if (!isLoopInvariant(RHS, L)) 12189 return false; 12190 12191 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 12192 if (!StrideC || !StrideC->getAPInt().isPowerOf2()) 12193 return false; 12194 12195 if (!ControlsExit || !loopHasNoAbnormalExits(L)) 12196 return false; 12197 12198 return loopIsFiniteByAssumption(L); 12199 }; 12200 12201 if (!IV) { 12202 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) { 12203 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand()); 12204 if (AR && AR->getLoop() == L && AR->isAffine()) { 12205 auto canProveNUW = [&]() { 12206 if (!isLoopInvariant(RHS, L)) 12207 return false; 12208 12209 if (!isKnownNonZero(AR->getStepRecurrence(*this))) 12210 // We need the sequence defined by AR to strictly increase in the 12211 // unsigned integer domain for the logic below to hold. 12212 return false; 12213 12214 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType()); 12215 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType()); 12216 // If RHS <=u Limit, then there must exist a value V in the sequence 12217 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and 12218 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned 12219 // overflow occurs. This limit also implies that a signed comparison 12220 // (in the wide bitwidth) is equivalent to an unsigned comparison as 12221 // the high bits on both sides must be zero. 12222 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this)); 12223 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1); 12224 Limit = Limit.zext(OuterBitWidth); 12225 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit); 12226 }; 12227 auto Flags = AR->getNoWrapFlags(); 12228 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW()) 12229 Flags = setFlags(Flags, SCEV::FlagNUW); 12230 12231 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 12232 if (AR->hasNoUnsignedWrap()) { 12233 // Emulate what getZeroExtendExpr would have done during construction 12234 // if we'd been able to infer the fact just above at that time. 12235 const SCEV *Step = AR->getStepRecurrence(*this); 12236 Type *Ty = ZExt->getType(); 12237 auto *S = getAddRecExpr( 12238 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0), 12239 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags()); 12240 IV = dyn_cast<SCEVAddRecExpr>(S); 12241 } 12242 } 12243 } 12244 } 12245 12246 12247 if (!IV && AllowPredicates) { 12248 // Try to make this an AddRec using runtime tests, in the first X 12249 // iterations of this loop, where X is the SCEV expression found by the 12250 // algorithm below. 12251 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12252 PredicatedIV = true; 12253 } 12254 12255 // Avoid weird loops 12256 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12257 return getCouldNotCompute(); 12258 12259 // A precondition of this method is that the condition being analyzed 12260 // reaches an exiting branch which dominates the latch. Given that, we can 12261 // assume that an increment which violates the nowrap specification and 12262 // produces poison must cause undefined behavior when the resulting poison 12263 // value is branched upon and thus we can conclude that the backedge is 12264 // taken no more often than would be required to produce that poison value. 12265 // Note that a well defined loop can exit on the iteration which violates 12266 // the nowrap specification if there is another exit (either explicit or 12267 // implicit/exceptional) which causes the loop to execute before the 12268 // exiting instruction we're analyzing would trigger UB. 12269 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12270 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12271 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 12272 12273 const SCEV *Stride = IV->getStepRecurrence(*this); 12274 12275 bool PositiveStride = isKnownPositive(Stride); 12276 12277 // Avoid negative or zero stride values. 12278 if (!PositiveStride) { 12279 // We can compute the correct backedge taken count for loops with unknown 12280 // strides if we can prove that the loop is not an infinite loop with side 12281 // effects. Here's the loop structure we are trying to handle - 12282 // 12283 // i = start 12284 // do { 12285 // A[i] = i; 12286 // i += s; 12287 // } while (i < end); 12288 // 12289 // The backedge taken count for such loops is evaluated as - 12290 // (max(end, start + stride) - start - 1) /u stride 12291 // 12292 // The additional preconditions that we need to check to prove correctness 12293 // of the above formula is as follows - 12294 // 12295 // a) IV is either nuw or nsw depending upon signedness (indicated by the 12296 // NoWrap flag). 12297 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has 12298 // no side effects within the loop) 12299 // c) loop has a single static exit (with no abnormal exits) 12300 // 12301 // Precondition a) implies that if the stride is negative, this is a single 12302 // trip loop. The backedge taken count formula reduces to zero in this case. 12303 // 12304 // Precondition b) and c) combine to imply that if rhs is invariant in L, 12305 // then a zero stride means the backedge can't be taken without executing 12306 // undefined behavior. 12307 // 12308 // The positive stride case is the same as isKnownPositive(Stride) returning 12309 // true (original behavior of the function). 12310 // 12311 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) || 12312 !loopHasNoAbnormalExits(L)) 12313 return getCouldNotCompute(); 12314 12315 // This bailout is protecting the logic in computeMaxBECountForLT which 12316 // has not yet been sufficiently auditted or tested with negative strides. 12317 // We used to filter out all known-non-positive cases here, we're in the 12318 // process of being less restrictive bit by bit. 12319 if (IsSigned && isKnownNonPositive(Stride)) 12320 return getCouldNotCompute(); 12321 12322 if (!isKnownNonZero(Stride)) { 12323 // If we have a step of zero, and RHS isn't invariant in L, we don't know 12324 // if it might eventually be greater than start and if so, on which 12325 // iteration. We can't even produce a useful upper bound. 12326 if (!isLoopInvariant(RHS, L)) 12327 return getCouldNotCompute(); 12328 12329 // We allow a potentially zero stride, but we need to divide by stride 12330 // below. Since the loop can't be infinite and this check must control 12331 // the sole exit, we can infer the exit must be taken on the first 12332 // iteration (e.g. backedge count = 0) if the stride is zero. Given that, 12333 // we know the numerator in the divides below must be zero, so we can 12334 // pick an arbitrary non-zero value for the denominator (e.g. stride) 12335 // and produce the right result. 12336 // FIXME: Handle the case where Stride is poison? 12337 auto wouldZeroStrideBeUB = [&]() { 12338 // Proof by contradiction. Suppose the stride were zero. If we can 12339 // prove that the backedge *is* taken on the first iteration, then since 12340 // we know this condition controls the sole exit, we must have an 12341 // infinite loop. We can't have a (well defined) infinite loop per 12342 // check just above. 12343 // Note: The (Start - Stride) term is used to get the start' term from 12344 // (start' + stride,+,stride). Remember that we only care about the 12345 // result of this expression when stride == 0 at runtime. 12346 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride); 12347 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS); 12348 }; 12349 if (!wouldZeroStrideBeUB()) { 12350 Stride = getUMaxExpr(Stride, getOne(Stride->getType())); 12351 } 12352 } 12353 } else if (!Stride->isOne() && !NoWrap) { 12354 auto isUBOnWrap = [&]() { 12355 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This 12356 // follows trivially from the fact that every (un)signed-wrapped, but 12357 // not self-wrapped value must be LT than the last value before 12358 // (un)signed wrap. Since we know that last value didn't exit, nor 12359 // will any smaller one. 12360 return canAssumeNoSelfWrap(IV); 12361 }; 12362 12363 // Avoid proven overflow cases: this will ensure that the backedge taken 12364 // count will not generate any unsigned overflow. Relaxed no-overflow 12365 // conditions exploit NoWrapFlags, allowing to optimize in presence of 12366 // undefined behaviors like the case of C language. 12367 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap()) 12368 return getCouldNotCompute(); 12369 } 12370 12371 // On all paths just preceeding, we established the following invariant: 12372 // IV can be assumed not to overflow up to and including the exiting 12373 // iteration. We proved this in one of two ways: 12374 // 1) We can show overflow doesn't occur before the exiting iteration 12375 // 1a) canIVOverflowOnLT, and b) step of one 12376 // 2) We can show that if overflow occurs, the loop must execute UB 12377 // before any possible exit. 12378 // Note that we have not yet proved RHS invariant (in general). 12379 12380 const SCEV *Start = IV->getStart(); 12381 12382 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond. 12383 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases. 12384 // Use integer-typed versions for actual computation; we can't subtract 12385 // pointers in general. 12386 const SCEV *OrigStart = Start; 12387 const SCEV *OrigRHS = RHS; 12388 if (Start->getType()->isPointerTy()) { 12389 Start = getLosslessPtrToIntExpr(Start); 12390 if (isa<SCEVCouldNotCompute>(Start)) 12391 return Start; 12392 } 12393 if (RHS->getType()->isPointerTy()) { 12394 RHS = getLosslessPtrToIntExpr(RHS); 12395 if (isa<SCEVCouldNotCompute>(RHS)) 12396 return RHS; 12397 } 12398 12399 // When the RHS is not invariant, we do not know the end bound of the loop and 12400 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 12401 // calculate the MaxBECount, given the start, stride and max value for the end 12402 // bound of the loop (RHS), and the fact that IV does not overflow (which is 12403 // checked above). 12404 if (!isLoopInvariant(RHS, L)) { 12405 const SCEV *MaxBECount = computeMaxBECountForLT( 12406 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 12407 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 12408 false /*MaxOrZero*/, Predicates); 12409 } 12410 12411 // We use the expression (max(End,Start)-Start)/Stride to describe the 12412 // backedge count, as if the backedge is taken at least once max(End,Start) 12413 // is End and so the result is as above, and if not max(End,Start) is Start 12414 // so we get a backedge count of zero. 12415 const SCEV *BECount = nullptr; 12416 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride); 12417 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!"); 12418 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!"); 12419 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!"); 12420 // Can we prove (max(RHS,Start) > Start - Stride? 12421 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) && 12422 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) { 12423 // In this case, we can use a refined formula for computing backedge taken 12424 // count. The general formula remains: 12425 // "End-Start /uceiling Stride" where "End = max(RHS,Start)" 12426 // We want to use the alternate formula: 12427 // "((End - 1) - (Start - Stride)) /u Stride" 12428 // Let's do a quick case analysis to show these are equivalent under 12429 // our precondition that max(RHS,Start) > Start - Stride. 12430 // * For RHS <= Start, the backedge-taken count must be zero. 12431 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 12432 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to 12433 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values 12434 // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing 12435 // this to the stride of 1 case. 12436 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride". 12437 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 12438 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to 12439 // "((RHS - (Start - Stride) - 1) /u Stride". 12440 // Our preconditions trivially imply no overflow in that form. 12441 const SCEV *MinusOne = getMinusOne(Stride->getType()); 12442 const SCEV *Numerator = 12443 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride)); 12444 BECount = getUDivExpr(Numerator, Stride); 12445 } 12446 12447 const SCEV *BECountIfBackedgeTaken = nullptr; 12448 if (!BECount) { 12449 auto canProveRHSGreaterThanEqualStart = [&]() { 12450 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 12451 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart)) 12452 return true; 12453 12454 // (RHS > Start - 1) implies RHS >= Start. 12455 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if 12456 // "Start - 1" doesn't overflow. 12457 // * For signed comparison, if Start - 1 does overflow, it's equal 12458 // to INT_MAX, and "RHS >s INT_MAX" is trivially false. 12459 // * For unsigned comparison, if Start - 1 does overflow, it's equal 12460 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false. 12461 // 12462 // FIXME: Should isLoopEntryGuardedByCond do this for us? 12463 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12464 auto *StartMinusOne = getAddExpr(OrigStart, 12465 getMinusOne(OrigStart->getType())); 12466 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne); 12467 }; 12468 12469 // If we know that RHS >= Start in the context of loop, then we know that 12470 // max(RHS, Start) = RHS at this point. 12471 const SCEV *End; 12472 if (canProveRHSGreaterThanEqualStart()) { 12473 End = RHS; 12474 } else { 12475 // If RHS < Start, the backedge will be taken zero times. So in 12476 // general, we can write the backedge-taken count as: 12477 // 12478 // RHS >= Start ? ceil(RHS - Start) / Stride : 0 12479 // 12480 // We convert it to the following to make it more convenient for SCEV: 12481 // 12482 // ceil(max(RHS, Start) - Start) / Stride 12483 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 12484 12485 // See what would happen if we assume the backedge is taken. This is 12486 // used to compute MaxBECount. 12487 BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride); 12488 } 12489 12490 // At this point, we know: 12491 // 12492 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End 12493 // 2. The index variable doesn't overflow. 12494 // 12495 // Therefore, we know N exists such that 12496 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)" 12497 // doesn't overflow. 12498 // 12499 // Using this information, try to prove whether the addition in 12500 // "(Start - End) + (Stride - 1)" has unsigned overflow. 12501 const SCEV *One = getOne(Stride->getType()); 12502 bool MayAddOverflow = [&] { 12503 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) { 12504 if (StrideC->getAPInt().isPowerOf2()) { 12505 // Suppose Stride is a power of two, and Start/End are unsigned 12506 // integers. Let UMAX be the largest representable unsigned 12507 // integer. 12508 // 12509 // By the preconditions of this function, we know 12510 // "(Start + Stride * N) >= End", and this doesn't overflow. 12511 // As a formula: 12512 // 12513 // End <= (Start + Stride * N) <= UMAX 12514 // 12515 // Subtracting Start from all the terms: 12516 // 12517 // End - Start <= Stride * N <= UMAX - Start 12518 // 12519 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore: 12520 // 12521 // End - Start <= Stride * N <= UMAX 12522 // 12523 // Stride * N is a multiple of Stride. Therefore, 12524 // 12525 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride) 12526 // 12527 // Since Stride is a power of two, UMAX + 1 is divisible by Stride. 12528 // Therefore, UMAX mod Stride == Stride - 1. So we can write: 12529 // 12530 // End - Start <= Stride * N <= UMAX - Stride - 1 12531 // 12532 // Dropping the middle term: 12533 // 12534 // End - Start <= UMAX - Stride - 1 12535 // 12536 // Adding Stride - 1 to both sides: 12537 // 12538 // (End - Start) + (Stride - 1) <= UMAX 12539 // 12540 // In other words, the addition doesn't have unsigned overflow. 12541 // 12542 // A similar proof works if we treat Start/End as signed values. 12543 // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to 12544 // use signed max instead of unsigned max. Note that we're trying 12545 // to prove a lack of unsigned overflow in either case. 12546 return false; 12547 } 12548 } 12549 if (Start == Stride || Start == getMinusSCEV(Stride, One)) { 12550 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1. 12551 // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End. 12552 // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End. 12553 // 12554 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End. 12555 return false; 12556 } 12557 return true; 12558 }(); 12559 12560 const SCEV *Delta = getMinusSCEV(End, Start); 12561 if (!MayAddOverflow) { 12562 // floor((D + (S - 1)) / S) 12563 // We prefer this formulation if it's legal because it's fewer operations. 12564 BECount = 12565 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride); 12566 } else { 12567 BECount = getUDivCeilSCEV(Delta, Stride); 12568 } 12569 } 12570 12571 const SCEV *MaxBECount; 12572 bool MaxOrZero = false; 12573 if (isa<SCEVConstant>(BECount)) { 12574 MaxBECount = BECount; 12575 } else if (BECountIfBackedgeTaken && 12576 isa<SCEVConstant>(BECountIfBackedgeTaken)) { 12577 // If we know exactly how many times the backedge will be taken if it's 12578 // taken at least once, then the backedge count will either be that or 12579 // zero. 12580 MaxBECount = BECountIfBackedgeTaken; 12581 MaxOrZero = true; 12582 } else { 12583 MaxBECount = computeMaxBECountForLT( 12584 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 12585 } 12586 12587 if (isa<SCEVCouldNotCompute>(MaxBECount) && 12588 !isa<SCEVCouldNotCompute>(BECount)) 12589 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 12590 12591 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 12592 } 12593 12594 ScalarEvolution::ExitLimit 12595 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 12596 const Loop *L, bool IsSigned, 12597 bool ControlsExit, bool AllowPredicates) { 12598 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 12599 // We handle only IV > Invariant 12600 if (!isLoopInvariant(RHS, L)) 12601 return getCouldNotCompute(); 12602 12603 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 12604 if (!IV && AllowPredicates) 12605 // Try to make this an AddRec using runtime tests, in the first X 12606 // iterations of this loop, where X is the SCEV expression found by the 12607 // algorithm below. 12608 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12609 12610 // Avoid weird loops 12611 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12612 return getCouldNotCompute(); 12613 12614 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12615 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12616 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12617 12618 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 12619 12620 // Avoid negative or zero stride values 12621 if (!isKnownPositive(Stride)) 12622 return getCouldNotCompute(); 12623 12624 // Avoid proven overflow cases: this will ensure that the backedge taken count 12625 // will not generate any unsigned overflow. Relaxed no-overflow conditions 12626 // exploit NoWrapFlags, allowing to optimize in presence of undefined 12627 // behaviors like the case of C language. 12628 if (!Stride->isOne() && !NoWrap) 12629 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 12630 return getCouldNotCompute(); 12631 12632 const SCEV *Start = IV->getStart(); 12633 const SCEV *End = RHS; 12634 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 12635 // If we know that Start >= RHS in the context of loop, then we know that 12636 // min(RHS, Start) = RHS at this point. 12637 if (isLoopEntryGuardedByCond( 12638 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 12639 End = RHS; 12640 else 12641 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 12642 } 12643 12644 if (Start->getType()->isPointerTy()) { 12645 Start = getLosslessPtrToIntExpr(Start); 12646 if (isa<SCEVCouldNotCompute>(Start)) 12647 return Start; 12648 } 12649 if (End->getType()->isPointerTy()) { 12650 End = getLosslessPtrToIntExpr(End); 12651 if (isa<SCEVCouldNotCompute>(End)) 12652 return End; 12653 } 12654 12655 // Compute ((Start - End) + (Stride - 1)) / Stride. 12656 // FIXME: This can overflow. Holding off on fixing this for now; 12657 // howManyGreaterThans will hopefully be gone soon. 12658 const SCEV *One = getOne(Stride->getType()); 12659 const SCEV *BECount = getUDivExpr( 12660 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride); 12661 12662 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 12663 : getUnsignedRangeMax(Start); 12664 12665 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 12666 : getUnsignedRangeMin(Stride); 12667 12668 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 12669 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 12670 : APInt::getMinValue(BitWidth) + (MinStride - 1); 12671 12672 // Although End can be a MIN expression we estimate MinEnd considering only 12673 // the case End = RHS. This is safe because in the other case (Start - End) 12674 // is zero, leading to a zero maximum backedge taken count. 12675 APInt MinEnd = 12676 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 12677 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 12678 12679 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 12680 ? BECount 12681 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd), 12682 getConstant(MinStride)); 12683 12684 if (isa<SCEVCouldNotCompute>(MaxBECount)) 12685 MaxBECount = BECount; 12686 12687 return ExitLimit(BECount, MaxBECount, false, Predicates); 12688 } 12689 12690 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 12691 ScalarEvolution &SE) const { 12692 if (Range.isFullSet()) // Infinite loop. 12693 return SE.getCouldNotCompute(); 12694 12695 // If the start is a non-zero constant, shift the range to simplify things. 12696 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 12697 if (!SC->getValue()->isZero()) { 12698 SmallVector<const SCEV *, 4> Operands(operands()); 12699 Operands[0] = SE.getZero(SC->getType()); 12700 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 12701 getNoWrapFlags(FlagNW)); 12702 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 12703 return ShiftedAddRec->getNumIterationsInRange( 12704 Range.subtract(SC->getAPInt()), SE); 12705 // This is strange and shouldn't happen. 12706 return SE.getCouldNotCompute(); 12707 } 12708 12709 // The only time we can solve this is when we have all constant indices. 12710 // Otherwise, we cannot determine the overflow conditions. 12711 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 12712 return SE.getCouldNotCompute(); 12713 12714 // Okay at this point we know that all elements of the chrec are constants and 12715 // that the start element is zero. 12716 12717 // First check to see if the range contains zero. If not, the first 12718 // iteration exits. 12719 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 12720 if (!Range.contains(APInt(BitWidth, 0))) 12721 return SE.getZero(getType()); 12722 12723 if (isAffine()) { 12724 // If this is an affine expression then we have this situation: 12725 // Solve {0,+,A} in Range === Ax in Range 12726 12727 // We know that zero is in the range. If A is positive then we know that 12728 // the upper value of the range must be the first possible exit value. 12729 // If A is negative then the lower of the range is the last possible loop 12730 // value. Also note that we already checked for a full range. 12731 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 12732 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 12733 12734 // The exit value should be (End+A)/A. 12735 APInt ExitVal = (End + A).udiv(A); 12736 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 12737 12738 // Evaluate at the exit value. If we really did fall out of the valid 12739 // range, then we computed our trip count, otherwise wrap around or other 12740 // things must have happened. 12741 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 12742 if (Range.contains(Val->getValue())) 12743 return SE.getCouldNotCompute(); // Something strange happened 12744 12745 // Ensure that the previous value is in the range. 12746 assert(Range.contains( 12747 EvaluateConstantChrecAtConstant(this, 12748 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 12749 "Linear scev computation is off in a bad way!"); 12750 return SE.getConstant(ExitValue); 12751 } 12752 12753 if (isQuadratic()) { 12754 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 12755 return SE.getConstant(S.getValue()); 12756 } 12757 12758 return SE.getCouldNotCompute(); 12759 } 12760 12761 const SCEVAddRecExpr * 12762 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 12763 assert(getNumOperands() > 1 && "AddRec with zero step?"); 12764 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 12765 // but in this case we cannot guarantee that the value returned will be an 12766 // AddRec because SCEV does not have a fixed point where it stops 12767 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 12768 // may happen if we reach arithmetic depth limit while simplifying. So we 12769 // construct the returned value explicitly. 12770 SmallVector<const SCEV *, 3> Ops; 12771 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 12772 // (this + Step) is {A+B,+,B+C,+...,+,N}. 12773 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 12774 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 12775 // We know that the last operand is not a constant zero (otherwise it would 12776 // have been popped out earlier). This guarantees us that if the result has 12777 // the same last operand, then it will also not be popped out, meaning that 12778 // the returned value will be an AddRec. 12779 const SCEV *Last = getOperand(getNumOperands() - 1); 12780 assert(!Last->isZero() && "Recurrency with zero step?"); 12781 Ops.push_back(Last); 12782 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 12783 SCEV::FlagAnyWrap)); 12784 } 12785 12786 // Return true when S contains at least an undef value. 12787 bool ScalarEvolution::containsUndefs(const SCEV *S) const { 12788 return SCEVExprContains(S, [](const SCEV *S) { 12789 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 12790 return isa<UndefValue>(SU->getValue()); 12791 return false; 12792 }); 12793 } 12794 12795 // Return true when S contains a value that is a nullptr. 12796 bool ScalarEvolution::containsErasedValue(const SCEV *S) const { 12797 return SCEVExprContains(S, [](const SCEV *S) { 12798 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 12799 return SU->getValue() == nullptr; 12800 return false; 12801 }); 12802 } 12803 12804 /// Return the size of an element read or written by Inst. 12805 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 12806 Type *Ty; 12807 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 12808 Ty = Store->getValueOperand()->getType(); 12809 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 12810 Ty = Load->getType(); 12811 else 12812 return nullptr; 12813 12814 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 12815 return getSizeOfExpr(ETy, Ty); 12816 } 12817 12818 //===----------------------------------------------------------------------===// 12819 // SCEVCallbackVH Class Implementation 12820 //===----------------------------------------------------------------------===// 12821 12822 void ScalarEvolution::SCEVCallbackVH::deleted() { 12823 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12824 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12825 SE->ConstantEvolutionLoopExitValue.erase(PN); 12826 SE->eraseValueFromMap(getValPtr()); 12827 // this now dangles! 12828 } 12829 12830 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12831 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12832 12833 // Forget all the expressions associated with users of the old value, 12834 // so that future queries will recompute the expressions using the new 12835 // value. 12836 Value *Old = getValPtr(); 12837 SmallVector<User *, 16> Worklist(Old->users()); 12838 SmallPtrSet<User *, 8> Visited; 12839 while (!Worklist.empty()) { 12840 User *U = Worklist.pop_back_val(); 12841 // Deleting the Old value will cause this to dangle. Postpone 12842 // that until everything else is done. 12843 if (U == Old) 12844 continue; 12845 if (!Visited.insert(U).second) 12846 continue; 12847 if (PHINode *PN = dyn_cast<PHINode>(U)) 12848 SE->ConstantEvolutionLoopExitValue.erase(PN); 12849 SE->eraseValueFromMap(U); 12850 llvm::append_range(Worklist, U->users()); 12851 } 12852 // Delete the Old value. 12853 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12854 SE->ConstantEvolutionLoopExitValue.erase(PN); 12855 SE->eraseValueFromMap(Old); 12856 // this now dangles! 12857 } 12858 12859 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12860 : CallbackVH(V), SE(se) {} 12861 12862 //===----------------------------------------------------------------------===// 12863 // ScalarEvolution Class Implementation 12864 //===----------------------------------------------------------------------===// 12865 12866 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12867 AssumptionCache &AC, DominatorTree &DT, 12868 LoopInfo &LI) 12869 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12870 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12871 LoopDispositions(64), BlockDispositions(64) { 12872 // To use guards for proving predicates, we need to scan every instruction in 12873 // relevant basic blocks, and not just terminators. Doing this is a waste of 12874 // time if the IR does not actually contain any calls to 12875 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12876 // 12877 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12878 // to _add_ guards to the module when there weren't any before, and wants 12879 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12880 // efficient in lieu of being smart in that rather obscure case. 12881 12882 auto *GuardDecl = F.getParent()->getFunction( 12883 Intrinsic::getName(Intrinsic::experimental_guard)); 12884 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12885 } 12886 12887 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12888 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12889 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12890 ValueExprMap(std::move(Arg.ValueExprMap)), 12891 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12892 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12893 PendingMerges(std::move(Arg.PendingMerges)), 12894 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12895 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12896 PredicatedBackedgeTakenCounts( 12897 std::move(Arg.PredicatedBackedgeTakenCounts)), 12898 BECountUsers(std::move(Arg.BECountUsers)), 12899 ConstantEvolutionLoopExitValue( 12900 std::move(Arg.ConstantEvolutionLoopExitValue)), 12901 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12902 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)), 12903 LoopDispositions(std::move(Arg.LoopDispositions)), 12904 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12905 BlockDispositions(std::move(Arg.BlockDispositions)), 12906 SCEVUsers(std::move(Arg.SCEVUsers)), 12907 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12908 SignedRanges(std::move(Arg.SignedRanges)), 12909 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12910 UniquePreds(std::move(Arg.UniquePreds)), 12911 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12912 LoopUsers(std::move(Arg.LoopUsers)), 12913 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12914 FirstUnknown(Arg.FirstUnknown) { 12915 Arg.FirstUnknown = nullptr; 12916 } 12917 12918 ScalarEvolution::~ScalarEvolution() { 12919 // Iterate through all the SCEVUnknown instances and call their 12920 // destructors, so that they release their references to their values. 12921 for (SCEVUnknown *U = FirstUnknown; U;) { 12922 SCEVUnknown *Tmp = U; 12923 U = U->Next; 12924 Tmp->~SCEVUnknown(); 12925 } 12926 FirstUnknown = nullptr; 12927 12928 ExprValueMap.clear(); 12929 ValueExprMap.clear(); 12930 HasRecMap.clear(); 12931 BackedgeTakenCounts.clear(); 12932 PredicatedBackedgeTakenCounts.clear(); 12933 12934 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12935 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12936 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12937 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12938 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12939 } 12940 12941 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12942 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12943 } 12944 12945 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12946 const Loop *L) { 12947 // Print all inner loops first 12948 for (Loop *I : *L) 12949 PrintLoopInfo(OS, SE, I); 12950 12951 OS << "Loop "; 12952 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12953 OS << ": "; 12954 12955 SmallVector<BasicBlock *, 8> ExitingBlocks; 12956 L->getExitingBlocks(ExitingBlocks); 12957 if (ExitingBlocks.size() != 1) 12958 OS << "<multiple exits> "; 12959 12960 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12961 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12962 else 12963 OS << "Unpredictable backedge-taken count.\n"; 12964 12965 if (ExitingBlocks.size() > 1) 12966 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12967 OS << " exit count for " << ExitingBlock->getName() << ": " 12968 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12969 } 12970 12971 OS << "Loop "; 12972 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12973 OS << ": "; 12974 12975 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12976 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12977 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12978 OS << ", actual taken count either this or zero."; 12979 } else { 12980 OS << "Unpredictable max backedge-taken count. "; 12981 } 12982 12983 OS << "\n" 12984 "Loop "; 12985 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12986 OS << ": "; 12987 12988 SmallVector<const SCEVPredicate *, 4> Preds; 12989 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Preds); 12990 if (!isa<SCEVCouldNotCompute>(PBT)) { 12991 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12992 OS << " Predicates:\n"; 12993 for (auto *P : Preds) 12994 P->print(OS, 4); 12995 } else { 12996 OS << "Unpredictable predicated backedge-taken count. "; 12997 } 12998 OS << "\n"; 12999 13000 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 13001 OS << "Loop "; 13002 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 13003 OS << ": "; 13004 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 13005 } 13006 } 13007 13008 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 13009 switch (LD) { 13010 case ScalarEvolution::LoopVariant: 13011 return "Variant"; 13012 case ScalarEvolution::LoopInvariant: 13013 return "Invariant"; 13014 case ScalarEvolution::LoopComputable: 13015 return "Computable"; 13016 } 13017 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 13018 } 13019 13020 void ScalarEvolution::print(raw_ostream &OS) const { 13021 // ScalarEvolution's implementation of the print method is to print 13022 // out SCEV values of all instructions that are interesting. Doing 13023 // this potentially causes it to create new SCEV objects though, 13024 // which technically conflicts with the const qualifier. This isn't 13025 // observable from outside the class though, so casting away the 13026 // const isn't dangerous. 13027 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 13028 13029 if (ClassifyExpressions) { 13030 OS << "Classifying expressions for: "; 13031 F.printAsOperand(OS, /*PrintType=*/false); 13032 OS << "\n"; 13033 for (Instruction &I : instructions(F)) 13034 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 13035 OS << I << '\n'; 13036 OS << " --> "; 13037 const SCEV *SV = SE.getSCEV(&I); 13038 SV->print(OS); 13039 if (!isa<SCEVCouldNotCompute>(SV)) { 13040 OS << " U: "; 13041 SE.getUnsignedRange(SV).print(OS); 13042 OS << " S: "; 13043 SE.getSignedRange(SV).print(OS); 13044 } 13045 13046 const Loop *L = LI.getLoopFor(I.getParent()); 13047 13048 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 13049 if (AtUse != SV) { 13050 OS << " --> "; 13051 AtUse->print(OS); 13052 if (!isa<SCEVCouldNotCompute>(AtUse)) { 13053 OS << " U: "; 13054 SE.getUnsignedRange(AtUse).print(OS); 13055 OS << " S: "; 13056 SE.getSignedRange(AtUse).print(OS); 13057 } 13058 } 13059 13060 if (L) { 13061 OS << "\t\t" "Exits: "; 13062 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 13063 if (!SE.isLoopInvariant(ExitValue, L)) { 13064 OS << "<<Unknown>>"; 13065 } else { 13066 OS << *ExitValue; 13067 } 13068 13069 bool First = true; 13070 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 13071 if (First) { 13072 OS << "\t\t" "LoopDispositions: { "; 13073 First = false; 13074 } else { 13075 OS << ", "; 13076 } 13077 13078 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 13079 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 13080 } 13081 13082 for (auto *InnerL : depth_first(L)) { 13083 if (InnerL == L) 13084 continue; 13085 if (First) { 13086 OS << "\t\t" "LoopDispositions: { "; 13087 First = false; 13088 } else { 13089 OS << ", "; 13090 } 13091 13092 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 13093 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 13094 } 13095 13096 OS << " }"; 13097 } 13098 13099 OS << "\n"; 13100 } 13101 } 13102 13103 OS << "Determining loop execution counts for: "; 13104 F.printAsOperand(OS, /*PrintType=*/false); 13105 OS << "\n"; 13106 for (Loop *I : LI) 13107 PrintLoopInfo(OS, &SE, I); 13108 } 13109 13110 ScalarEvolution::LoopDisposition 13111 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 13112 auto &Values = LoopDispositions[S]; 13113 for (auto &V : Values) { 13114 if (V.getPointer() == L) 13115 return V.getInt(); 13116 } 13117 Values.emplace_back(L, LoopVariant); 13118 LoopDisposition D = computeLoopDisposition(S, L); 13119 auto &Values2 = LoopDispositions[S]; 13120 for (auto &V : llvm::reverse(Values2)) { 13121 if (V.getPointer() == L) { 13122 V.setInt(D); 13123 break; 13124 } 13125 } 13126 return D; 13127 } 13128 13129 ScalarEvolution::LoopDisposition 13130 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 13131 switch (S->getSCEVType()) { 13132 case scConstant: 13133 return LoopInvariant; 13134 case scPtrToInt: 13135 case scTruncate: 13136 case scZeroExtend: 13137 case scSignExtend: 13138 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 13139 case scAddRecExpr: { 13140 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 13141 13142 // If L is the addrec's loop, it's computable. 13143 if (AR->getLoop() == L) 13144 return LoopComputable; 13145 13146 // Add recurrences are never invariant in the function-body (null loop). 13147 if (!L) 13148 return LoopVariant; 13149 13150 // Everything that is not defined at loop entry is variant. 13151 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 13152 return LoopVariant; 13153 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 13154 " dominate the contained loop's header?"); 13155 13156 // This recurrence is invariant w.r.t. L if AR's loop contains L. 13157 if (AR->getLoop()->contains(L)) 13158 return LoopInvariant; 13159 13160 // This recurrence is variant w.r.t. L if any of its operands 13161 // are variant. 13162 for (auto *Op : AR->operands()) 13163 if (!isLoopInvariant(Op, L)) 13164 return LoopVariant; 13165 13166 // Otherwise it's loop-invariant. 13167 return LoopInvariant; 13168 } 13169 case scAddExpr: 13170 case scMulExpr: 13171 case scUMaxExpr: 13172 case scSMaxExpr: 13173 case scUMinExpr: 13174 case scSMinExpr: 13175 case scSequentialUMinExpr: { 13176 bool HasVarying = false; 13177 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 13178 LoopDisposition D = getLoopDisposition(Op, L); 13179 if (D == LoopVariant) 13180 return LoopVariant; 13181 if (D == LoopComputable) 13182 HasVarying = true; 13183 } 13184 return HasVarying ? LoopComputable : LoopInvariant; 13185 } 13186 case scUDivExpr: { 13187 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 13188 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 13189 if (LD == LoopVariant) 13190 return LoopVariant; 13191 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 13192 if (RD == LoopVariant) 13193 return LoopVariant; 13194 return (LD == LoopInvariant && RD == LoopInvariant) ? 13195 LoopInvariant : LoopComputable; 13196 } 13197 case scUnknown: 13198 // All non-instruction values are loop invariant. All instructions are loop 13199 // invariant if they are not contained in the specified loop. 13200 // Instructions are never considered invariant in the function body 13201 // (null loop) because they are defined within the "loop". 13202 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 13203 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 13204 return LoopInvariant; 13205 case scCouldNotCompute: 13206 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 13207 } 13208 llvm_unreachable("Unknown SCEV kind!"); 13209 } 13210 13211 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 13212 return getLoopDisposition(S, L) == LoopInvariant; 13213 } 13214 13215 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 13216 return getLoopDisposition(S, L) == LoopComputable; 13217 } 13218 13219 ScalarEvolution::BlockDisposition 13220 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 13221 auto &Values = BlockDispositions[S]; 13222 for (auto &V : Values) { 13223 if (V.getPointer() == BB) 13224 return V.getInt(); 13225 } 13226 Values.emplace_back(BB, DoesNotDominateBlock); 13227 BlockDisposition D = computeBlockDisposition(S, BB); 13228 auto &Values2 = BlockDispositions[S]; 13229 for (auto &V : llvm::reverse(Values2)) { 13230 if (V.getPointer() == BB) { 13231 V.setInt(D); 13232 break; 13233 } 13234 } 13235 return D; 13236 } 13237 13238 ScalarEvolution::BlockDisposition 13239 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 13240 switch (S->getSCEVType()) { 13241 case scConstant: 13242 return ProperlyDominatesBlock; 13243 case scPtrToInt: 13244 case scTruncate: 13245 case scZeroExtend: 13246 case scSignExtend: 13247 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 13248 case scAddRecExpr: { 13249 // This uses a "dominates" query instead of "properly dominates" query 13250 // to test for proper dominance too, because the instruction which 13251 // produces the addrec's value is a PHI, and a PHI effectively properly 13252 // dominates its entire containing block. 13253 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 13254 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 13255 return DoesNotDominateBlock; 13256 13257 // Fall through into SCEVNAryExpr handling. 13258 LLVM_FALLTHROUGH; 13259 } 13260 case scAddExpr: 13261 case scMulExpr: 13262 case scUMaxExpr: 13263 case scSMaxExpr: 13264 case scUMinExpr: 13265 case scSMinExpr: 13266 case scSequentialUMinExpr: { 13267 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 13268 bool Proper = true; 13269 for (const SCEV *NAryOp : NAry->operands()) { 13270 BlockDisposition D = getBlockDisposition(NAryOp, BB); 13271 if (D == DoesNotDominateBlock) 13272 return DoesNotDominateBlock; 13273 if (D == DominatesBlock) 13274 Proper = false; 13275 } 13276 return Proper ? ProperlyDominatesBlock : DominatesBlock; 13277 } 13278 case scUDivExpr: { 13279 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 13280 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 13281 BlockDisposition LD = getBlockDisposition(LHS, BB); 13282 if (LD == DoesNotDominateBlock) 13283 return DoesNotDominateBlock; 13284 BlockDisposition RD = getBlockDisposition(RHS, BB); 13285 if (RD == DoesNotDominateBlock) 13286 return DoesNotDominateBlock; 13287 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 13288 ProperlyDominatesBlock : DominatesBlock; 13289 } 13290 case scUnknown: 13291 if (Instruction *I = 13292 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 13293 if (I->getParent() == BB) 13294 return DominatesBlock; 13295 if (DT.properlyDominates(I->getParent(), BB)) 13296 return ProperlyDominatesBlock; 13297 return DoesNotDominateBlock; 13298 } 13299 return ProperlyDominatesBlock; 13300 case scCouldNotCompute: 13301 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 13302 } 13303 llvm_unreachable("Unknown SCEV kind!"); 13304 } 13305 13306 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 13307 return getBlockDisposition(S, BB) >= DominatesBlock; 13308 } 13309 13310 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 13311 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 13312 } 13313 13314 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 13315 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 13316 } 13317 13318 void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L, 13319 bool Predicated) { 13320 auto &BECounts = 13321 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts; 13322 auto It = BECounts.find(L); 13323 if (It != BECounts.end()) { 13324 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) { 13325 if (!isa<SCEVConstant>(ENT.ExactNotTaken)) { 13326 auto UserIt = BECountUsers.find(ENT.ExactNotTaken); 13327 assert(UserIt != BECountUsers.end()); 13328 UserIt->second.erase({L, Predicated}); 13329 } 13330 } 13331 BECounts.erase(It); 13332 } 13333 } 13334 13335 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) { 13336 SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end()); 13337 SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end()); 13338 13339 while (!Worklist.empty()) { 13340 const SCEV *Curr = Worklist.pop_back_val(); 13341 auto Users = SCEVUsers.find(Curr); 13342 if (Users != SCEVUsers.end()) 13343 for (auto *User : Users->second) 13344 if (ToForget.insert(User).second) 13345 Worklist.push_back(User); 13346 } 13347 13348 for (auto *S : ToForget) 13349 forgetMemoizedResultsImpl(S); 13350 13351 for (auto I = PredicatedSCEVRewrites.begin(); 13352 I != PredicatedSCEVRewrites.end();) { 13353 std::pair<const SCEV *, const Loop *> Entry = I->first; 13354 if (ToForget.count(Entry.first)) 13355 PredicatedSCEVRewrites.erase(I++); 13356 else 13357 ++I; 13358 } 13359 } 13360 13361 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) { 13362 LoopDispositions.erase(S); 13363 BlockDispositions.erase(S); 13364 UnsignedRanges.erase(S); 13365 SignedRanges.erase(S); 13366 HasRecMap.erase(S); 13367 MinTrailingZerosCache.erase(S); 13368 13369 auto ExprIt = ExprValueMap.find(S); 13370 if (ExprIt != ExprValueMap.end()) { 13371 for (Value *V : ExprIt->second) { 13372 auto ValueIt = ValueExprMap.find_as(V); 13373 if (ValueIt != ValueExprMap.end()) 13374 ValueExprMap.erase(ValueIt); 13375 } 13376 ExprValueMap.erase(ExprIt); 13377 } 13378 13379 auto ScopeIt = ValuesAtScopes.find(S); 13380 if (ScopeIt != ValuesAtScopes.end()) { 13381 for (const auto &Pair : ScopeIt->second) 13382 if (!isa_and_nonnull<SCEVConstant>(Pair.second)) 13383 erase_value(ValuesAtScopesUsers[Pair.second], 13384 std::make_pair(Pair.first, S)); 13385 ValuesAtScopes.erase(ScopeIt); 13386 } 13387 13388 auto ScopeUserIt = ValuesAtScopesUsers.find(S); 13389 if (ScopeUserIt != ValuesAtScopesUsers.end()) { 13390 for (const auto &Pair : ScopeUserIt->second) 13391 erase_value(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S)); 13392 ValuesAtScopesUsers.erase(ScopeUserIt); 13393 } 13394 13395 auto BEUsersIt = BECountUsers.find(S); 13396 if (BEUsersIt != BECountUsers.end()) { 13397 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original. 13398 auto Copy = BEUsersIt->second; 13399 for (const auto &Pair : Copy) 13400 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt()); 13401 BECountUsers.erase(BEUsersIt); 13402 } 13403 } 13404 13405 void 13406 ScalarEvolution::getUsedLoops(const SCEV *S, 13407 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 13408 struct FindUsedLoops { 13409 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 13410 : LoopsUsed(LoopsUsed) {} 13411 SmallPtrSetImpl<const Loop *> &LoopsUsed; 13412 bool follow(const SCEV *S) { 13413 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 13414 LoopsUsed.insert(AR->getLoop()); 13415 return true; 13416 } 13417 13418 bool isDone() const { return false; } 13419 }; 13420 13421 FindUsedLoops F(LoopsUsed); 13422 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 13423 } 13424 13425 void ScalarEvolution::getReachableBlocks( 13426 SmallPtrSetImpl<BasicBlock *> &Reachable, Function &F) { 13427 SmallVector<BasicBlock *> Worklist; 13428 Worklist.push_back(&F.getEntryBlock()); 13429 while (!Worklist.empty()) { 13430 BasicBlock *BB = Worklist.pop_back_val(); 13431 if (!Reachable.insert(BB).second) 13432 continue; 13433 13434 Value *Cond; 13435 BasicBlock *TrueBB, *FalseBB; 13436 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB), 13437 m_BasicBlock(FalseBB)))) { 13438 if (auto *C = dyn_cast<ConstantInt>(Cond)) { 13439 Worklist.push_back(C->isOne() ? TrueBB : FalseBB); 13440 continue; 13441 } 13442 13443 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 13444 const SCEV *L = getSCEV(Cmp->getOperand(0)); 13445 const SCEV *R = getSCEV(Cmp->getOperand(1)); 13446 if (isKnownPredicateViaConstantRanges(Cmp->getPredicate(), L, R)) { 13447 Worklist.push_back(TrueBB); 13448 continue; 13449 } 13450 if (isKnownPredicateViaConstantRanges(Cmp->getInversePredicate(), L, 13451 R)) { 13452 Worklist.push_back(FalseBB); 13453 continue; 13454 } 13455 } 13456 } 13457 13458 append_range(Worklist, successors(BB)); 13459 } 13460 } 13461 13462 void ScalarEvolution::verify() const { 13463 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 13464 ScalarEvolution SE2(F, TLI, AC, DT, LI); 13465 13466 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 13467 13468 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 13469 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 13470 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 13471 13472 const SCEV *visitConstant(const SCEVConstant *Constant) { 13473 return SE.getConstant(Constant->getAPInt()); 13474 } 13475 13476 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13477 return SE.getUnknown(Expr->getValue()); 13478 } 13479 13480 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 13481 return SE.getCouldNotCompute(); 13482 } 13483 }; 13484 13485 SCEVMapper SCM(SE2); 13486 SmallPtrSet<BasicBlock *, 16> ReachableBlocks; 13487 SE2.getReachableBlocks(ReachableBlocks, F); 13488 13489 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * { 13490 if (containsUndefs(Old) || containsUndefs(New)) { 13491 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 13492 // not propagate undef aggressively). This means we can (and do) fail 13493 // verification in cases where a transform makes a value go from "undef" 13494 // to "undef+1" (say). The transform is fine, since in both cases the 13495 // result is "undef", but SCEV thinks the value increased by 1. 13496 return nullptr; 13497 } 13498 13499 // Unless VerifySCEVStrict is set, we only compare constant deltas. 13500 const SCEV *Delta = SE2.getMinusSCEV(Old, New); 13501 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta)) 13502 return nullptr; 13503 13504 return Delta; 13505 }; 13506 13507 while (!LoopStack.empty()) { 13508 auto *L = LoopStack.pop_back_val(); 13509 llvm::append_range(LoopStack, *L); 13510 13511 // Only verify BECounts in reachable loops. For an unreachable loop, 13512 // any BECount is legal. 13513 if (!ReachableBlocks.contains(L->getHeader())) 13514 continue; 13515 13516 // Only verify cached BECounts. Computing new BECounts may change the 13517 // results of subsequent SCEV uses. 13518 auto It = BackedgeTakenCounts.find(L); 13519 if (It == BackedgeTakenCounts.end()) 13520 continue; 13521 13522 auto *CurBECount = 13523 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this))); 13524 auto *NewBECount = SE2.getBackedgeTakenCount(L); 13525 13526 if (CurBECount == SE2.getCouldNotCompute() || 13527 NewBECount == SE2.getCouldNotCompute()) { 13528 // NB! This situation is legal, but is very suspicious -- whatever pass 13529 // change the loop to make a trip count go from could not compute to 13530 // computable or vice-versa *should have* invalidated SCEV. However, we 13531 // choose not to assert here (for now) since we don't want false 13532 // positives. 13533 continue; 13534 } 13535 13536 if (SE.getTypeSizeInBits(CurBECount->getType()) > 13537 SE.getTypeSizeInBits(NewBECount->getType())) 13538 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 13539 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 13540 SE.getTypeSizeInBits(NewBECount->getType())) 13541 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 13542 13543 const SCEV *Delta = GetDelta(CurBECount, NewBECount); 13544 if (Delta && !Delta->isZero()) { 13545 dbgs() << "Trip Count for " << *L << " Changed!\n"; 13546 dbgs() << "Old: " << *CurBECount << "\n"; 13547 dbgs() << "New: " << *NewBECount << "\n"; 13548 dbgs() << "Delta: " << *Delta << "\n"; 13549 std::abort(); 13550 } 13551 } 13552 13553 // Collect all valid loops currently in LoopInfo. 13554 SmallPtrSet<Loop *, 32> ValidLoops; 13555 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 13556 while (!Worklist.empty()) { 13557 Loop *L = Worklist.pop_back_val(); 13558 if (ValidLoops.insert(L).second) 13559 Worklist.append(L->begin(), L->end()); 13560 } 13561 for (auto &KV : ValueExprMap) { 13562 #ifndef NDEBUG 13563 // Check for SCEV expressions referencing invalid/deleted loops. 13564 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) { 13565 assert(ValidLoops.contains(AR->getLoop()) && 13566 "AddRec references invalid loop"); 13567 } 13568 #endif 13569 13570 // Check that the value is also part of the reverse map. 13571 auto It = ExprValueMap.find(KV.second); 13572 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) { 13573 dbgs() << "Value " << *KV.first 13574 << " is in ValueExprMap but not in ExprValueMap\n"; 13575 std::abort(); 13576 } 13577 13578 if (auto *I = dyn_cast<Instruction>(&*KV.first)) { 13579 if (!ReachableBlocks.contains(I->getParent())) 13580 continue; 13581 const SCEV *OldSCEV = SCM.visit(KV.second); 13582 const SCEV *NewSCEV = SE2.getSCEV(I); 13583 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV); 13584 if (Delta && !Delta->isZero()) { 13585 dbgs() << "SCEV for value " << *I << " changed!\n" 13586 << "Old: " << *OldSCEV << "\n" 13587 << "New: " << *NewSCEV << "\n" 13588 << "Delta: " << *Delta << "\n"; 13589 std::abort(); 13590 } 13591 } 13592 } 13593 13594 for (const auto &KV : ExprValueMap) { 13595 for (Value *V : KV.second) { 13596 auto It = ValueExprMap.find_as(V); 13597 if (It == ValueExprMap.end()) { 13598 dbgs() << "Value " << *V 13599 << " is in ExprValueMap but not in ValueExprMap\n"; 13600 std::abort(); 13601 } 13602 if (It->second != KV.first) { 13603 dbgs() << "Value " << *V << " mapped to " << *It->second 13604 << " rather than " << *KV.first << "\n"; 13605 std::abort(); 13606 } 13607 } 13608 } 13609 13610 // Verify integrity of SCEV users. 13611 for (const auto &S : UniqueSCEVs) { 13612 SmallVector<const SCEV *, 4> Ops; 13613 collectUniqueOps(&S, Ops); 13614 for (const auto *Op : Ops) { 13615 // We do not store dependencies of constants. 13616 if (isa<SCEVConstant>(Op)) 13617 continue; 13618 auto It = SCEVUsers.find(Op); 13619 if (It != SCEVUsers.end() && It->second.count(&S)) 13620 continue; 13621 dbgs() << "Use of operand " << *Op << " by user " << S 13622 << " is not being tracked!\n"; 13623 std::abort(); 13624 } 13625 } 13626 13627 // Verify integrity of ValuesAtScopes users. 13628 for (const auto &ValueAndVec : ValuesAtScopes) { 13629 const SCEV *Value = ValueAndVec.first; 13630 for (const auto &LoopAndValueAtScope : ValueAndVec.second) { 13631 const Loop *L = LoopAndValueAtScope.first; 13632 const SCEV *ValueAtScope = LoopAndValueAtScope.second; 13633 if (!isa<SCEVConstant>(ValueAtScope)) { 13634 auto It = ValuesAtScopesUsers.find(ValueAtScope); 13635 if (It != ValuesAtScopesUsers.end() && 13636 is_contained(It->second, std::make_pair(L, Value))) 13637 continue; 13638 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: " 13639 << *ValueAtScope << " missing in ValuesAtScopesUsers\n"; 13640 std::abort(); 13641 } 13642 } 13643 } 13644 13645 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) { 13646 const SCEV *ValueAtScope = ValueAtScopeAndVec.first; 13647 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) { 13648 const Loop *L = LoopAndValue.first; 13649 const SCEV *Value = LoopAndValue.second; 13650 assert(!isa<SCEVConstant>(Value)); 13651 auto It = ValuesAtScopes.find(Value); 13652 if (It != ValuesAtScopes.end() && 13653 is_contained(It->second, std::make_pair(L, ValueAtScope))) 13654 continue; 13655 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: " 13656 << *ValueAtScope << " missing in ValuesAtScopes\n"; 13657 std::abort(); 13658 } 13659 } 13660 13661 // Verify integrity of BECountUsers. 13662 auto VerifyBECountUsers = [&](bool Predicated) { 13663 auto &BECounts = 13664 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts; 13665 for (const auto &LoopAndBEInfo : BECounts) { 13666 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) { 13667 if (!isa<SCEVConstant>(ENT.ExactNotTaken)) { 13668 auto UserIt = BECountUsers.find(ENT.ExactNotTaken); 13669 if (UserIt != BECountUsers.end() && 13670 UserIt->second.contains({ LoopAndBEInfo.first, Predicated })) 13671 continue; 13672 dbgs() << "Value " << *ENT.ExactNotTaken << " for loop " 13673 << *LoopAndBEInfo.first << " missing from BECountUsers\n"; 13674 std::abort(); 13675 } 13676 } 13677 } 13678 }; 13679 VerifyBECountUsers(/* Predicated */ false); 13680 VerifyBECountUsers(/* Predicated */ true); 13681 } 13682 13683 bool ScalarEvolution::invalidate( 13684 Function &F, const PreservedAnalyses &PA, 13685 FunctionAnalysisManager::Invalidator &Inv) { 13686 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 13687 // of its dependencies is invalidated. 13688 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 13689 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 13690 Inv.invalidate<AssumptionAnalysis>(F, PA) || 13691 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 13692 Inv.invalidate<LoopAnalysis>(F, PA); 13693 } 13694 13695 AnalysisKey ScalarEvolutionAnalysis::Key; 13696 13697 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 13698 FunctionAnalysisManager &AM) { 13699 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 13700 AM.getResult<AssumptionAnalysis>(F), 13701 AM.getResult<DominatorTreeAnalysis>(F), 13702 AM.getResult<LoopAnalysis>(F)); 13703 } 13704 13705 PreservedAnalyses 13706 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 13707 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 13708 return PreservedAnalyses::all(); 13709 } 13710 13711 PreservedAnalyses 13712 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 13713 // For compatibility with opt's -analyze feature under legacy pass manager 13714 // which was not ported to NPM. This keeps tests using 13715 // update_analyze_test_checks.py working. 13716 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 13717 << F.getName() << "':\n"; 13718 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 13719 return PreservedAnalyses::all(); 13720 } 13721 13722 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 13723 "Scalar Evolution Analysis", false, true) 13724 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 13725 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 13726 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 13727 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 13728 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 13729 "Scalar Evolution Analysis", false, true) 13730 13731 char ScalarEvolutionWrapperPass::ID = 0; 13732 13733 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 13734 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 13735 } 13736 13737 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 13738 SE.reset(new ScalarEvolution( 13739 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 13740 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 13741 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 13742 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 13743 return false; 13744 } 13745 13746 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 13747 13748 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 13749 SE->print(OS); 13750 } 13751 13752 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 13753 if (!VerifySCEV) 13754 return; 13755 13756 SE->verify(); 13757 } 13758 13759 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 13760 AU.setPreservesAll(); 13761 AU.addRequiredTransitive<AssumptionCacheTracker>(); 13762 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 13763 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 13764 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 13765 } 13766 13767 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 13768 const SCEV *RHS) { 13769 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS); 13770 } 13771 13772 const SCEVPredicate * 13773 ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred, 13774 const SCEV *LHS, const SCEV *RHS) { 13775 FoldingSetNodeID ID; 13776 assert(LHS->getType() == RHS->getType() && 13777 "Type mismatch between LHS and RHS"); 13778 // Unique this node based on the arguments 13779 ID.AddInteger(SCEVPredicate::P_Compare); 13780 ID.AddInteger(Pred); 13781 ID.AddPointer(LHS); 13782 ID.AddPointer(RHS); 13783 void *IP = nullptr; 13784 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13785 return S; 13786 SCEVComparePredicate *Eq = new (SCEVAllocator) 13787 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS); 13788 UniquePreds.InsertNode(Eq, IP); 13789 return Eq; 13790 } 13791 13792 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 13793 const SCEVAddRecExpr *AR, 13794 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13795 FoldingSetNodeID ID; 13796 // Unique this node based on the arguments 13797 ID.AddInteger(SCEVPredicate::P_Wrap); 13798 ID.AddPointer(AR); 13799 ID.AddInteger(AddedFlags); 13800 void *IP = nullptr; 13801 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13802 return S; 13803 auto *OF = new (SCEVAllocator) 13804 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 13805 UniquePreds.InsertNode(OF, IP); 13806 return OF; 13807 } 13808 13809 namespace { 13810 13811 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 13812 public: 13813 13814 /// Rewrites \p S in the context of a loop L and the SCEV predication 13815 /// infrastructure. 13816 /// 13817 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 13818 /// equivalences present in \p Pred. 13819 /// 13820 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 13821 /// \p NewPreds such that the result will be an AddRecExpr. 13822 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 13823 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13824 const SCEVPredicate *Pred) { 13825 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 13826 return Rewriter.visit(S); 13827 } 13828 13829 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13830 if (Pred) { 13831 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) { 13832 for (auto *Pred : U->getPredicates()) 13833 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) 13834 if (IPred->getLHS() == Expr && 13835 IPred->getPredicate() == ICmpInst::ICMP_EQ) 13836 return IPred->getRHS(); 13837 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) { 13838 if (IPred->getLHS() == Expr && 13839 IPred->getPredicate() == ICmpInst::ICMP_EQ) 13840 return IPred->getRHS(); 13841 } 13842 } 13843 return convertToAddRecWithPreds(Expr); 13844 } 13845 13846 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 13847 const SCEV *Operand = visit(Expr->getOperand()); 13848 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13849 if (AR && AR->getLoop() == L && AR->isAffine()) { 13850 // This couldn't be folded because the operand didn't have the nuw 13851 // flag. Add the nusw flag as an assumption that we could make. 13852 const SCEV *Step = AR->getStepRecurrence(SE); 13853 Type *Ty = Expr->getType(); 13854 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 13855 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 13856 SE.getSignExtendExpr(Step, Ty), L, 13857 AR->getNoWrapFlags()); 13858 } 13859 return SE.getZeroExtendExpr(Operand, Expr->getType()); 13860 } 13861 13862 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 13863 const SCEV *Operand = visit(Expr->getOperand()); 13864 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13865 if (AR && AR->getLoop() == L && AR->isAffine()) { 13866 // This couldn't be folded because the operand didn't have the nsw 13867 // flag. Add the nssw flag as an assumption that we could make. 13868 const SCEV *Step = AR->getStepRecurrence(SE); 13869 Type *Ty = Expr->getType(); 13870 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 13871 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 13872 SE.getSignExtendExpr(Step, Ty), L, 13873 AR->getNoWrapFlags()); 13874 } 13875 return SE.getSignExtendExpr(Operand, Expr->getType()); 13876 } 13877 13878 private: 13879 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 13880 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13881 const SCEVPredicate *Pred) 13882 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 13883 13884 bool addOverflowAssumption(const SCEVPredicate *P) { 13885 if (!NewPreds) { 13886 // Check if we've already made this assumption. 13887 return Pred && Pred->implies(P); 13888 } 13889 NewPreds->insert(P); 13890 return true; 13891 } 13892 13893 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 13894 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13895 auto *A = SE.getWrapPredicate(AR, AddedFlags); 13896 return addOverflowAssumption(A); 13897 } 13898 13899 // If \p Expr represents a PHINode, we try to see if it can be represented 13900 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 13901 // to add this predicate as a runtime overflow check, we return the AddRec. 13902 // If \p Expr does not meet these conditions (is not a PHI node, or we 13903 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13904 // return \p Expr. 13905 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13906 if (!isa<PHINode>(Expr->getValue())) 13907 return Expr; 13908 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13909 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13910 if (!PredicatedRewrite) 13911 return Expr; 13912 for (auto *P : PredicatedRewrite->second){ 13913 // Wrap predicates from outer loops are not supported. 13914 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13915 if (L != WP->getExpr()->getLoop()) 13916 return Expr; 13917 } 13918 if (!addOverflowAssumption(P)) 13919 return Expr; 13920 } 13921 return PredicatedRewrite->first; 13922 } 13923 13924 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13925 const SCEVPredicate *Pred; 13926 const Loop *L; 13927 }; 13928 13929 } // end anonymous namespace 13930 13931 const SCEV * 13932 ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13933 const SCEVPredicate &Preds) { 13934 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13935 } 13936 13937 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13938 const SCEV *S, const Loop *L, 13939 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13940 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13941 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13942 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13943 13944 if (!AddRec) 13945 return nullptr; 13946 13947 // Since the transformation was successful, we can now transfer the SCEV 13948 // predicates. 13949 for (auto *P : TransformPreds) 13950 Preds.insert(P); 13951 13952 return AddRec; 13953 } 13954 13955 /// SCEV predicates 13956 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13957 SCEVPredicateKind Kind) 13958 : FastID(ID), Kind(Kind) {} 13959 13960 SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID, 13961 const ICmpInst::Predicate Pred, 13962 const SCEV *LHS, const SCEV *RHS) 13963 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) { 13964 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13965 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13966 } 13967 13968 bool SCEVComparePredicate::implies(const SCEVPredicate *N) const { 13969 const auto *Op = dyn_cast<SCEVComparePredicate>(N); 13970 13971 if (!Op) 13972 return false; 13973 13974 if (Pred != ICmpInst::ICMP_EQ) 13975 return false; 13976 13977 return Op->LHS == LHS && Op->RHS == RHS; 13978 } 13979 13980 bool SCEVComparePredicate::isAlwaysTrue() const { return false; } 13981 13982 void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const { 13983 if (Pred == ICmpInst::ICMP_EQ) 13984 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13985 else 13986 OS.indent(Depth) << "Compare predicate: " << *LHS 13987 << " " << CmpInst::getPredicateName(Pred) << ") " 13988 << *RHS << "\n"; 13989 13990 } 13991 13992 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13993 const SCEVAddRecExpr *AR, 13994 IncrementWrapFlags Flags) 13995 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13996 13997 const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; } 13998 13999 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 14000 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 14001 14002 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 14003 } 14004 14005 bool SCEVWrapPredicate::isAlwaysTrue() const { 14006 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 14007 IncrementWrapFlags IFlags = Flags; 14008 14009 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 14010 IFlags = clearFlags(IFlags, IncrementNSSW); 14011 14012 return IFlags == IncrementAnyWrap; 14013 } 14014 14015 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 14016 OS.indent(Depth) << *getExpr() << " Added Flags: "; 14017 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 14018 OS << "<nusw>"; 14019 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 14020 OS << "<nssw>"; 14021 OS << "\n"; 14022 } 14023 14024 SCEVWrapPredicate::IncrementWrapFlags 14025 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 14026 ScalarEvolution &SE) { 14027 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 14028 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 14029 14030 // We can safely transfer the NSW flag as NSSW. 14031 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 14032 ImpliedFlags = IncrementNSSW; 14033 14034 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 14035 // If the increment is positive, the SCEV NUW flag will also imply the 14036 // WrapPredicate NUSW flag. 14037 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 14038 if (Step->getValue()->getValue().isNonNegative()) 14039 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 14040 } 14041 14042 return ImpliedFlags; 14043 } 14044 14045 /// Union predicates don't get cached so create a dummy set ID for it. 14046 SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds) 14047 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) { 14048 for (auto *P : Preds) 14049 add(P); 14050 } 14051 14052 bool SCEVUnionPredicate::isAlwaysTrue() const { 14053 return all_of(Preds, 14054 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 14055 } 14056 14057 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 14058 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 14059 return all_of(Set->Preds, 14060 [this](const SCEVPredicate *I) { return this->implies(I); }); 14061 14062 return any_of(Preds, 14063 [N](const SCEVPredicate *I) { return I->implies(N); }); 14064 } 14065 14066 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 14067 for (auto Pred : Preds) 14068 Pred->print(OS, Depth); 14069 } 14070 14071 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 14072 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 14073 for (auto Pred : Set->Preds) 14074 add(Pred); 14075 return; 14076 } 14077 14078 Preds.push_back(N); 14079 } 14080 14081 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 14082 Loop &L) 14083 : SE(SE), L(L) { 14084 SmallVector<const SCEVPredicate*, 4> Empty; 14085 Preds = std::make_unique<SCEVUnionPredicate>(Empty); 14086 } 14087 14088 void ScalarEvolution::registerUser(const SCEV *User, 14089 ArrayRef<const SCEV *> Ops) { 14090 for (auto *Op : Ops) 14091 // We do not expect that forgetting cached data for SCEVConstants will ever 14092 // open any prospects for sharpening or introduce any correctness issues, 14093 // so we don't bother storing their dependencies. 14094 if (!isa<SCEVConstant>(Op)) 14095 SCEVUsers[Op].insert(User); 14096 } 14097 14098 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 14099 const SCEV *Expr = SE.getSCEV(V); 14100 RewriteEntry &Entry = RewriteMap[Expr]; 14101 14102 // If we already have an entry and the version matches, return it. 14103 if (Entry.second && Generation == Entry.first) 14104 return Entry.second; 14105 14106 // We found an entry but it's stale. Rewrite the stale entry 14107 // according to the current predicate. 14108 if (Entry.second) 14109 Expr = Entry.second; 14110 14111 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds); 14112 Entry = {Generation, NewSCEV}; 14113 14114 return NewSCEV; 14115 } 14116 14117 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 14118 if (!BackedgeCount) { 14119 SmallVector<const SCEVPredicate *, 4> Preds; 14120 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds); 14121 for (auto *P : Preds) 14122 addPredicate(*P); 14123 } 14124 return BackedgeCount; 14125 } 14126 14127 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 14128 if (Preds->implies(&Pred)) 14129 return; 14130 14131 auto &OldPreds = Preds->getPredicates(); 14132 SmallVector<const SCEVPredicate*, 4> NewPreds(OldPreds.begin(), OldPreds.end()); 14133 NewPreds.push_back(&Pred); 14134 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds); 14135 updateGeneration(); 14136 } 14137 14138 const SCEVPredicate &PredicatedScalarEvolution::getPredicate() const { 14139 return *Preds; 14140 } 14141 14142 void PredicatedScalarEvolution::updateGeneration() { 14143 // If the generation number wrapped recompute everything. 14144 if (++Generation == 0) { 14145 for (auto &II : RewriteMap) { 14146 const SCEV *Rewritten = II.second.second; 14147 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)}; 14148 } 14149 } 14150 } 14151 14152 void PredicatedScalarEvolution::setNoOverflow( 14153 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 14154 const SCEV *Expr = getSCEV(V); 14155 const auto *AR = cast<SCEVAddRecExpr>(Expr); 14156 14157 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 14158 14159 // Clear the statically implied flags. 14160 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 14161 addPredicate(*SE.getWrapPredicate(AR, Flags)); 14162 14163 auto II = FlagsMap.insert({V, Flags}); 14164 if (!II.second) 14165 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 14166 } 14167 14168 bool PredicatedScalarEvolution::hasNoOverflow( 14169 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 14170 const SCEV *Expr = getSCEV(V); 14171 const auto *AR = cast<SCEVAddRecExpr>(Expr); 14172 14173 Flags = SCEVWrapPredicate::clearFlags( 14174 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 14175 14176 auto II = FlagsMap.find(V); 14177 14178 if (II != FlagsMap.end()) 14179 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 14180 14181 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 14182 } 14183 14184 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 14185 const SCEV *Expr = this->getSCEV(V); 14186 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 14187 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 14188 14189 if (!New) 14190 return nullptr; 14191 14192 for (auto *P : NewPreds) 14193 addPredicate(*P); 14194 14195 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 14196 return New; 14197 } 14198 14199 PredicatedScalarEvolution::PredicatedScalarEvolution( 14200 const PredicatedScalarEvolution &Init) 14201 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), 14202 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates())), 14203 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 14204 for (auto I : Init.FlagsMap) 14205 FlagsMap.insert(I); 14206 } 14207 14208 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 14209 // For each block. 14210 for (auto *BB : L.getBlocks()) 14211 for (auto &I : *BB) { 14212 if (!SE.isSCEVable(I.getType())) 14213 continue; 14214 14215 auto *Expr = SE.getSCEV(&I); 14216 auto II = RewriteMap.find(Expr); 14217 14218 if (II == RewriteMap.end()) 14219 continue; 14220 14221 // Don't print things that are not interesting. 14222 if (II->second.second == Expr) 14223 continue; 14224 14225 OS.indent(Depth) << "[PSE]" << I << ":\n"; 14226 OS.indent(Depth + 2) << *Expr << "\n"; 14227 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 14228 } 14229 } 14230 14231 // Match the mathematical pattern A - (A / B) * B, where A and B can be 14232 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 14233 // for URem with constant power-of-2 second operands. 14234 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 14235 // 4, A / B becomes X / 8). 14236 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 14237 const SCEV *&RHS) { 14238 // Try to match 'zext (trunc A to iB) to iY', which is used 14239 // for URem with constant power-of-2 second operands. Make sure the size of 14240 // the operand A matches the size of the whole expressions. 14241 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 14242 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 14243 LHS = Trunc->getOperand(); 14244 // Bail out if the type of the LHS is larger than the type of the 14245 // expression for now. 14246 if (getTypeSizeInBits(LHS->getType()) > 14247 getTypeSizeInBits(Expr->getType())) 14248 return false; 14249 if (LHS->getType() != Expr->getType()) 14250 LHS = getZeroExtendExpr(LHS, Expr->getType()); 14251 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 14252 << getTypeSizeInBits(Trunc->getType())); 14253 return true; 14254 } 14255 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 14256 if (Add == nullptr || Add->getNumOperands() != 2) 14257 return false; 14258 14259 const SCEV *A = Add->getOperand(1); 14260 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 14261 14262 if (Mul == nullptr) 14263 return false; 14264 14265 const auto MatchURemWithDivisor = [&](const SCEV *B) { 14266 // (SomeExpr + (-(SomeExpr / B) * B)). 14267 if (Expr == getURemExpr(A, B)) { 14268 LHS = A; 14269 RHS = B; 14270 return true; 14271 } 14272 return false; 14273 }; 14274 14275 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 14276 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 14277 return MatchURemWithDivisor(Mul->getOperand(1)) || 14278 MatchURemWithDivisor(Mul->getOperand(2)); 14279 14280 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 14281 if (Mul->getNumOperands() == 2) 14282 return MatchURemWithDivisor(Mul->getOperand(1)) || 14283 MatchURemWithDivisor(Mul->getOperand(0)) || 14284 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 14285 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 14286 return false; 14287 } 14288 14289 const SCEV * 14290 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 14291 SmallVector<BasicBlock*, 16> ExitingBlocks; 14292 L->getExitingBlocks(ExitingBlocks); 14293 14294 // Form an expression for the maximum exit count possible for this loop. We 14295 // merge the max and exact information to approximate a version of 14296 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 14297 SmallVector<const SCEV*, 4> ExitCounts; 14298 for (BasicBlock *ExitingBB : ExitingBlocks) { 14299 const SCEV *ExitCount = getExitCount(L, ExitingBB); 14300 if (isa<SCEVCouldNotCompute>(ExitCount)) 14301 ExitCount = getExitCount(L, ExitingBB, 14302 ScalarEvolution::ConstantMaximum); 14303 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 14304 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 14305 "We should only have known counts for exiting blocks that " 14306 "dominate latch!"); 14307 ExitCounts.push_back(ExitCount); 14308 } 14309 } 14310 if (ExitCounts.empty()) 14311 return getCouldNotCompute(); 14312 return getUMinFromMismatchedTypes(ExitCounts); 14313 } 14314 14315 /// A rewriter to replace SCEV expressions in Map with the corresponding entry 14316 /// in the map. It skips AddRecExpr because we cannot guarantee that the 14317 /// replacement is loop invariant in the loop of the AddRec. 14318 /// 14319 /// At the moment only rewriting SCEVUnknown and SCEVZeroExtendExpr is 14320 /// supported. 14321 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 14322 const DenseMap<const SCEV *, const SCEV *> ⤅ 14323 14324 public: 14325 SCEVLoopGuardRewriter(ScalarEvolution &SE, 14326 DenseMap<const SCEV *, const SCEV *> &M) 14327 : SCEVRewriteVisitor(SE), Map(M) {} 14328 14329 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 14330 14331 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 14332 auto I = Map.find(Expr); 14333 if (I == Map.end()) 14334 return Expr; 14335 return I->second; 14336 } 14337 14338 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 14339 auto I = Map.find(Expr); 14340 if (I == Map.end()) 14341 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr( 14342 Expr); 14343 return I->second; 14344 } 14345 }; 14346 14347 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 14348 SmallVector<const SCEV *> ExprsToRewrite; 14349 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 14350 const SCEV *RHS, 14351 DenseMap<const SCEV *, const SCEV *> 14352 &RewriteMap) { 14353 // WARNING: It is generally unsound to apply any wrap flags to the proposed 14354 // replacement SCEV which isn't directly implied by the structure of that 14355 // SCEV. In particular, using contextual facts to imply flags is *NOT* 14356 // legal. See the scoping rules for flags in the header to understand why. 14357 14358 // If LHS is a constant, apply information to the other expression. 14359 if (isa<SCEVConstant>(LHS)) { 14360 std::swap(LHS, RHS); 14361 Predicate = CmpInst::getSwappedPredicate(Predicate); 14362 } 14363 14364 // Check for a condition of the form (-C1 + X < C2). InstCombine will 14365 // create this form when combining two checks of the form (X u< C2 + C1) and 14366 // (X >=u C1). 14367 auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap, 14368 &ExprsToRewrite]() { 14369 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS); 14370 if (!AddExpr || AddExpr->getNumOperands() != 2) 14371 return false; 14372 14373 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0)); 14374 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1)); 14375 auto *C2 = dyn_cast<SCEVConstant>(RHS); 14376 if (!C1 || !C2 || !LHSUnknown) 14377 return false; 14378 14379 auto ExactRegion = 14380 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt()) 14381 .sub(C1->getAPInt()); 14382 14383 // Bail out, unless we have a non-wrapping, monotonic range. 14384 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet()) 14385 return false; 14386 auto I = RewriteMap.find(LHSUnknown); 14387 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown; 14388 RewriteMap[LHSUnknown] = getUMaxExpr( 14389 getConstant(ExactRegion.getUnsignedMin()), 14390 getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax()))); 14391 ExprsToRewrite.push_back(LHSUnknown); 14392 return true; 14393 }; 14394 if (MatchRangeCheckIdiom()) 14395 return; 14396 14397 // If we have LHS == 0, check if LHS is computing a property of some unknown 14398 // SCEV %v which we can rewrite %v to express explicitly. 14399 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 14400 if (Predicate == CmpInst::ICMP_EQ && RHSC && 14401 RHSC->getValue()->isNullValue()) { 14402 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 14403 // explicitly express that. 14404 const SCEV *URemLHS = nullptr; 14405 const SCEV *URemRHS = nullptr; 14406 if (matchURem(LHS, URemLHS, URemRHS)) { 14407 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 14408 auto Multiple = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS); 14409 RewriteMap[LHSUnknown] = Multiple; 14410 ExprsToRewrite.push_back(LHSUnknown); 14411 return; 14412 } 14413 } 14414 } 14415 14416 // Do not apply information for constants or if RHS contains an AddRec. 14417 if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS)) 14418 return; 14419 14420 // If RHS is SCEVUnknown, make sure the information is applied to it. 14421 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) { 14422 std::swap(LHS, RHS); 14423 Predicate = CmpInst::getSwappedPredicate(Predicate); 14424 } 14425 14426 // Limit to expressions that can be rewritten. 14427 if (!isa<SCEVUnknown>(LHS) && !isa<SCEVZeroExtendExpr>(LHS)) 14428 return; 14429 14430 // Check whether LHS has already been rewritten. In that case we want to 14431 // chain further rewrites onto the already rewritten value. 14432 auto I = RewriteMap.find(LHS); 14433 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 14434 14435 const SCEV *RewrittenRHS = nullptr; 14436 switch (Predicate) { 14437 case CmpInst::ICMP_ULT: 14438 RewrittenRHS = 14439 getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 14440 break; 14441 case CmpInst::ICMP_SLT: 14442 RewrittenRHS = 14443 getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 14444 break; 14445 case CmpInst::ICMP_ULE: 14446 RewrittenRHS = getUMinExpr(RewrittenLHS, RHS); 14447 break; 14448 case CmpInst::ICMP_SLE: 14449 RewrittenRHS = getSMinExpr(RewrittenLHS, RHS); 14450 break; 14451 case CmpInst::ICMP_UGT: 14452 RewrittenRHS = 14453 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 14454 break; 14455 case CmpInst::ICMP_SGT: 14456 RewrittenRHS = 14457 getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 14458 break; 14459 case CmpInst::ICMP_UGE: 14460 RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS); 14461 break; 14462 case CmpInst::ICMP_SGE: 14463 RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS); 14464 break; 14465 case CmpInst::ICMP_EQ: 14466 if (isa<SCEVConstant>(RHS)) 14467 RewrittenRHS = RHS; 14468 break; 14469 case CmpInst::ICMP_NE: 14470 if (isa<SCEVConstant>(RHS) && 14471 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 14472 RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 14473 break; 14474 default: 14475 break; 14476 } 14477 14478 if (RewrittenRHS) { 14479 RewriteMap[LHS] = RewrittenRHS; 14480 if (LHS == RewrittenLHS) 14481 ExprsToRewrite.push_back(LHS); 14482 } 14483 }; 14484 // First, collect conditions from dominating branches. Starting at the loop 14485 // predecessor, climb up the predecessor chain, as long as there are 14486 // predecessors that can be found that have unique successors leading to the 14487 // original header. 14488 // TODO: share this logic with isLoopEntryGuardedByCond. 14489 SmallVector<std::pair<Value *, bool>> Terms; 14490 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 14491 L->getLoopPredecessor(), L->getHeader()); 14492 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 14493 14494 const BranchInst *LoopEntryPredicate = 14495 dyn_cast<BranchInst>(Pair.first->getTerminator()); 14496 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 14497 continue; 14498 14499 Terms.emplace_back(LoopEntryPredicate->getCondition(), 14500 LoopEntryPredicate->getSuccessor(0) == Pair.second); 14501 } 14502 14503 // Now apply the information from the collected conditions to RewriteMap. 14504 // Conditions are processed in reverse order, so the earliest conditions is 14505 // processed first. This ensures the SCEVs with the shortest dependency chains 14506 // are constructed first. 14507 DenseMap<const SCEV *, const SCEV *> RewriteMap; 14508 for (auto &E : reverse(Terms)) { 14509 bool EnterIfTrue = E.second; 14510 SmallVector<Value *, 8> Worklist; 14511 SmallPtrSet<Value *, 8> Visited; 14512 Worklist.push_back(E.first); 14513 while (!Worklist.empty()) { 14514 Value *Cond = Worklist.pop_back_val(); 14515 if (!Visited.insert(Cond).second) 14516 continue; 14517 14518 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 14519 auto Predicate = 14520 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 14521 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 14522 getSCEV(Cmp->getOperand(1)), RewriteMap); 14523 continue; 14524 } 14525 14526 Value *L, *R; 14527 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 14528 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 14529 Worklist.push_back(L); 14530 Worklist.push_back(R); 14531 } 14532 } 14533 } 14534 14535 // Also collect information from assumptions dominating the loop. 14536 for (auto &AssumeVH : AC.assumptions()) { 14537 if (!AssumeVH) 14538 continue; 14539 auto *AssumeI = cast<CallInst>(AssumeVH); 14540 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 14541 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 14542 continue; 14543 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 14544 getSCEV(Cmp->getOperand(1)), RewriteMap); 14545 } 14546 14547 if (RewriteMap.empty()) 14548 return Expr; 14549 14550 // Now that all rewrite information is collect, rewrite the collected 14551 // expressions with the information in the map. This applies information to 14552 // sub-expressions. 14553 if (ExprsToRewrite.size() > 1) { 14554 for (const SCEV *Expr : ExprsToRewrite) { 14555 const SCEV *RewriteTo = RewriteMap[Expr]; 14556 RewriteMap.erase(Expr); 14557 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 14558 RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)}); 14559 } 14560 } 14561 14562 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 14563 return Rewriter.visit(Expr); 14564 } 14565